diff --git a/README.md b/README.md index 4dfcf2e..5ff029d 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,8 @@ client }); ``` +WebSocket TestNet: set `useTestnet: true` on `WebsocketClient`. + See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets diff --git a/docs/GATE_SDK_QUICKSTART_GUIDE.md b/docs/GATE_SDK_QUICKSTART_GUIDE.md index 5aaf489..1de6cb3 100644 --- a/docs/GATE_SDK_QUICKSTART_GUIDE.md +++ b/docs/GATE_SDK_QUICKSTART_GUIDE.md @@ -1738,11 +1738,9 @@ Gate TestNet is a separate environment with separate credentials. Use it for all | REST API | `https://api-testnet.gateapi.io/api/v4` | | Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | | USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | -Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: - -- Spot WebSocket TestNet is not wired through `useTestnet: true` in this SDK. The Spot testnet map entry is a stub (`NoTestnetForSpotWebsockets!`), so set `wsUrl` to the Spot TestNet host above. -- For Futures-only REST TestNet, the SDK also accepts `baseUrlKey: 'futuresTestnet'`, which resolves to `https://fx-api-testnet.gateio.ws/api/v4`. The Global TestNet REST host in the table is the host used by the Spot and Futures order examples in this guide. +For WebSocket TestNet, set `useTestnet: true`. ```javascript import { RestClient, WebsocketClient } from 'gateio-api'; @@ -1756,7 +1754,7 @@ const rest = new RestClient({ const spotWs = new WebsocketClient({ apiKey: process.env.GATE_TESTNET_API_KEY, apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', + useTestnet: true, }); ``` diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index efece8f..ea6ec2e 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -49,454 +49,454 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L711) | | GET | `/v1/public/system_info` | -| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L715) | | POST | `/ann/list_article` | -| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L734) | :closed_lock_with_key: | POST | `/withdrawals` | -| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L748) | :closed_lock_with_key: | POST | `/withdrawals/push` | -| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L764) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | -| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L781) | | GET | `/wallet/currency_chains` | -| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L791) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | -| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L805) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | -| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L819) | :closed_lock_with_key: | GET | `/wallet/deposits` | -| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L838) | :closed_lock_with_key: | POST | `/wallet/transfers` | -| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L850) | :closed_lock_with_key: | GET | `/wallet/transfers` | -| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L862) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | -| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L876) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | -| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L890) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | -| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L905) | :closed_lock_with_key: | GET | `/wallet/order_status` | -| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L921) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | -| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L933) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | -| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L945) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | -| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L957) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | -| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L970) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | -| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L982) | :closed_lock_with_key: | GET | `/wallet/saved_address` | -| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L992) | :closed_lock_with_key: | GET | `/wallet/fee` | -| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1013) | :closed_lock_with_key: | GET | `/wallet/total_balance` | -| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1022) | :closed_lock_with_key: | GET | `/wallet/small_balance` | -| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1032) | :closed_lock_with_key: | POST | `/wallet/small_balance` | -| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1045) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | -| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1057) | :closed_lock_with_key: | GET | `/wallet/push` | -| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1066) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | -| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1081) | :closed_lock_with_key: | POST | `/sub_accounts` | -| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1092) | :closed_lock_with_key: | GET | `/sub_accounts` | -| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1102) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | -| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1112) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | -| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1125) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | -| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1139) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | -| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1150) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | -| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1165) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | -| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1180) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | -| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1190) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | -| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1204) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | -| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1223) | :closed_lock_with_key: | GET | `/unified/accounts` | -| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1239) | :closed_lock_with_key: | GET | `/unified/borrowable` | -| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1255) | :closed_lock_with_key: | GET | `/unified/transferable` | -| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1270) | :closed_lock_with_key: | GET | `/unified/transferables` | -| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1279) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | -| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1297) | :closed_lock_with_key: | POST | `/unified/loans` | -| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1309) | :closed_lock_with_key: | GET | `/unified/loans` | -| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1319) | :closed_lock_with_key: | GET | `/unified/loan_records` | -| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1331) | :closed_lock_with_key: | GET | `/unified/interest_records` | -| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1342) | :closed_lock_with_key: | GET | `/unified/risk_units` | -| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1354) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | -| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1363) | :closed_lock_with_key: | GET | `/unified/unified_mode` | -| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1375) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | -| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1386) | | GET | `/unified/currency_discount_tiers` | -| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1398) | | GET | `/unified/loan_margin_tiers` | -| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1415) | | POST | `/unified/portfolio_calculator` | -| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1429) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | -| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1443) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | -| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1457) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | -| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1472) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | -| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1487) | :closed_lock_with_key: | GET | `/unified/currencies` | -| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1499) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | -| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1505) | :closed_lock_with_key: | POST | `/unified/loans/repay` | -| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1512) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | -| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1519) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | -| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1530) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | -| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1539) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | -| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1559) | | GET | `/spot/currencies` | -| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1569) | | GET | `/spot/currencies/{currency}` | -| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1578) | | GET | `/spot/currency_pairs` | -| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1588) | | GET | `/spot/currency_pairs/{currency_pair}` | -| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1602) | | GET | `/spot/tickers` | -| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1617) | | GET | `/spot/order_book` | -| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1630) | | GET | `/spot/trades` | -| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1642) | | GET | `/spot/candlesticks` | -| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1654) | :closed_lock_with_key: | GET | `/spot/fee` | -| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1663) | :closed_lock_with_key: | GET | `/spot/batch_fee` | -| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1675) | :closed_lock_with_key: | GET | `/spot/accounts` | -| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1687) | :closed_lock_with_key: | GET | `/spot/account_book` | -| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1706) | :closed_lock_with_key: | POST | `/spot/batch_orders` | -| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1733) | :closed_lock_with_key: | GET | `/spot/open_orders` | -| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1749) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | -| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1765) | :closed_lock_with_key: | POST | `/spot/orders` | -| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1782) | :closed_lock_with_key: | GET | `/spot/orders` | -| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1797) | :closed_lock_with_key: | DELETE | `/spot/orders` | -| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1826) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | -| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1851) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | -| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1868) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | -| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1896) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | -| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1925) | :closed_lock_with_key: | GET | `/spot/my_trades` | -| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1954) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | -| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1973) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | -| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2000) | :closed_lock_with_key: | GET | `/spot/insurance_history` | -| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2014) | :closed_lock_with_key: | POST | `/spot/price_orders` | -| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2026) | :closed_lock_with_key: | GET | `/spot/price_orders` | -| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2038) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | -| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2051) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | -| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2063) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | -| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2077) | :closed_lock_with_key: | GET | `/spot/pov_orders` | -| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2089) | :closed_lock_with_key: | POST | `/spot/pov_orders` | -| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2101) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | -| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2115) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | -| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2127) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | -| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2139) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | -| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2160) | :closed_lock_with_key: | GET | `/margin/accounts` | -| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2174) | :closed_lock_with_key: | GET | `/margin/account_book` | -| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2192) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | -| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2210) | :closed_lock_with_key: | POST | `/margin/auto_repay` | -| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2221) | :closed_lock_with_key: | GET | `/margin/auto_repay` | -| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2235) | :closed_lock_with_key: | GET | `/margin/transferable` | -| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2252) | | GET | `/margin/cross/currencies` | -| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2263) | | GET | `/margin/cross/currencies/{currency}` | -| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2275) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | -| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2288) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | -| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2305) | :closed_lock_with_key: | POST | `/margin/cross/loans` | -| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2320) | :closed_lock_with_key: | GET | `/margin/cross/loans` | -| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2333) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | -| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2348) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | -| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2364) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | -| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2377) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | -| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2393) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | -| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2409) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | -| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2423) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | -| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2436) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | -| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2452) | | GET | `/margin/loan_margin_tiers` | -| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2468) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | -| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2485) | :closed_lock_with_key: | GET | `/margin/user/account` | -| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2500) | | GET | `/margin/uni/currency_pairs` | -| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2515) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | -| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2527) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | -| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2537) | :closed_lock_with_key: | POST | `/margin/uni/loans` | -| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2553) | :closed_lock_with_key: | GET | `/margin/uni/loans` | -| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2563) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | -| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2575) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | -| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2587) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | -| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2603) | | GET | `/flash_swap/currency_pairs` | -| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2619) | :closed_lock_with_key: | POST | `/flash_swap/orders` | -| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2631) | :closed_lock_with_key: | GET | `/flash_swap/orders` | -| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2643) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | -| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2653) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | -| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2670) | | GET | `/futures/{settle}/contracts` | -| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2685) | | GET | `/futures/{settle}/contracts/{contract}` | -| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2692) | | GET | `/futures/{settle}/adl_risk_states` | -| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2706) | | GET | `/futures/{settle}/order_book` | -| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2719) | | GET | `/futures/{settle}/trades` | -| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2734) | | GET | `/futures/{settle}/candlesticks` | -| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2747) | | GET | `/futures/{settle}/premium_index` | -| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2760) | | GET | `/futures/{settle}/tickers` | -| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2777) | | GET | `/futures/{settle}/funding_rate` | -| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2793) | | POST | `/futures/{settle}/funding_rates` | -| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2811) | | GET | `/futures/{settle}/insurance` | -| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2830) | | GET | `/futures/{settle}/contract_stats` | -| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2841) | | GET | `/futures/{settle}/index_constituents/{index}` | -| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2858) | | GET | `/futures/{settle}/liq_orders` | -| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2875) | | GET | `/futures/{settle}/risk_limit_tiers` | -| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2888) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | -| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2902) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | -| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2915) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | -| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2930) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | -| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2947) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | -| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2975) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | -| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2995) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | -| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3011) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | -| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3028) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | -| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3048) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | -| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3064) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | -| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3079) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | -| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3095) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | -| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3119) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | -| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3146) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | -| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3167) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | -| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3182) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | -| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3202) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | -| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3225) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | -| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3250) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | -| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3267) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | -| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3292) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | -| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3313) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | -| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3328) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | -| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3341) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | -| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3354) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | -| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3367) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | -| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3384) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | -| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3401) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | -| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3419) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | -| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3446) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | -| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3468) | | GET | `/futures/{settle}/risk_limit_table` | -| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3481) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | -| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3494) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | -| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3507) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | -| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3523) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | -| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3538) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | -| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3553) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend` | -| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3568) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | -| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3586) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | -| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3599) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | -| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3614) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | -| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3627) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | -| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3645) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | -| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3658) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | -| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3671) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | -| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3681) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | -| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3691) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | -| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3703) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | -| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3711) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | -| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3720) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | -| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3729) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | -| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3746) | | GET | `/delivery/{settle}/contracts` | -| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3758) | | GET | `/delivery/{settle}/contracts/{contract}` | -| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3773) | | GET | `/delivery/{settle}/order_book` | -| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3786) | | GET | `/delivery/{settle}/trades` | -| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3800) | | GET | `/delivery/{settle}/candlesticks` | -| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3811) | | GET | `/delivery/{settle}/tickers` | -| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3828) | | GET | `/delivery/{settle}/insurance` | -| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3847) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | -| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3858) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | -| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3869) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | -| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3879) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | -| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3894) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | -| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3912) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | -| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3930) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | -| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3950) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | -| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3965) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | -| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3978) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | -| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3997) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | -| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4012) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | -| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4027) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | -| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4040) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | -| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4053) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | -| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4066) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | -| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4079) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | -| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4094) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | -| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4107) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | -| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4123) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | -| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4138) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | -| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4157) | | GET | `/options/underlyings` | -| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4167) | | GET | `/options/expirations` | -| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4177) | | GET | `/options/contracts` | -| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4190) | | GET | `/options/contracts/{contract}` | -| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4200) | | GET | `/options/settlements` | -| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4212) | | GET | `/options/settlements/{contract}` | -| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4227) | :closed_lock_with_key: | GET | `/options/my_settlements` | -| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4241) | | GET | `/options/order_book` | -| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4253) | | GET | `/options/tickers` | -| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4267) | | GET | `/options/underlying/tickers/{underlying}` | -| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4281) | | GET | `/options/candlesticks` | -| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4291) | | GET | `/options/underlying/candlesticks` | -| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4303) | | GET | `/options/trades` | -| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4314) | :closed_lock_with_key: | GET | `/options/accounts` | -| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4324) | :closed_lock_with_key: | GET | `/options/account_book` | -| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4336) | :closed_lock_with_key: | GET | `/options/positions` | -| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4348) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | -| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4360) | :closed_lock_with_key: | GET | `/options/position_close` | -| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4373) | :closed_lock_with_key: | POST | `/options/orders` | -| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4385) | :closed_lock_with_key: | GET | `/options/orders` | -| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4397) | :closed_lock_with_key: | DELETE | `/options/orders` | -| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4411) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | -| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4423) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | -| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4438) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | -| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4457) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | -| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4473) | :closed_lock_with_key: | GET | `/options/my_trades` | -| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4485) | :closed_lock_with_key: | POST | `/options/mmp` | -| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4497) | :closed_lock_with_key: | GET | `/options/mmp` | -| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4509) | :closed_lock_with_key: | POST | `/options/mmp/reset` | -| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4525) | | GET | `/earn/uni/currencies` | -| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4535) | | GET | `/earn/uni/currencies/{currency}` | -| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4545) | :closed_lock_with_key: | POST | `/earn/uni/lends` | -| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4555) | :closed_lock_with_key: | GET | `/earn/uni/lends` | -| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4567) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | -| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4580) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | -| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4593) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | -| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4606) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | -| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4619) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | -| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4635) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | -| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4650) | :closed_lock_with_key: | GET | `/earn/uni/chart` | -| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4658) | :closed_lock_with_key: | GET | `/earn/uni/rate` | -| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4675) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | -| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4687) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | -| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4699) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | -| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4709) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | -| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4719) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | -| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4731) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | -| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4743) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | -| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4755) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | -| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4767) | | GET | `/loan/multi_collateral/currencies` | -| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4776) | | GET | `/loan/multi_collateral/ltv` | -| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4785) | | GET | `/loan/multi_collateral/fixed_rate` | -| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4798) | | GET | `/loan/multi_collateral/current_rate` | -| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4820) | | GET | `/earn/dual/investment_plan` | -| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4831) | :closed_lock_with_key: | GET | `/earn/dual/orders` | -| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4843) | :closed_lock_with_key: | POST | `/earn/dual/orders` | -| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4852) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | -| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4861) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | -| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4870) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | -| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4881) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | -| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4890) | | GET | `/earn/fixed-term/product` | -| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4899) | | GET | `/earn/fixed-term/product/{asset}/list` | -| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4909) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | -| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4918) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | -| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4927) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | -| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4938) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | -| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4947) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | -| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4956) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | -| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | -| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | -| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4981) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | -| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4990) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | -| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5001) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | -| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5010) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | -| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5019) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | -| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | -| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5035) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | -| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5047) | :closed_lock_with_key: | GET | `/earn/staking/coins` | -| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5060) | :closed_lock_with_key: | POST | `/earn/staking/swap` | -| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5079) | :closed_lock_with_key: | GET | `/account/detail` | -| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5088) | :closed_lock_with_key: | GET | `/account/rate_limit` | -| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5098) | :closed_lock_with_key: | POST | `/account/stp_groups` | -| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5108) | :closed_lock_with_key: | GET | `/account/stp_groups` | -| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5118) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | -| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5128) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | -| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5144) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | -| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5162) | :closed_lock_with_key: | POST | `/account/debit_fee` | -| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5173) | :closed_lock_with_key: | GET | `/account/debit_fee` | -| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5182) | :closed_lock_with_key: | GET | `/account/main_keys` | -| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5198) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | -| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5211) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | -| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5225) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | -| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5240) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | -| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5263) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | -| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5273) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | -| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5286) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | -| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5299) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | -| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5308) | :closed_lock_with_key: | GET | `/rebate/user/info` | -| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5343) | :closed_lock_with_key: | POST | `/otc/quote` | -| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5355) | :closed_lock_with_key: | POST | `/otc/order/create` | -| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5369) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | -| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5378) | :closed_lock_with_key: | GET | `/otc/bank/list` | -| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank_list` | -| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5389) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | -| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5398) | :closed_lock_with_key: | POST | `/otc/bank/create` | -| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5412) | :closed_lock_with_key: | POST | `/otc/bank/delete` | -| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | -| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | -| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5435) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5454) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5490) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5504) | :closed_lock_with_key: | POST | `/otc/order/cancel` | -| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5516) | :closed_lock_with_key: | GET | `/otc/order/list` | -| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5530) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | -| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5544) | :closed_lock_with_key: | GET | `/otc/order/detail` | -| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5558) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | -| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5567) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | -| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5579) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | -| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5592) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5601) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5612) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | -| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5624) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | -| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5636) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | -| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5648) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | -| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5659) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | -| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5670) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | -| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5681) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | -| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5692) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | -| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5705) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | -| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5714) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | -| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5725) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | -| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5734) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | -| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5745) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | -| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5756) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | -| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5777) | | GET | `/crossex/rule/symbols` | -| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5789) | | GET | `/crossex/rule/risk_limits` | -| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5803) | | GET | `/crossex/transfers/coin` | -| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5817) | :closed_lock_with_key: | POST | `/crossex/transfers` | -| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5831) | :closed_lock_with_key: | GET | `/crossex/transfers` | -| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5845) | :closed_lock_with_key: | POST | `/crossex/orders` | -| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5859) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | -| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5873) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | -| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5886) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | -| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5901) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | -| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5913) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | -| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5927) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | -| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5941) | :closed_lock_with_key: | PUT | `/crossex/accounts` | -| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5955) | :closed_lock_with_key: | GET | `/crossex/accounts` | -| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5967) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | -| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5981) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | -| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5995) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | -| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6011) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | -| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6025) | :closed_lock_with_key: | POST | `/crossex/position` | -| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6031) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | -| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6045) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | -| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6058) | :closed_lock_with_key: | GET | `/crossex/fee` | -| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6070) | :closed_lock_with_key: | GET | `/crossex/positions` | -| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6084) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | -| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6098) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | -| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6110) | :closed_lock_with_key: | GET | `/crossex/open_orders` | -| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6124) | :closed_lock_with_key: | GET | `/crossex/history_orders` | -| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6138) | :closed_lock_with_key: | GET | `/crossex/history_positions` | -| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6152) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | -| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6166) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | -| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6180) | :closed_lock_with_key: | GET | `/crossex/history_trades` | -| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6194) | :closed_lock_with_key: | GET | `/crossex/account_book` | -| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6208) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | -| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6222) | | GET | `/crossex/market/tickers` | -| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6236) | | GET | `/crossex/market/funding_info` | -| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6254) | :closed_lock_with_key: | GET | `/alpha/accounts` | -| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6266) | :closed_lock_with_key: | GET | `/alpha/account_book` | -| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6280) | :closed_lock_with_key: | POST | `/alpha/quote` | -| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6292) | :closed_lock_with_key: | POST | `/alpha/orders` | -| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6304) | :closed_lock_with_key: | GET | `/alpha/orders` | -| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6316) | :closed_lock_with_key: | GET | `/alpha/order` | -| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6328) | | GET | `/alpha/currencies` | -| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6340) | | GET | `/alpha/tickers` | -| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6346) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | -| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6350) | | GET | `/tradfi/symbols/categories` | -| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6356) | | GET | `/tradfi/symbols` | -| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6368) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | -| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6374) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | -| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6380) | | GET | `/tradfi/symbols/{symbol}/klines` | -| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/tickers` | -| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6391) | :closed_lock_with_key: | POST | `/tradfi/users` | -| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6395) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | -| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6399) | :closed_lock_with_key: | POST | `/tradfi/transactions` | -| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6405) | :closed_lock_with_key: | GET | `/tradfi/transactions` | -| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6411) | :closed_lock_with_key: | POST | `/tradfi/orders` | -| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6417) | :closed_lock_with_key: | GET | `/tradfi/orders` | -| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6421) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | -| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | -| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6432) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | -| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6438) | :closed_lock_with_key: | GET | `/tradfi/positions` | -| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6444) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | -| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6453) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | -| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6462) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | -| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6471) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | -| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6485) | :closed_lock_with_key: | GET | `/stock/users/assets` | -| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6497) | | GET | `/stock/symbols` | -| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6509) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | -| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6521) | | GET | `/stock/market/{symbol}/orderbook` | -| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6531) | :closed_lock_with_key: | GET | `/stock/orders` | -| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6545) | :closed_lock_with_key: | POST | `/stock/orders` | -| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6556) | :closed_lock_with_key: | DELETE | `/stock/orders` | -| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6566) | :closed_lock_with_key: | GET | `/stock/orders/history` | -| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6579) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | -| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6592) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | -| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6604) | :closed_lock_with_key: | GET | `/stock/positions` | -| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6616) | :closed_lock_with_key: | POST | `/stock/positions/close` | -| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6628) | :closed_lock_with_key: | GET | `/stock/transactions` | -| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6642) | :closed_lock_with_key: | POST | `/stock/transactions` | -| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6653) | | GET | `/stock/exchanges` | -| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6664) | | GET | `/stock/fee-rate` | +| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L712) | | GET | `/v1/public/system_info` | +| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L716) | | POST | `/ann/list_article` | +| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L735) | :closed_lock_with_key: | POST | `/withdrawals` | +| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L749) | :closed_lock_with_key: | POST | `/withdrawals/push` | +| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L765) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | +| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L782) | | GET | `/wallet/currency_chains` | +| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L792) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | +| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L806) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | +| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L820) | :closed_lock_with_key: | GET | `/wallet/deposits` | +| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L839) | :closed_lock_with_key: | POST | `/wallet/transfers` | +| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L851) | :closed_lock_with_key: | GET | `/wallet/transfers` | +| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L863) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | +| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L877) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | +| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L891) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | +| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L906) | :closed_lock_with_key: | GET | `/wallet/order_status` | +| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L922) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | +| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L934) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | +| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L946) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | +| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L958) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | +| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L971) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | +| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L983) | :closed_lock_with_key: | GET | `/wallet/saved_address` | +| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L993) | :closed_lock_with_key: | GET | `/wallet/fee` | +| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1014) | :closed_lock_with_key: | GET | `/wallet/total_balance` | +| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1023) | :closed_lock_with_key: | GET | `/wallet/small_balance` | +| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1033) | :closed_lock_with_key: | POST | `/wallet/small_balance` | +| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1046) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | +| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1058) | :closed_lock_with_key: | GET | `/wallet/push` | +| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1067) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | +| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1082) | :closed_lock_with_key: | POST | `/sub_accounts` | +| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1093) | :closed_lock_with_key: | GET | `/sub_accounts` | +| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1103) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | +| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1113) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | +| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1126) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | +| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1140) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | +| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1151) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | +| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1166) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | +| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1181) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | +| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1191) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | +| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1205) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | +| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1224) | :closed_lock_with_key: | GET | `/unified/accounts` | +| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1240) | :closed_lock_with_key: | GET | `/unified/borrowable` | +| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1256) | :closed_lock_with_key: | GET | `/unified/transferable` | +| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1271) | :closed_lock_with_key: | GET | `/unified/transferables` | +| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1280) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | +| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1298) | :closed_lock_with_key: | POST | `/unified/loans` | +| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1310) | :closed_lock_with_key: | GET | `/unified/loans` | +| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1320) | :closed_lock_with_key: | GET | `/unified/loan_records` | +| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1332) | :closed_lock_with_key: | GET | `/unified/interest_records` | +| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1343) | :closed_lock_with_key: | GET | `/unified/risk_units` | +| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1355) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | +| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1364) | :closed_lock_with_key: | GET | `/unified/unified_mode` | +| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1376) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | +| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1387) | | GET | `/unified/currency_discount_tiers` | +| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1399) | | GET | `/unified/loan_margin_tiers` | +| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1416) | | POST | `/unified/portfolio_calculator` | +| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1430) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | +| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1444) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | +| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1458) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | +| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1473) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | +| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1488) | :closed_lock_with_key: | GET | `/unified/currencies` | +| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1500) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | +| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1506) | :closed_lock_with_key: | POST | `/unified/loans/repay` | +| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1513) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | +| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1520) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | +| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1531) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | +| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1540) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | +| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1560) | | GET | `/spot/currencies` | +| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1570) | | GET | `/spot/currencies/{currency}` | +| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1579) | | GET | `/spot/currency_pairs` | +| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1589) | | GET | `/spot/currency_pairs/{currency_pair}` | +| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1603) | | GET | `/spot/tickers` | +| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1618) | | GET | `/spot/order_book` | +| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1631) | | GET | `/spot/trades` | +| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1643) | | GET | `/spot/candlesticks` | +| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1655) | :closed_lock_with_key: | GET | `/spot/fee` | +| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1664) | :closed_lock_with_key: | GET | `/spot/batch_fee` | +| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1676) | :closed_lock_with_key: | GET | `/spot/accounts` | +| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1688) | :closed_lock_with_key: | GET | `/spot/account_book` | +| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1707) | :closed_lock_with_key: | POST | `/spot/batch_orders` | +| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1734) | :closed_lock_with_key: | GET | `/spot/open_orders` | +| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1750) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | +| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1766) | :closed_lock_with_key: | POST | `/spot/orders` | +| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1783) | :closed_lock_with_key: | GET | `/spot/orders` | +| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1798) | :closed_lock_with_key: | DELETE | `/spot/orders` | +| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1827) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | +| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1852) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | +| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1869) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | +| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1897) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | +| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1926) | :closed_lock_with_key: | GET | `/spot/my_trades` | +| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1955) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | +| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1974) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | +| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2001) | :closed_lock_with_key: | GET | `/spot/insurance_history` | +| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2015) | :closed_lock_with_key: | POST | `/spot/price_orders` | +| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2027) | :closed_lock_with_key: | GET | `/spot/price_orders` | +| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2039) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | +| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2052) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | +| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2064) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | +| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2078) | :closed_lock_with_key: | GET | `/spot/pov_orders` | +| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2090) | :closed_lock_with_key: | POST | `/spot/pov_orders` | +| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2102) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | +| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2116) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | +| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2128) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | +| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2140) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | +| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2161) | :closed_lock_with_key: | GET | `/margin/accounts` | +| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2175) | :closed_lock_with_key: | GET | `/margin/account_book` | +| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2193) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | +| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2211) | :closed_lock_with_key: | POST | `/margin/auto_repay` | +| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2222) | :closed_lock_with_key: | GET | `/margin/auto_repay` | +| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2236) | :closed_lock_with_key: | GET | `/margin/transferable` | +| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2253) | | GET | `/margin/cross/currencies` | +| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2264) | | GET | `/margin/cross/currencies/{currency}` | +| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2276) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | +| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2289) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | +| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2306) | :closed_lock_with_key: | POST | `/margin/cross/loans` | +| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2321) | :closed_lock_with_key: | GET | `/margin/cross/loans` | +| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2334) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | +| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2349) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | +| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2365) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | +| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2378) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | +| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2394) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | +| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2410) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | +| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2424) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | +| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2437) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | +| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2453) | | GET | `/margin/loan_margin_tiers` | +| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2469) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | +| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2486) | :closed_lock_with_key: | GET | `/margin/user/account` | +| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2501) | | GET | `/margin/uni/currency_pairs` | +| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2516) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | +| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2528) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | +| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2538) | :closed_lock_with_key: | POST | `/margin/uni/loans` | +| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2554) | :closed_lock_with_key: | GET | `/margin/uni/loans` | +| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2564) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | +| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2576) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | +| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2588) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | +| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2604) | | GET | `/flash_swap/currency_pairs` | +| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2620) | :closed_lock_with_key: | POST | `/flash_swap/orders` | +| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2632) | :closed_lock_with_key: | GET | `/flash_swap/orders` | +| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2644) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | +| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2654) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | +| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2671) | | GET | `/futures/{settle}/contracts` | +| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2686) | | GET | `/futures/{settle}/contracts/{contract}` | +| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2693) | | GET | `/futures/{settle}/adl_risk_states` | +| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2707) | | GET | `/futures/{settle}/order_book` | +| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2720) | | GET | `/futures/{settle}/trades` | +| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2735) | | GET | `/futures/{settle}/candlesticks` | +| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2748) | | GET | `/futures/{settle}/premium_index` | +| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2761) | | GET | `/futures/{settle}/tickers` | +| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2778) | | GET | `/futures/{settle}/funding_rate` | +| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2794) | | POST | `/futures/{settle}/funding_rates` | +| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2812) | | GET | `/futures/{settle}/insurance` | +| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2831) | | GET | `/futures/{settle}/contract_stats` | +| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2842) | | GET | `/futures/{settle}/index_constituents/{index}` | +| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2859) | | GET | `/futures/{settle}/liq_orders` | +| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2876) | | GET | `/futures/{settle}/risk_limit_tiers` | +| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2889) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | +| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2903) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | +| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2916) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | +| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2931) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | +| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2948) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | +| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2976) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | +| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2996) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | +| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3012) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | +| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3029) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | +| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3049) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | +| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3065) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | +| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3080) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | +| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3096) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | +| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3120) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | +| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3147) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | +| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3168) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | +| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3183) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | +| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3203) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | +| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3226) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | +| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3251) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | +| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3268) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | +| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3293) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | +| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3314) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | +| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3329) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | +| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3342) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | +| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3355) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | +| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3368) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | +| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3385) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | +| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3402) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | +| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3420) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | +| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3447) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | +| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3469) | | GET | `/futures/{settle}/risk_limit_table` | +| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3482) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | +| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3495) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | +| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3508) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | +| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3524) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | +| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3539) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | +| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3557) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend/{order_id}` | +| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3575) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | +| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3593) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | +| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3606) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | +| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3621) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | +| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3634) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | +| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3652) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | +| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3665) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | +| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3678) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | +| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3688) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | +| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3698) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | +| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3710) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | +| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3718) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | +| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3727) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | +| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3736) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | +| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3753) | | GET | `/delivery/{settle}/contracts` | +| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3765) | | GET | `/delivery/{settle}/contracts/{contract}` | +| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3780) | | GET | `/delivery/{settle}/order_book` | +| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3793) | | GET | `/delivery/{settle}/trades` | +| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3807) | | GET | `/delivery/{settle}/candlesticks` | +| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3818) | | GET | `/delivery/{settle}/tickers` | +| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3835) | | GET | `/delivery/{settle}/insurance` | +| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3854) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | +| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3865) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | +| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3876) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | +| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3886) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | +| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3901) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | +| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3919) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | +| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3937) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | +| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3957) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | +| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3972) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | +| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3985) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | +| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4004) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | +| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4019) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | +| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4034) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | +| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4047) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | +| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4060) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | +| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4073) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | +| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4086) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | +| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4101) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | +| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4114) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | +| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4130) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | +| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4145) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | +| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4164) | | GET | `/options/underlyings` | +| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4174) | | GET | `/options/expirations` | +| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4184) | | GET | `/options/contracts` | +| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4197) | | GET | `/options/contracts/{contract}` | +| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4207) | | GET | `/options/settlements` | +| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4219) | | GET | `/options/settlements/{contract}` | +| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4234) | :closed_lock_with_key: | GET | `/options/my_settlements` | +| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4248) | | GET | `/options/order_book` | +| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4260) | | GET | `/options/tickers` | +| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4274) | | GET | `/options/underlying/tickers/{underlying}` | +| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4288) | | GET | `/options/candlesticks` | +| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4298) | | GET | `/options/underlying/candlesticks` | +| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4310) | | GET | `/options/trades` | +| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4321) | :closed_lock_with_key: | GET | `/options/accounts` | +| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4331) | :closed_lock_with_key: | GET | `/options/account_book` | +| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4343) | :closed_lock_with_key: | GET | `/options/positions` | +| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4355) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | +| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4367) | :closed_lock_with_key: | GET | `/options/position_close` | +| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4380) | :closed_lock_with_key: | POST | `/options/orders` | +| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4392) | :closed_lock_with_key: | GET | `/options/orders` | +| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4404) | :closed_lock_with_key: | DELETE | `/options/orders` | +| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4418) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | +| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4430) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | +| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4445) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | +| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4464) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | +| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4480) | :closed_lock_with_key: | GET | `/options/my_trades` | +| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4492) | :closed_lock_with_key: | POST | `/options/mmp` | +| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4504) | :closed_lock_with_key: | GET | `/options/mmp` | +| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4516) | :closed_lock_with_key: | POST | `/options/mmp/reset` | +| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4532) | | GET | `/earn/uni/currencies` | +| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4542) | | GET | `/earn/uni/currencies/{currency}` | +| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4552) | :closed_lock_with_key: | POST | `/earn/uni/lends` | +| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4562) | :closed_lock_with_key: | GET | `/earn/uni/lends` | +| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4574) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | +| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4587) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | +| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4600) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | +| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4613) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | +| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4626) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | +| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4642) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | +| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4657) | :closed_lock_with_key: | GET | `/earn/uni/chart` | +| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4665) | :closed_lock_with_key: | GET | `/earn/uni/rate` | +| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4682) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | +| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4694) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | +| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4706) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | +| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4716) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | +| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4726) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | +| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4738) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | +| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4750) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | +| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4762) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | +| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4774) | | GET | `/loan/multi_collateral/currencies` | +| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4783) | | GET | `/loan/multi_collateral/ltv` | +| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4792) | | GET | `/loan/multi_collateral/fixed_rate` | +| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4805) | | GET | `/loan/multi_collateral/current_rate` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4827) | | GET | `/earn/dual/investment_plan` | +| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4838) | :closed_lock_with_key: | GET | `/earn/dual/orders` | +| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4850) | :closed_lock_with_key: | POST | `/earn/dual/orders` | +| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4859) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | +| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4868) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | +| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4877) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | +| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4888) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | +| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4897) | | GET | `/earn/fixed-term/product` | +| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4906) | | GET | `/earn/fixed-term/product/{asset}/list` | +| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4916) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | +| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4925) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | +| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4934) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | +| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4945) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | +| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4954) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | +| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | +| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | +| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4977) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | +| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4988) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | +| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4997) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | +| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5008) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | +| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5017) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | +| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | +| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5033) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | +| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5042) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | +| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5054) | :closed_lock_with_key: | GET | `/earn/staking/coins` | +| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5067) | :closed_lock_with_key: | POST | `/earn/staking/swap` | +| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5086) | :closed_lock_with_key: | GET | `/account/detail` | +| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5095) | :closed_lock_with_key: | GET | `/account/rate_limit` | +| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5105) | :closed_lock_with_key: | POST | `/account/stp_groups` | +| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5115) | :closed_lock_with_key: | GET | `/account/stp_groups` | +| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5125) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | +| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5135) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | +| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5151) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | +| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5169) | :closed_lock_with_key: | POST | `/account/debit_fee` | +| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5180) | :closed_lock_with_key: | GET | `/account/debit_fee` | +| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5189) | :closed_lock_with_key: | GET | `/account/main_keys` | +| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5205) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | +| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5218) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | +| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5232) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | +| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5247) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | +| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5270) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | +| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5280) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | +| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5293) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | +| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5306) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | +| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5315) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5350) | :closed_lock_with_key: | POST | `/otc/quote` | +| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5362) | :closed_lock_with_key: | POST | `/otc/order/create` | +| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5376) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | +| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank/list` | +| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5392) | :closed_lock_with_key: | GET | `/otc/bank_list` | +| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5396) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | +| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5405) | :closed_lock_with_key: | POST | `/otc/bank/create` | +| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/delete` | +| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | +| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5433) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | +| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5442) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5461) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5497) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5511) | :closed_lock_with_key: | POST | `/otc/order/cancel` | +| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5523) | :closed_lock_with_key: | GET | `/otc/order/list` | +| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5537) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | +| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5551) | :closed_lock_with_key: | GET | `/otc/order/detail` | +| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5565) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | +| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5574) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | +| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5586) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | +| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5599) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5608) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5619) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | +| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5631) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | +| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5643) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | +| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5655) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | +| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5666) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | +| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5677) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | +| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5688) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | +| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5699) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | +| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5712) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | +| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5721) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | +| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5732) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | +| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5741) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | +| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5752) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | +| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5763) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | +| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5784) | | GET | `/crossex/rule/symbols` | +| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5796) | | GET | `/crossex/rule/risk_limits` | +| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5810) | | GET | `/crossex/transfers/coin` | +| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5824) | :closed_lock_with_key: | POST | `/crossex/transfers` | +| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5838) | :closed_lock_with_key: | GET | `/crossex/transfers` | +| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5852) | :closed_lock_with_key: | POST | `/crossex/orders` | +| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5866) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | +| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5880) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | +| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5893) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | +| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5908) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | +| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5920) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | +| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5934) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | +| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5948) | :closed_lock_with_key: | PUT | `/crossex/accounts` | +| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5962) | :closed_lock_with_key: | GET | `/crossex/accounts` | +| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5974) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | +| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5988) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | +| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6002) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | +| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6018) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | +| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6032) | :closed_lock_with_key: | POST | `/crossex/position` | +| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6038) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | +| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6052) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | +| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6065) | :closed_lock_with_key: | GET | `/crossex/fee` | +| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6077) | :closed_lock_with_key: | GET | `/crossex/positions` | +| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6091) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | +| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6105) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | +| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6117) | :closed_lock_with_key: | GET | `/crossex/open_orders` | +| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6131) | :closed_lock_with_key: | GET | `/crossex/history_orders` | +| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6145) | :closed_lock_with_key: | GET | `/crossex/history_positions` | +| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6159) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | +| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6173) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | +| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6187) | :closed_lock_with_key: | GET | `/crossex/history_trades` | +| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6201) | :closed_lock_with_key: | GET | `/crossex/account_book` | +| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6215) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | +| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6229) | | GET | `/crossex/market/tickers` | +| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6243) | | GET | `/crossex/market/funding_info` | +| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6261) | :closed_lock_with_key: | GET | `/alpha/accounts` | +| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6273) | :closed_lock_with_key: | GET | `/alpha/account_book` | +| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6287) | :closed_lock_with_key: | POST | `/alpha/quote` | +| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6299) | :closed_lock_with_key: | POST | `/alpha/orders` | +| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6311) | :closed_lock_with_key: | GET | `/alpha/orders` | +| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6323) | :closed_lock_with_key: | GET | `/alpha/order` | +| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6335) | | GET | `/alpha/currencies` | +| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6347) | | GET | `/alpha/tickers` | +| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6353) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | +| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6357) | | GET | `/tradfi/symbols/categories` | +| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6363) | | GET | `/tradfi/symbols` | +| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6375) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | +| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6381) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | +| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/klines` | +| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6394) | | GET | `/tradfi/symbols/{symbol}/tickers` | +| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6398) | :closed_lock_with_key: | POST | `/tradfi/users` | +| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6402) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | +| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6406) | :closed_lock_with_key: | POST | `/tradfi/transactions` | +| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6412) | :closed_lock_with_key: | GET | `/tradfi/transactions` | +| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6418) | :closed_lock_with_key: | POST | `/tradfi/orders` | +| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6424) | :closed_lock_with_key: | GET | `/tradfi/orders` | +| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | +| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6435) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | +| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6439) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | +| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6445) | :closed_lock_with_key: | GET | `/tradfi/positions` | +| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6451) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | +| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6460) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | +| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6469) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | +| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6478) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | +| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6492) | :closed_lock_with_key: | GET | `/stock/users/assets` | +| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6504) | | GET | `/stock/symbols` | +| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6516) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | +| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6528) | | GET | `/stock/market/{symbol}/orderbook` | +| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6538) | :closed_lock_with_key: | GET | `/stock/orders` | +| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6552) | :closed_lock_with_key: | POST | `/stock/orders` | +| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6563) | :closed_lock_with_key: | DELETE | `/stock/orders` | +| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6573) | :closed_lock_with_key: | GET | `/stock/orders/history` | +| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6586) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | +| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6599) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | +| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6611) | :closed_lock_with_key: | GET | `/stock/positions` | +| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6623) | :closed_lock_with_key: | POST | `/stock/positions/close` | +| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6635) | :closed_lock_with_key: | GET | `/stock/transactions` | +| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6649) | :closed_lock_with_key: | POST | `/stock/transactions` | +| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6660) | | GET | `/stock/exchanges` | +| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6671) | | GET | `/stock/fee-rate` | # WebsocketAPIClient.ts diff --git a/examples/Rest/futures/testnet.ts b/examples/Rest/futures/testnet.ts index 8fb22c4..2e30082 100644 --- a/examples/Rest/futures/testnet.ts +++ b/examples/Rest/futures/testnet.ts @@ -11,24 +11,7 @@ const account = { const gateRestClient = new RestClient({ apiKey: account.key, apiSecret: account.secret, - /** - * To use a different base URL, use the baseUrl key. The SDK uses the live environment by default: - * baseUrlKey: 'live', - *'https://api.gateio.ws/api/v4' - * But you can force it to use any of the available environments. Examples below. - */ - - /* - * Futures TestNet trading: - * 'https://fx-api-testnet.gateio.ws/api/v4' - */ - baseUrlKey: 'futuresTestnet', - - /** - * Futures live trading alternative (futures only): - * 'https://fx-api.gateio.ws/api/v4' - */ - // baseUrlKey: 'futuresLiveAlternative' + baseUrl: 'https://api-testnet.gateapi.io/api/v4', }); async function submitFuturesOrder() { diff --git a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js index a211c1f..48dc1d7 100644 --- a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js +++ b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js @@ -4,7 +4,7 @@ import { RestClient } from 'gateio-api'; // This example shows how to call this Gate.io API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "gateio-api" for Gate.io exchange // This Gate.io API SDK is available on npm via "npm install gateio-api" -// ENDPOINT: /futures/{settle}/price_orders/amend +// ENDPOINT: /futures/{settle}/price_orders/amend/{order_id} // METHOD: PUT // PUBLIC: NO diff --git a/llms.txt b/llms.txt index a13ad5e..12027b0 100644 --- a/llms.txt +++ b/llms.txt @@ -196,136 +196,6 @@ Most examples also have minimal typescript, so if you rename them to "js" they s node ./examples/spot/getTickers.js ``` -================ -File: src/lib/websocket/websocket-util.ts -================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { WSAPIRequest } from '../../types/websockets/requests.js'; -import { - FuturesWSAPITopic, - SpotWSAPITopic, -} from '../../types/websockets/wsAPI.js'; -⋮---- -/** - * Should be one WS key per unique URL. Some URLs may need a suffix. - */ -⋮---- -/** - * Spot & Margin - * https://www.gate.io/docs/developers/apiv4/ws/en/ - */ -⋮---- -/** - * Perpetual futures (USDT) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ -⋮---- -/** - * Perpetual futures (BTC) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ -⋮---- -/** - * Delivery Futures (USDT) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ -⋮---- -/** - * Delivery Futures (BTC) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ -⋮---- -/** - * Options - * https://www.gate.io/docs/developers/options/ws/en/ - */ -⋮---- -/** - * Announcements V4 - * https://www.gate.io/docs/developers/options/ws/en/ - */ -⋮---- -/** This is used to differentiate between each of the available websocket streams */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; -⋮---- -export type FuturesWsKey = - | typeof WS_KEY_MAP.perpFuturesUSDTV4 - | typeof WS_KEY_MAP.perpFuturesBTCV4 - | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 - | typeof WS_KEY_MAP.deliveryFuturesBTCV4; -⋮---- -export type WsMarket = 'all'; -⋮---- -/** - * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters. - * - * - Topic: the topic this event is for - * - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters. - */ -export interface WsTopicRequest< - TWSTopic extends string = string, - TWSPayload = any, -> { - topic: TWSTopic; - payload?: TWSPayload; -} -⋮---- -/** - * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params) - */ -export type WsTopicRequestOrStringTopic< - TWSTopic extends string, - TWSPayload = any, -> = WsTopicRequest | string; -⋮---- -/** - * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges. - * Examples: - * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'> - * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'> - * - Only one livenet, no other networks: NetworkMap<'livenet'> - */ -type NetworkMap< - TRequiredKeys extends string, - TOptionalKeys extends string | undefined = undefined, -> = Record & - (TOptionalKeys extends string - ? Record - : Record); -⋮---- -export function neverGuard(x: never, msg: string): Error -⋮---- -/** - * WS API promises are stored using a primary key. This key is constructed using - * properties found in every request & reply. - */ -export function getPromiseRefForWSAPIRequest( - requestEvent: WSAPIRequest, -): string -⋮---- -export function getPrivateSpotTopics(): string[] -⋮---- -// Consumeable channels for spot -⋮---- -// WebSocket API for spot -⋮---- -export function getPrivateFuturesTopics(): string[] -⋮---- -// These are the same for perps vs delivery futures -⋮---- -export function getPrivateOptionsTopics(): string[] -⋮---- -/** - * ws.terminate() is undefined in browsers. - * This only works in node.js, not in browsers. - * Does nothing if `ws` is undefined. Does nothing in browsers. - */ -export function safeTerminateWs( - ws?: WebSocket | any, - fallbackToClose?: boolean, -): boolean - ================ File: src/lib/websocket/WsStore.types.ts ================ @@ -441,118 +311,6 @@ File: src/lib/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error -================ -File: src/lib/requestUtils.ts -================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { GateBaseUrlKey } from '../types/shared.js'; -⋮---- -export interface RestClientOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - /** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ - recvWindow?: number; - - /** Default: false. If true, we'll throw errors if any params are undefined */ - strictParamValidation?: boolean; - - /** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.gate.io' - **/ - baseUrl?: string; - - // manually override with one of the known base URLs in the library - baseUrlKey?: GateBaseUrlKey; - - /** Default: true. whether to try and post-process request exceptions (and throw them). */ - parseExceptions?: boolean; - - /** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 - */ - keepAlive?: boolean; - - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ - keepAliveMsecs?: number; - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ - customSignMessageFn?: (message: string, secret: string) => Promise; -} -⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ -⋮---- -/** Default: false. If true, we'll throw errors if any params are undefined */ -⋮---- -/** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.gate.io' - **/ -⋮---- -// manually override with one of the known base URLs in the library -⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ -⋮---- -/** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 - */ -⋮---- -/** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ -⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ -⋮---- -export function serializeParams | undefined = {}>( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, -): string -⋮---- -// Only prefix if there's a value -⋮---- -export function getRestBaseUrl(restClientOptions: RestClientOptions): string -⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} -⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike - ================ File: src/lib/webCryptoAPI.ts ================ @@ -600,32 +358,12 @@ export interface CreateStpGroupReq { } ================ -File: src/types/request/announcement.ts +File: src/types/request/collateralLoan.ts ================ -/** POST /ann/list_article */ -⋮---- -export interface ListAnnouncementArticlesReq { - title_query?: string; - page?: string; - size?: string; - tags?: string; - timer?: string; - cate_name?: string; - cate_level?: string; - sub_website_id?: string; - pinned?: number; - update_after?: number; - lang?: string; - filter_empty_content?: number; -} - -================ -File: src/types/request/collateralLoan.ts -================ -/**========================================================================================================================== - * COLLATERAL LOAN - * ========================================================================================================================== - */ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- export interface SubmitLoanOrderReq { collateral_amount: string; @@ -1146,44 +884,6 @@ export interface AccountMainKey { state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified -================ -File: src/types/response/announcement.ts -================ -export interface AnnouncementArticleLanguage { - code?: string; - name?: string; -} -⋮---- -export interface AnnouncementArticle { - id?: number; - title?: string; - brief?: string; - created?: string; - updated?: string; - release_time?: string; - views?: number; - author?: string; - author_id?: number; - tags?: string; - cate?: string; - is_top?: number; - cate_id?: number; - source?: string; - content_lang_list?: AnnouncementArticleLanguage[]; -} -⋮---- -export interface AnnouncementArticleListData { - list?: AnnouncementArticle[]; - total?: number; -} -⋮---- -export interface AnnouncementArticleListResponse { - code?: number; - data?: AnnouncementArticleListData; - message?: string; - version?: string; -} - ================ File: src/types/response/collateralloan.ts ================ @@ -1250,6 +950,193 @@ export interface LoanCollateralRatio { left_borrowable_amount: string; } +================ +File: src/types/response/delivery.ts +================ +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ +⋮---- +export interface DeliveryOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} +⋮---- +export interface DeliveryTrade { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; // Deprecated +} +⋮---- +is_internal?: boolean; // Deprecated +⋮---- +export interface DeliveryCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; +} +⋮---- +export interface DeliveryTicker { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; // Deprecated + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; +} +⋮---- +quanto_base_rate?: string; // Deprecated +⋮---- +export interface DeliveryAccount { + total: string; // Balance, only applicable to classic contract account + unrealised_pnl: string; + position_margin?: string; // Deprecated + order_margin: string; // Initial margin for all pending orders + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic?: boolean; // Deprecated + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + isolated_position_margin: string; + enable_new_dual_mode?: boolean; // Deprecated + margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + enable_tiered_mm: boolean; +} +⋮---- +total: string; // Balance, only applicable to classic contract account +⋮---- +position_margin?: string; // Deprecated +order_margin: string; // Initial margin for all pending orders +⋮---- +position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) +⋮---- +enable_evolved_classic?: boolean; // Deprecated +⋮---- +enable_new_dual_mode?: boolean; // Deprecated +margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +⋮---- +export interface DeliveryBook { + time: number; + change: string; + balance: string; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; + contract?: string; + trade_id?: string; +} +⋮---- +export interface DeliveryTradingHistoryRecord { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; +} +⋮---- +export interface DeliveryClosedPosition { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} +⋮---- +export interface DeliveryLiquidationHistoryRecord { + time: number; + contract: string; + leverage?: string; + size: number; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + order_id?: number; + order_price: string; + fill_price: string; + left: number; +} +⋮---- +export interface DeliverySettlementHistoryRecord { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + settle_price: string; + profit: string; + fee: string; +} + ================ File: src/types/response/earnuni.ts ================ @@ -1338,1301 +1225,1691 @@ export interface SubmitFlashSwapOrderPreviewResp { } ================ -File: src/types/response/subaccount.ts +File: src/types/response/margin.ts ================ -export interface SubAccount { - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; -} -⋮---- -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; -} +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ ⋮---- -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 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 SubAccountMode { - user_id: number; - is_unified: boolean; - mode: 'classic' | 'multi_currency' | 'portfolio'; -} - -================ -File: src/types/websockets/events.ts -================ -export interface WsDataEvent { - data: TData; - table: string; - wsKey: TWSKey; +export interface MarginBalanceHistoryRecord { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; } - -================ -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 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 WsRequestAuthGate { - method: 'api_key'; - KEY: string; - SIGN: string; +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 WsRequestPing { +export interface CrossMarginAccountHistoryRecord { + id: string; time: number; - channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; + currency: string; + change: string; + balance: string; + type: string; } ⋮---- -export interface WsRequestOperationGate< - TWSTopic extends string, - TWSPayload = any, -> { - time: number; - id?: number; - channel: TWSTopic; - auth?: WsRequestAuthGate; - event?: WsOperation; - payload?: TWSPayload; +export interface CrossMarginMorrowLoanRecord { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; } ⋮---- -export interface WSAPIRequest< - TRequestParams = any, - TWSChannel extends WSAPITopic = any, -> { - time: number; - id?: number; - channel: TWSChannel; - event: 'api'; - payload: { - req_id: string; - req_param?: TRequestParams | string; - req_header: { - 'X-Gate-Channel-Id': typeof CHANNEL_ID; - }; - api_key?: string; - signature?: string; - timestamp?: string; +export interface MarginUserAccount { + currency_pair: string; + account_type: string; // Description updated to remove "risk" option + leverage: string; + locked: boolean; + risk?: string; // Deprecated + mmr?: string; // Refined description + base: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; + quote: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; }; } +⋮---- +account_type: string; // Description updated to remove "risk" option +⋮---- +risk?: string; // Deprecated +mmr?: string; // Refined description ================ -File: src/types/websockets/wsAPI.ts +File: src/types/response/options.ts ================ -import { WsKey } from '../../lib/websocket/websocket-util.js'; -⋮---- -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; +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ ⋮---- -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 OptionsContract { + name: string; + tag: string; // Expiry period: day, week, month + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id?: number; // Deprecated + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date + multiplier: string; // Option contract multiplier + order_price_round: string; + mark_price_round: string; // Minimum unit of mark price + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate?: string; // Deprecated + order_size_min: number; + order_size_max: number; + orders_limit: number; // Maximum number of orders per user in this market } ⋮---- -export interface WSAPISpotOrderCancelIdsReq { - currency_pair: string; - id: string; - account?: string; -} +tag: string; // Expiry period: day, week, month ⋮---- -export interface WSAPISpotOrderCancelCPReq { - currency_pair: string; - side?: 'buy' | 'sell'; - account?: string; -} +trade_id?: number; // Deprecated ⋮---- -export interface WSAPISpotOrderAmendReq { - amount?: string; - price?: string; - amend_text?: string; - order_id: string; - currency_pair: string; - account?: string; -} +underlying_price: string; // Forward futures price for the delivery date +multiplier: string; // Option contract multiplier ⋮---- -export interface WSAPISpotOrderStatusReq { - order_id: string; - currency_pair: string; - account?: string; -} +mark_price_round: string; // Minimum unit of mark price ⋮---- -export interface WSAPISpotOrderListReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: string; - from?: number; - to?: number; - side?: 'buy' | 'sell'; -} +order_price_deviate?: string; // Deprecated ⋮---- -// ==================================== -// Futures WebSocket API Request Types -// ==================================== +orders_limit: number; // Maximum number of orders per user in this market ⋮---- -export interface WSAPIFuturesOrderPlaceReq { +export interface OptionsSettlementHistoryRecord { + time: number; contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - text?: string; - auto_size?: 'close_long' | 'close_short'; - stp_act?: 'cn' | 'co' | 'cb'; -} -⋮---- -export interface WSAPIFuturesOrderCancelReq { - order_id: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; } ⋮---- -export interface WSAPIFuturesOrderCancelCPReq { +export interface OptionsUserSettlement { + time: number; + underlying: string; contract: string; - side?: 'bid' | 'ask'; -} -⋮---- -export interface WSAPIFuturesOrderAmendReq { - order_id: string; - price?: string; - size?: number; - amend_text?: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; } ⋮---- -export interface WSAPIFuturesOrderListReq { - contract: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: number; +export interface OptionsOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; } ⋮---- -export interface WSAPIFuturesOrderStatusReq { - order_id: string; +export interface OptionsTicker { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; // Leverage calculation formula updated with reference note + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; } ⋮---- -// ==================================== -// Spot WebSocket API Response Types -// ==================================== +leverage: string; // Leverage calculation formula updated with reference note ⋮---- -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 OptionsCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; } ⋮---- -export interface WSAPISpotOrderCancelIdsRespItem { - currency_pair: string; - id: string; - succeeded: boolean; +export interface OptionsUnderlyingCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; } ⋮---- -// ==================================== -// Futures WebSocket API Response Types -// ==================================== -⋮---- -export interface WSAPIFuturesOrder { +export interface OptionsTrade { id: number; - user: number; create_time: number; - finish_time?: number; - update_time?: number; - finish_as?: string; - status: string; + create_time_ms: number; 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; + is_internal?: boolean; // Deprecated } ⋮---- -export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { - succeeded: boolean; -} +is_internal?: boolean; // Deprecated ⋮---- -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 interface OptionsAccount { + user: number; + total?: string; // Only applicable to classic options accounts (unified account limitation) + equity?: string; // Only applicable to classic options accounts (unified account limitation) + short_enabled: boolean; + unrealised_pnl: string; // Enhanced with calculation formula + init_margin: string; + maint_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + liq_triggered?: boolean; // Whether account is in liquidation status + margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode } ⋮---- -export type WsAPITopicRequestParams = - WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; +total?: string; // Only applicable to classic options accounts (unified account limitation) +equity?: string; // Only applicable to classic options accounts (unified account limitation) ⋮---- -// ==================================== -// Response Headers and Base Response -// ==================================== +unrealised_pnl: string; // Enhanced with calculation formula ⋮---- -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; +liq_triggered?: boolean; // Whether account is in liquidation status +margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +⋮---- +export interface OptionsAccountChangeRecord { + time: number; + change: string; + balance: string; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + text: string; } ⋮---- -/** String timestamp as ms */ +export interface OptionsPositionsUnderlying { + user: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date + contract: string; + size: number; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; +} ⋮---- -/** Status of WS API call. "200" if successful, else exception is thrown */ +underlying_price: string; // Forward futures price for the delivery date ⋮---- -export interface WSAPILoginResponse { - api_key: string; - uid: string; +export interface GetOptionsLiquidationResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + text: string; + settle_size: string; } ⋮---- -export interface WSAPIOrderStatusResponse { - left: string; - update_time: string; - amount: string; - create_time: 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; - 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; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; fill_price: string; - update_time_ms: number; - create_time_ms: number; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; } ⋮---- -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; +export interface OptionsUserHistoryRecord { + id: number; + create_time: number; + contract: string; + order_id: number; + size: number; + price: string; + underlying_price: string; // Forward futures price for the delivery date + role: 'taker' | 'maker'; } ⋮---- -/** Auto-generated */ -⋮---- -// ==================================== -// Response Type Mapping -// ==================================== +underlying_price: string; // Forward futures price for the delivery date ⋮---- -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 OptionsMMPSettings { + underlying: string; + window: number; + frozen_period: number; + qty_limit: string; + delta_limit: string; + trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered + frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered } ⋮---- -// export interface WsAPIResponseMap { -// 'spot.login': WSAPIResponse; -// 'futures.login': WSAPIResponse; -// string: object; -// } +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/WebsocketAPIClient.ts +File: src/types/response/subaccount.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'; +export interface SubAccount { + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; +} ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; +export 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; } ⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ +export interface 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; +} ⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should - * be used to transmit that message. This is only useful if you wish to use an alternative wss - * domain that is supported by the SDK. - * - * Note: To use testnet, don't set the wsKey - use `testnet: true` in - * the constructor instead. - * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. - * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 - */ -export class WebsocketAPIClient +export interface SubAccountMode { + user_id: number; + is_unified: boolean; + mode: 'classic' | 'multi_currency' | 'portfolio'; +} + +================ +File: src/types/websockets/events.ts +================ +export interface WsDataEvent { + data: TData; + table: string; + wsKey: TWSKey; +} + +================ +File: src/types/websockets/requests.ts +================ +import { CHANNEL_ID } from '../../lib/requestUtils.js'; +import { WSAPITopic } from './wsAPI.js'; ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- -public getWSClient(): WebsocketClient +export interface WsRequestAuthGate { + method: 'api_key'; + KEY: string; + SIGN: string; +} ⋮---- -public setTimeOffsetMs(newOffset: number): void +export interface WsRequestPing { + time: number; + channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; +} ⋮---- -/* - * - * SPOT - Trading requests - * - */ +export interface WsRequestOperationGate< + TWSTopic extends string, + TWSPayload = any, +> { + time: number; + id?: number; + channel: TWSTopic; + auth?: WsRequestAuthGate; + event?: WsOperation; + payload?: TWSPayload; +} ⋮---- -/** - * Submit a spot order - */ -submitNewSpotOrder( - params: WSAPISpotOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +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'; ⋮---- -/** - * Cancel a spot order - */ -cancelSpotOrder( - params: WSAPISpotOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +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'; ⋮---- -/** - * Cancel all spot orders with the given id list - */ -cancelSpotOrderById( - params: WSAPISpotOrderCancelIdsReq[], - wsKey?: WSAPIWsKey, -): Promise> +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'; ⋮---- -/** - * Cancel a spot order for a given symbol - */ -cancelSpotOrderForSymbol( - params: WSAPISpotOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WsAPIWsKeyTopicMap { + spotV4: SpotWSAPITopic; + perpFuturesUSDTV4: FuturesWSAPITopic; + perpFuturesBTCV4: FuturesWSAPITopic; + deliveryFuturesUSDTV4: FuturesWSAPITopic; + deliveryFuturesBTCV4: FuturesWSAPITopic; + // optionsV4: never; + // announcementsV4: never; +} ⋮---- -/** - * Update a spot order - */ -updateSpotOrder( - params: WSAPISpotOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +// optionsV4: never; +// announcementsV4: never; ⋮---- -/** - * 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> +export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; +export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; ⋮---- -/** - * Submit a batch of futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -submitNewFuturesBatchOrder( - params: WSAPIFuturesOrderPlaceReq[], - wsKey?: WSAPIWsKey, -): Promise> +// ==================================== +// Spot WebSocket API Request Types +// ==================================== ⋮---- -/** - * Cancel a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrder( - params: WSAPIFuturesOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +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'; +} ⋮---- -/** - * Cancel futures orders by id list - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrderById( - params: string[], - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderCancelReq { + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -/** - * Cancel all open futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesAllOpenOrders( - params: WSAPIFuturesOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderCancelIdsReq { + currency_pair: string; + id: string; + account?: string; +} ⋮---- -/** - * Update a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -updateFuturesOrder( - params: WSAPIFuturesOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderCancelCPReq { + currency_pair: string; + side?: 'buy' | 'sell'; + account?: string; +} ⋮---- -/** - * Get all futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrders( - params: WSAPIFuturesOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderAmendReq { + amount?: string; + price?: string; + amend_text?: string; + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -/** - * Get futures order status - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrderStatus( - params: WSAPIFuturesOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +export interface WSAPISpotOrderStatusReq { + order_id: string; + currency_pair: string; + account?: string; +} ⋮---- -/** - * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * - */ +export interface WSAPISpotOrderListReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: string; + from?: number; + to?: number; + side?: 'buy' | 'sell'; +} ⋮---- -private setupDefaultEventListeners() +// ==================================== +// Futures WebSocket API Request Types +// ==================================== ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +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'; +} ⋮---- -// Blind JSON.stringify can fail on circular references +export interface WSAPIFuturesOrderCancelReq { + order_id: string; +} ⋮---- -// 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 WSAPIFuturesOrderCancelCPReq { + contract: string; + side?: 'bid' | 'ask'; +} ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface WSAPIFuturesOrderAmendReq { + order_id: string; + price?: string; + size?: number; + amend_text?: string; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ +export interface WSAPIFuturesOrderListReq { + contract: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: number; +} ⋮---- -/** - * WS topics are always a string for gate. Some exchanges use complex objects - */ -export type WsTopic = string; +export interface WSAPIFuturesOrderStatusReq { + order_id: string; +} ⋮---- -export class WebsocketClient extends BaseWebsocketClient +// ==================================== +// Spot WebSocket API Response Types +// ==================================== ⋮---- -/** - * 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, -) +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; +} ⋮---- -/** - * WS API Methods - similar to the REST API, but via WebSockets - */ +export interface WSAPISpotOrderCancelIdsRespItem { + currency_pair: string; + id: string; + succeeded: boolean; +} ⋮---- -/** - * 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 - */ +// ==================================== +// Futures WebSocket API Response Types +// ==================================== ⋮---- -// 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; +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; +} ⋮---- -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 +export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { + succeeded: boolean; +} ⋮---- -// Some commands don't require authentication. +export interface WSAPIFuturesOrderCancelIdsRespItem { + id: string; + user_id: number; + succeeded?: boolean; + message?: string; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +// ==================================== +// Request Parameter Mapping +// ==================================== ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +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; +} ⋮---- -// id: timeInSeconds, +export type WsAPITopicRequestParams = + WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; ⋮---- -/** - * 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. - */ +// ==================================== +// Response Headers and Base Response +// ==================================== ⋮---- -// Sign request +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; +} ⋮---- -// Store deferred promise +/** String timestamp as ms */ ⋮---- -// Enrich returned promise with request context for easier debugging +/** Status of WS API call. "200" if successful, else exception is thrown */ ⋮---- -// throw e; +export interface WSAPILoginResponse { + api_key: string; + uid: string; +} ⋮---- -// Send event +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; +} ⋮---- -// Return deferred promise, so caller can await this call +export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; ⋮---- -/** - * - * Internal methods - not intended for public use - * - */ -⋮---- -protected getWsUrl(wsKey: WsKey): string +export interface WSAPIResponse< + TResponseData extends object = WSAPIResponseData | object, + TChannel extends WSAPITopic = WSAPITopic, +> { + wsKey: WsKey; + header: WSAPIResponseHeader; + data: { + result: TResponseData; + }; + /** Auto-generated */ + request_id: string; +} ⋮---- -protected sendPingEvent(wsKey: WsKey) +/** Auto-generated */ ⋮---- -protected sendPongEvent(wsKey: WsKey) +// ==================================== +// Response Type Mapping +// ==================================== ⋮---- -// Send a protocol layer pong +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' + >; +} ⋮---- -// 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 +// export interface WsAPIResponseMap { +// 'spot.login': WSAPIResponse; +// 'futures.login': WSAPIResponse; +// string: object; +// } + +================ +File: src/WebsocketAPIClient.ts +================ +import { DefaultLogger } from './lib/logger.js'; +import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; +import { WSClientConfigurableOptions } from './types/websockets/client.js'; +import { + WSAPIFuturesOrder, + WSAPIFuturesOrderAmendReq, + WSAPIFuturesOrderBatchPlaceRespItem, + WSAPIFuturesOrderCancelCPReq, + WSAPIFuturesOrderCancelIdsRespItem, + WSAPIFuturesOrderCancelReq, + WSAPIFuturesOrderListReq, + WSAPIFuturesOrderPlaceReq, + WSAPIFuturesOrderStatusReq, + WSAPIResponse, + WSAPISpotOrder, + WSAPISpotOrderAmendReq, + WSAPISpotOrderCancelCPReq, + WSAPISpotOrderCancelIdsReq, + WSAPISpotOrderCancelIdsRespItem, + WSAPISpotOrderCancelReq, + WSAPISpotOrderListReq, + WSAPISpotOrderPlaceReq, + WSAPISpotOrderStatusReq, + WSAPIWsKey, +} from './types/websockets/wsAPI.js'; +import { WebsocketClient } from './WebsocketClient.js'; ⋮---- -protected isWsPong(msg: any): boolean +/** + * 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; +} ⋮---- /** - * Parse incoming events into categories, before emitting to the user + * 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(....)`. */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] ⋮---- -// WS API Exception +/** + * 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 ⋮---- -// WS API Success +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -// 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. +public getWSClient(): WebsocketClient ⋮---- -// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) +public setTimeOffsetMs(newOffset: number): void ⋮---- -// Request/reply pattern for authentication success +/* + * + * SPOT - Trading requests + * + */ ⋮---- /** - * Determines if a topic is for a private channel, using a hardcoded list of strings + * Submit a spot order */ -protected isPrivateTopicRequest( - request: WsTopicRequest, - wsKey: WsKey, -): boolean -⋮---- -// No private announcements channels +submitNewSpotOrder( + params: WSAPISpotOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Not in use for gate.io + * Cancel a spot order */ -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket +cancelSpotOrder( + params: WSAPISpotOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Not in use for gate.io + * Cancel all spot orders with the given id list */ -protected getPrivateWSKeys(): WsKey[] +cancelSpotOrderById( + params: WSAPISpotOrderCancelIdsReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +/** + * Cancel a spot order for a given symbol + */ +cancelSpotOrderForSymbol( + params: WSAPISpotOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null +/** + * Update a spot order + */ +updateSpotOrder( + params: WSAPISpotOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) + * Get the status of a spot order */ -protected async getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: WsKey, - operation: WsOperation, -): Promise +getSpotOrderStatus( + params: WSAPISpotOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); -// console.trace(); +/** + * Get all spot orders + */ +getSpotOrders( + params: WSAPISpotOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// Events that are ready to send (usually stringified JSON) +/* + * + * Futures - Trading requests + * + */ ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + * Submit a futures order. + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -private async getWsRequestEvents( - market: WsMarket, - operation: WsOperation, - requests: WsTopicRequest[], - wsKey: WsKey, -): Promise[]> -⋮---- -// If private topic request, build auth part for request +submitNewFuturesOrder( + params: WSAPIFuturesOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// No key or secret, push event as failed +/** + * Submit a batch of futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +submitNewFuturesBatchOrder( + params: WSAPIFuturesOrderPlaceReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +/** + * Cancel a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrder( + params: WSAPIFuturesOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -protected async getWsAuthRequestEvent(wsKey: WsKey): Promise +/** + * Cancel futures orders by id list + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrderById( + params: string[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// id: timeInSeconds, +/** + * 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 * - * @param requestEvent - * @returns A signed updated WS API request object, ready to be sent + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ -private async signWSAPIRequest( - requestEvent: WSAPIRequest, -): Promise> - -================ -File: .eslintrc.cjs -================ -// 'no-unused-vars': ['warn'], - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} - -================ -File: jest.config.ts -================ +updateFuturesOrder( + params: WSAPIFuturesOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> +⋮---- /** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ + * Get all futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrders( + params: WSAPIFuturesOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -import type { Config } from 'jest'; +/** + * Get futures order status + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrderStatus( + params: WSAPIFuturesOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +/** + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * + */ ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +private setupDefaultEventListeners() ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +// Blind JSON.stringify can fail on circular references ⋮---- -// Indicates whether the coverage information should be collected while executing the test +// 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'; ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} ⋮---- -// The directory where Jest should output its coverage files +/** If true, will skip auth requirement for WS API connection */ ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +/** + * WS topics are always a string for gate. Some exchanges use complex objects + */ +export type WsTopic = string; ⋮---- -// Indicates which provider should be used to instrument code for coverage +export class WebsocketClient extends BaseWebsocketClient ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +/** + * 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[] ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +/** + * 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 ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +/** + * 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, +) ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +/** + * 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, +) ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +/** + * WS API Methods - similar to the REST API, but via WebSockets + */ ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +/** + * 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 + */ ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +// 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; ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +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 ⋮---- -// 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%", +// Some commands don't require authentication. ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -// An array of file extensions your modules use +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- -// modulePaths: ['src'], +// id: timeInSeconds, ⋮---- -// 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: {}, +/** + * 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. + */ ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +// Sign request ⋮---- -// Activates notifications for test results -// notify: false, +// Store deferred promise ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +// Enrich returned promise with request context for easier debugging ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +// throw e; ⋮---- -// Run tests from one or more projects -// projects: undefined, +// Send event ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +// Return deferred promise, so caller can await this call ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +/** + * + * Internal methods - not intended for public use + * + */ ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +protected getWsUrl(wsKey: WsKey): string ⋮---- -// A path to a custom resolver -// resolver: undefined, +protected sendPingEvent(wsKey: WsKey) ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +protected sendPongEvent(wsKey: WsKey) ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +// Send a protocol layer pong ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +// 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 ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +protected isWsPong(msg: any): boolean ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +/** + * Parse incoming events into categories, before emitting to the user + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +// WS API Exception ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +// WS API Success ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +// 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. ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +// Request/reply pattern for authentication success ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +/** + * Determines if a topic is for a private channel, using a hardcoded list of strings + */ +protected isPrivateTopicRequest( + request: WsTopicRequest, + wsKey: WsKey, +): boolean ⋮---- -// The glob patterns Jest uses to detect test files +// No private announcements channels ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", +/** + * Not in use for gate.io + */ ⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], +// eslint-disable-next-line @typescript-eslint/no-unused-vars +protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket ⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +/** + * Not in use for gate.io + */ +protected getPrivateWSKeys(): WsKey[] ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +/** 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 ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +/** + * 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 ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); +// console.trace(); ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +// Events that are ready to send (usually stringified JSON) ⋮---- -// 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, +/** + * @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[]> ⋮---- -// Indicates whether each individual test should be reported during the run -// verbose: undefined, -verbose: true, // report individual test +// If private topic request, build auth part for request ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +// No key or secret, push event as failed ⋮---- -// Whether to use watchman for file crawling -// watchman: true, +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: LICENSE.md +File: .eslintrc.cjs ================ -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. +// 'no-unused-vars': ['warn'], ================ -File: postBuild.sh +File: .prettierrc ================ -#!/bin/bash -# -# Add package.json files to cjs/mjs subtrees +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" +} + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ +⋮---- +import type { Config } from 'jest'; +⋮---- +// All imported modules in your tests should be mocked automatically +// automock: false, +⋮---- +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, +⋮---- +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +⋮---- +// Automatically clear mock calls, instances, contexts and results before every test +⋮---- +// Indicates whether the coverage information should be collected while executing the test +⋮---- +// An array of glob patterns indicating a set of files for which coverage information should be collected +⋮---- +// The directory where Jest should output its coverage files +⋮---- +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], +⋮---- +// Indicates which provider should be used to instrument code for coverage +⋮---- +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], +⋮---- +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, +⋮---- +// A path to a custom dependency extractor +// dependencyExtractor: undefined, +⋮---- +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, +⋮---- +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, +⋮---- +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], +⋮---- +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, +⋮---- +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, +⋮---- +// A set of global variables that need to be available in all test environments +// globals: {}, +⋮---- +// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. +// maxWorkers: "50%", +⋮---- +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], +⋮---- +// An array of file extensions your modules use +⋮---- +// modulePaths: ['src'], +⋮---- +// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module +// moduleNameMapper: {}, +⋮---- +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], +⋮---- +// Activates notifications for test results +// notify: false, +⋮---- +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", +⋮---- +// A preset that is used as a base for Jest's configuration +// preset: undefined, +⋮---- +// Run tests from one or more projects +// projects: undefined, +⋮---- +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, +⋮---- +// Automatically reset mock state before every test +// resetMocks: false, +⋮---- +// Reset the module registry before running each individual test +// resetModules: false, +⋮---- +// A path to a custom resolver +// resolver: undefined, +⋮---- +// Automatically restore mock state and implementation before every test +// restoreMocks: false, +⋮---- +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, +⋮---- +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], +⋮---- +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", +⋮---- +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], +⋮---- +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], +⋮---- +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, +⋮---- +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], +⋮---- +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", +⋮---- +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, +⋮---- +// Adds a location field to test results +// testLocationInResults: false, +⋮---- +// The glob patterns Jest uses to detect test files +⋮---- +// "**/__tests__/**/*.[jt]s?(x)", +⋮---- +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], +⋮---- +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], +⋮---- +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, +⋮---- +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", +⋮---- +// A map from regular expressions to paths to transformers +// transform: undefined, +⋮---- +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], +⋮---- +// Prevents import esm module error from v1 axios release, issue #5026 +⋮---- +// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them +// unmockedModulePathPatterns: undefined, +⋮---- +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test +⋮---- +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], +⋮---- +// Whether to use watchman for file crawling +// watchman: true, + +================ +File: LICENSE.md +================ +Copyright 2022 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: postBuild.sh +================ +#!/bin/bash +# +# Add package.json files to cjs/mjs subtrees # cat >dist/cjs/package.json < { + topic: TWSTopic; + payload?: TWSPayload; +} +⋮---- +/** + * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params) + */ +export type WsTopicRequestOrStringTopic< + TWSTopic extends string, + TWSPayload = any, +> = WsTopicRequest | string; +⋮---- +/** + * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges. + * Examples: + * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'> + * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'> + * - Only one livenet, no other networks: NetworkMap<'livenet'> + */ +type NetworkMap< + TRequiredKeys extends string, + TOptionalKeys extends string | undefined = undefined, +> = Record & + (TOptionalKeys extends string + ? Record + : Record); +⋮---- +// https://www.gate.com/docs/developers/apiv4/ws/en/ +⋮---- +// https://www.gate.com/docs/developers/options/ws/en/ +⋮---- +export function neverGuard(x: never, msg: string): Error +⋮---- +/** + * WS API promises are stored using a primary key. This key is constructed using + * properties found in every request & reply. + */ +export function getPromiseRefForWSAPIRequest( + requestEvent: WSAPIRequest, +): string +⋮---- +export function getPrivateSpotTopics(): string[] +⋮---- +// Consumeable channels for spot +⋮---- +// WebSocket API for spot +⋮---- +export function getPrivateFuturesTopics(): string[] +⋮---- +// These are the same for perps vs delivery futures +⋮---- +export function getPrivateOptionsTopics(): string[] +⋮---- +/** + * ws.terminate() is undefined in browsers. + * This only works in node.js, not in browsers. + * Does nothing if `ws` is undefined. Does nothing in browsers. + */ +export function safeTerminateWs( + ws?: WebSocket | any, + fallbackToClose?: boolean, +): boolean + +================ +File: src/lib/websocket/WsStore.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { DefaultLogger } from '../logger.js'; +import { + DeferredPromise, + WSConnectedResult, + WsConnectionStateEnum, WsStoredState, } from './WsStore.types.js'; ⋮---- @@ -4343,6 +4707,26 @@ export function appendGateMultipartFields( fields: Record, ): void +================ +File: src/types/request/announcement.ts +================ +/** POST /ann/list_article */ +⋮---- +export interface ListAnnouncementArticlesReq { + title_query?: string; + page?: string; + size?: string; + tags?: string; + timer?: string; + cate_name?: string; + cate_level?: string; + sub_website_id?: string; + pinned?: number; + update_after?: number; + lang?: string; + filter_empty_content?: number; +} + ================ File: src/types/request/options.ts ================ @@ -4534,99 +4918,6 @@ export interface GetPartnerAgentDataAggregatedReq { * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. */ -================ -File: src/types/request/stock.ts -================ -/** Stock / TradFi Spot API request types */ -⋮---- -export interface GetStockUserAssetsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; -} -⋮---- -export interface GetStockSymbolsReq { - symbols?: string; - exchange?: string; // us | hk | jp - with_desc_i18n?: boolean; - page?: number; - page_size?: number; -} -⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface GetStockSymbolDetailReq { - symbols?: string; - exchange?: string; // us | hk | jp - page?: number; - page_size?: number; -} -⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface GetStockOrdersReq { - symbol?: string; -} -⋮---- -export interface CreateStockOrderReq { - volume: string; - symbol: string; - side: 1 | 2; - price_type: 'market' | 'limit'; - /** Limit: all only; market: regular only */ - trading_session: 'all' | 'regular'; - time_in_force: 'day'; - price?: string; - client_order_id?: string; -} -⋮---- -/** Limit: all only; market: regular only */ -⋮---- -export interface GetStockOrderHistoryReq { - symbol?: string; - order_ids?: string; - begin_time?: number; - end_time?: number; - side?: 1 | 2; - page?: number; - page_size?: number; -} -⋮---- -export interface UpdateStockOrderReq { - volume: string; - price: string; -} -⋮---- -export interface GetStockPositionsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; - symbol?: string; - exchange?: string; // us | hk | jp -} -⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface CloseStockPositionReq { - symbol: string; - close_type: 1 | 2; - close_volume?: string; -} -⋮---- -export interface GetStockTransactionsReq { - begin_time?: number; - end_time?: number; - ref_id?: string; - type?: string; - page?: number; - page_size?: number; -} -⋮---- -export interface CreateStockTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; - ref_id: string; -} - ================ File: src/types/response/alpha.ts ================ @@ -4770,14 +5061,52 @@ volume: string; // 24h Trading Volume (USDT) market_cap: string; // Current Token Market Cap ================ -File: src/types/response/autoinvest.ts +File: src/types/response/announcement.ts ================ -/**========================================================================================================================== - * EARN AUTO INVEST - * ========================================================================================================================== - */ -⋮---- -/** POST /earn/autoinvest/plans/create — example response shape */ +export interface AnnouncementArticleLanguage { + code?: string; + name?: string; +} +⋮---- +export interface AnnouncementArticle { + id?: number; + title?: string; + brief?: string; + created?: string; + updated?: string; + release_time?: string; + views?: number; + author?: string; + author_id?: number; + tags?: string; + cate?: string; + is_top?: number; + cate_id?: number; + source?: string; + content_lang_list?: AnnouncementArticleLanguage[]; +} +⋮---- +export interface AnnouncementArticleListData { + list?: AnnouncementArticle[]; + total?: number; +} +⋮---- +export interface AnnouncementArticleListResponse { + code?: number; + data?: AnnouncementArticleListData; + message?: string; + version?: string; +} + +================ +File: src/types/response/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST + * ========================================================================================================================== + */ +⋮---- +/** POST /earn/autoinvest/plans/create — example response shape */ export interface CreateAutoInvestPlanResp { id: number; amount: string; @@ -4893,385 +5222,64 @@ export interface AutoInvestPlansListResp { } ================ -File: src/types/response/delivery.ts +File: src/types/response/marginuni.ts ================ /**========================================================================================================================== - * DELIVERY + * MARGIN UNI * ========================================================================================================================== */ ⋮---- -export interface DeliveryOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; +export interface LendingMarket { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; + status?: string | number; + delisted_time?: number; } ⋮---- -export interface DeliveryTrade { - id: number; +export interface MarginUNILoan { + currency: string; + currency_pair: string; + amount: string; + type: string; // Lending type, margin indicates margin borrowing create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated -} -⋮---- -is_internal?: boolean; // Deprecated -⋮---- -export interface DeliveryCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} -⋮---- -export interface DeliveryTicker { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; // Deprecated - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; + update_time: number; } ⋮---- -quanto_base_rate?: string; // Deprecated +type: string; // Lending type, margin indicates margin borrowing ⋮---- -export interface DeliveryAccount { - total: string; // Balance, only applicable to classic contract account - unrealised_pnl: string; - position_margin?: string; // Deprecated - order_margin: string; // Initial margin for all pending orders - available: string; - point: string; +export interface MarginUNILoanRecord { + type: string; + currency_pair: string; currency: string; - in_dual_mode: boolean; - position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic?: boolean; // Deprecated - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - isolated_position_margin: string; - enable_new_dual_mode?: boolean; // Deprecated - margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - enable_tiered_mm: boolean; -} -⋮---- -total: string; // Balance, only applicable to classic contract account -⋮---- -position_margin?: string; // Deprecated -order_margin: string; // Initial margin for all pending orders -⋮---- -position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) -⋮---- -enable_evolved_classic?: boolean; // Deprecated -⋮---- -enable_new_dual_mode?: boolean; // Deprecated -margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode -⋮---- -export interface DeliveryBook { - time: number; - change: string; - balance: string; - type: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; - text: string; - contract?: string; - trade_id?: string; -} -⋮---- -export interface DeliveryTradingHistoryRecord { - id: number; + amount: string; 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 MarginUNIInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; // Lending type, margin indicates margin borrowing + create_time: number; } ⋮---- -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; -} +type: string; // Lending type, margin indicates margin borrowing ⋮---- -export interface DeliverySettlementHistoryRecord { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - settle_price: string; - profit: string; - fee: string; +export interface MarginUNIMaxBorrowable { + currency: string; + currency_pair: string; + borrowable: string; } ================ -File: src/types/response/margin.ts +File: src/types/response/multicollateralLoan.ts ================ /**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ -⋮---- -export interface MarginAccount { - currency_pair: string; - locked: boolean; - risk: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; -} -⋮---- -export interface MarginBalanceHistoryRecord { - id: string; - time: string; - time_ms: number; - currency: string; - currency_pair: string; - change: string; - balance: string; - type: string; -} -⋮---- -export interface CrossMarginCurrency { - name: string; - rate: string; - prec: string; - discount: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - price: string; - loanable: boolean; - status: number; -} -⋮---- -export interface CrossMarginAccount { - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [currency: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - }; - }; - total: string; - borrowed: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - portfolio_margin_total: string; - portfolio_margin_total_liab: string; - portfolio_margin_total_equity: string; -} -⋮---- -export interface CrossMarginAccountHistoryRecord { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; -} -⋮---- -export interface CrossMarginMorrowLoanRecord { - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text?: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; -} -⋮---- -export interface MarginUserAccount { - currency_pair: string; - account_type: string; // Description updated to remove "risk" option - leverage: string; - locked: boolean; - risk?: string; // Deprecated - mmr?: string; // Refined description - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; -} -⋮---- -account_type: string; // Description updated to remove "risk" option -⋮---- -risk?: string; // Deprecated -mmr?: string; // Refined description - -================ -File: src/types/response/marginuni.ts -================ -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ -⋮---- -export interface LendingMarket { - currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; - status?: string | number; - delisted_time?: number; -} -⋮---- -export interface MarginUNILoan { - currency: string; - currency_pair: string; - amount: string; - type: string; // Lending type, margin indicates margin borrowing - create_time: number; - update_time: number; -} -⋮---- -type: string; // Lending type, margin indicates margin borrowing -⋮---- -export interface MarginUNILoanRecord { - type: string; - currency_pair: string; - currency: string; - amount: string; - create_time: number; -} -⋮---- -export interface MarginUNIInterestRecord { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; // Lending type, margin indicates margin borrowing - create_time: number; -} -⋮---- -type: string; // Lending type, margin indicates margin borrowing -⋮---- -export interface MarginUNIMaxBorrowable { - currency: string; - currency_pair: string; - borrowable: string; -} - -================ -File: src/types/response/multicollateralLoan.ts -================ -/**========================================================================================================================== - * MULTI COLLATERAL LOAN + * MULTI COLLATERAL LOAN * ========================================================================================================================== */ ⋮---- @@ -5440,297 +5448,41 @@ export interface MultiLoanFixedRate { } ================ -File: src/types/response/options.ts +File: src/types/response/rebate.ts ================ -/**========================================================================================================================== - * OPTIONS - * ========================================================================================================================== - */ -⋮---- -export interface OptionsContract { - name: string; - tag: string; // Expiry period: day, week, month - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id?: number; // Deprecated - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; // Forward futures price for the delivery date - multiplier: string; // Option contract multiplier - order_price_round: string; - mark_price_round: string; // Minimum unit of mark price - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate?: string; // Deprecated - order_size_min: number; - order_size_max: number; - orders_limit: number; // Maximum number of orders per user in this market +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; } ⋮---- -tag: string; // Expiry period: day, week, month -⋮---- -trade_id?: number; // Deprecated -⋮---- -underlying_price: string; // Forward futures price for the delivery date -multiplier: string; // Option contract multiplier +export interface AgencyCommissionHistoryRecord { + commission_time: number; + user_id: number; + group_name: string; + /** Rebate commission amount (not a generic trade notional). */ + commission_amount: string; + /** Asset of the rebate commission. */ + commission_asset: string; + source: string; +} ⋮---- -mark_price_round: string; // Minimum unit of mark price +/** Rebate commission amount (not a generic trade notional). */ ⋮---- -order_price_deviate?: string; // Deprecated +/** Asset of the rebate commission. */ ⋮---- -orders_limit: number; // Maximum number of orders per user in this market -⋮---- -export interface OptionsSettlementHistoryRecord { - time: number; - contract: string; - profit: string; - fee: string; - strike_price: string; - settle_price: string; -} -⋮---- -export interface OptionsUserSettlement { - time: number; - underlying: string; - contract: string; - strike_price: string; - settle_price: string; - size: number; - settle_profit: string; - fee: string; - realised_pnl: string; -} -⋮---- -export interface OptionsOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} -⋮---- -export interface OptionsTicker { - name: string; - last_price: string; - mark_price: string; - index_price: string; - ask1_size: number; - ask1_price: string; - bid1_size: number; - bid1_price: string; - position_size: number; - mark_iv: string; - bid_iv: string; - ask_iv: string; - leverage: string; // Leverage calculation formula updated with reference note - delta: string; - gamma: string; - vega: string; - theta: string; - rho: string; -} -⋮---- -leverage: string; // Leverage calculation formula updated with reference note -⋮---- -export interface OptionsCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} -⋮---- -export interface OptionsUnderlyingCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} -⋮---- -export interface OptionsTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated -} -⋮---- -is_internal?: boolean; // Deprecated -⋮---- -export interface OptionsAccount { - user: number; - total?: string; // Only applicable to classic options accounts (unified account limitation) - equity?: string; // Only applicable to classic options accounts (unified account limitation) - short_enabled: boolean; - unrealised_pnl: string; // Enhanced with calculation formula - init_margin: string; - maint_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - liq_triggered?: boolean; // Whether account is in liquidation status - margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode -} -⋮---- -total?: string; // Only applicable to classic options accounts (unified account limitation) -equity?: string; // Only applicable to classic options accounts (unified account limitation) -⋮---- -unrealised_pnl: string; // Enhanced with calculation formula -⋮---- -liq_triggered?: boolean; // Whether account is in liquidation status -margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode -⋮---- -export interface OptionsAccountChangeRecord { - time: number; - change: string; - balance: string; - type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - text: string; -} -⋮---- -export interface OptionsPositionsUnderlying { - user: number; - underlying: string; - underlying_price: string; // Forward futures price for the delivery date - contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; -} -⋮---- -underlying_price: string; // Forward futures price for the delivery date -⋮---- -export interface GetOptionsLiquidationResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - text: string; - settle_size: string; -} -⋮---- -export interface SubmitOptionsOrderResp { - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; -} -⋮---- -export interface OptionsUserHistoryRecord { - id: number; - create_time: number; - contract: string; - order_id: number; - size: number; - price: string; - underlying_price: string; // Forward futures price for the delivery date - role: 'taker' | 'maker'; -} -⋮---- -underlying_price: string; // Forward futures price for the delivery date -⋮---- -export interface OptionsMMPSettings { - underlying: string; - window: number; - frozen_period: number; - qty_limit: string; - delta_limit: string; - trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered - frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered -} -⋮---- -trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered -frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered - -================ -File: src/types/response/rebate.ts -================ -export interface AgencyTransactionHistoryRecord { - transaction_time: number; - user_id: number; - group_name: string; - fee: string; - fee_asset: string; - currency_pair: string; - amount: string; - amount_asset: string; - source: string; -} -⋮---- -export interface AgencyCommissionHistoryRecord { - commission_time: number; - user_id: number; - group_name: string; - /** Rebate commission amount (not a generic trade notional). */ - commission_amount: string; - /** Asset of the rebate commission. */ - commission_asset: string; - source: string; -} -⋮---- -/** Rebate commission amount (not a generic trade notional). */ -⋮---- -/** Asset of the rebate commission. */ -⋮---- -export interface PartnerSubordinate { - user_id: number; - user_join_time: number; - type: number; - desc: string; -} +export interface PartnerSubordinate { + user_id: number; + user_join_time: number; + type: number; + desc: string; +} ⋮---- export interface BrokerCommissionHistoryRecord { commission_time: number; @@ -5821,246 +5573,7 @@ export interface PartnerDataAggregatedResponse { } ================ -File: src/types/response/stock.ts -================ -export type StockCategory = - | 'CS' - | 'ETF' - | 'ADRC' - | 'ADR' - | 'ETV' - | 'PFD' - | 'ETS' - | 'ETN' - | 'FUND'; -⋮---- -export type StockAssetType = 'STOCK' | 'ETF'; -⋮---- -export interface StockApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; -} -⋮---- -export interface StockListData { - list?: T[]; - total?: number; - total_page?: number; -} -⋮---- -export interface StockUserAssets { - equity?: string; - balance?: string; - available?: string; - position_market_value?: string; - position_pnl?: string; - today_pnl?: string; - user_exists?: boolean; - option_position_market_value?: string; - option_position_pnl?: string; - option_today_pnl?: string; -} -⋮---- -export interface StockSymbolDescI18n { - lang?: string; - value?: string; -} -⋮---- -export interface StockSymbolItem { - symbol?: string; - exchange?: string; - exchange_desc?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - symbol_desc?: string; - category?: StockCategory | string; - asset_type?: StockAssetType; - trade_status?: string; - trade_mode?: number; - order_fill_timing?: number; - icon_link?: string; - quote_currency_symbol?: string; - price_precision?: number; - volume_precision?: number; - is_ipo?: boolean; - ipo_price?: string; - sell_price_protection?: string; - buy_price_protection?: string; - symbol_descs?: StockSymbolDescI18n[]; - timestamp?: number; -} -⋮---- -export interface StockSymbolDetailItem { - symbol?: string; - exchange?: string; - exchange_desc?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - symbol_desc?: string; - category?: StockCategory | string; - asset_type?: StockAssetType; - settlement_currency?: string; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - volume_precision?: number; - is_ipo?: boolean; - ipo_price?: string; - price_protection?: string; - sell_price_protection?: string; - buy_price_protection?: string; - slippage_rate?: string; - commission_rate?: string; - trade_status?: string; - trade_mode?: number; - order_fill_timing?: number; - symbol_descs?: StockSymbolDescI18n[]; - [key: string]: unknown; -} -⋮---- -export interface StockOrderBookLevel { - p?: string; - user_order?: boolean; - [key: string]: unknown; -} -⋮---- -export interface StockOrderBook { - symbol?: string; - bids?: StockOrderBookLevel[]; - asks?: StockOrderBookLevel[]; - timestamp?: number; -} -⋮---- -export interface StockOrderItem { - order_id?: string; - symbol?: string; - exchange?: string; - quote_currency?: string; - fx_rate?: string; - symbol_desc?: string; - trade_status?: string; - trade_mode?: number; - price_type?: string; - side?: number; - status?: number; - volume?: string; - fill_volume?: string; - price?: string; - time_setup?: number; - time_update?: number; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - price_protection?: string; - sell_price_protection?: string; - buy_price_protection?: string; - commission_rate?: string; - slippage_rate?: string; - [key: string]: unknown; -} -⋮---- -export interface StockCreateOrderResult { - id?: string; -} -⋮---- -export interface StockOrderHistoryItem { - order_id?: string; - symbol?: string; - exchange?: string; - quote_currency?: string; - fx_rate?: string; - symbol_desc?: string; - price_type?: string; - status?: number; - status_desc?: string; - status_detail?: { title?: string; message?: string } | null; - finish_as?: number; - side?: number; - time_in_force?: string; - volume?: string; - fill_volume?: string; - price?: string; - avg_fill_price?: string | null; - commission?: string; - time_setup?: number; - time_done?: number; - [key: string]: unknown; -} -⋮---- -export interface StockUpdateOrderResult { - order_id?: number; -} -⋮---- -export interface StockPositionItem { - symbol?: string; - exchange?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - trade_status?: string; - symbol_desc?: string; - position_pnl?: string; - today_pnl?: string; - pnl_rate?: string; - today_sell_amount?: string; - today_buy_amount?: string; - today_sell_volume?: string; - today_buy_volume?: string; - yesterday_volume?: string; - volume?: string; - available?: string; - transfer_out_pending_qty?: string; - avg_cost_price?: string; - diluted_cost_price?: string; - last_price?: string; - extended_last_price?: string | null; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - price_protection?: string; - [key: string]: unknown; -} -⋮---- -export interface StockClosePositionResult { - order_id?: number; -} -⋮---- -export interface StockTransactionItem { - asset?: string; - symbol?: string; - symbol_display?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - ref_id?: string; - time?: number; - unit_text?: string; - detail?: object; -} -⋮---- -export interface StockExchangeItem { - exchange?: string; - exchange_desc?: string; - icon_link?: string; - support_transfer?: boolean; -} -⋮---- -export interface StockFeeRateItem { - vip_level?: number; - maker_fee?: string; - taker_fee?: string; -} - -================ -File: src/types/response/withdrawal.ts +File: src/types/response/withdrawal.ts ================ export interface WithdrawalRecord { id: string; @@ -6117,72 +5630,141 @@ export interface WithdrawalRecord { | 'VERIFY'; // Verification in Progress ================ -File: src/types/shared.ts +File: .npmrc ================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'futuresTestnet'; +min-release-age=30 +save-exact=true + +================ +File: .nvmrc +================ +v24.18.0 + +================ +File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts +================ +import { readFileSync } from 'fs'; ⋮---- -// interfaces +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; -} +async function submitOTCBankPersonalSupplementExample() + +================ +File: src/lib/requestUtils.ts +================ +import WebSocket from 'isomorphic-ws'; ⋮---- -// Used for spot and flash swap -export interface CurrencyPair { - id?: string; - base?: string; - base_name?: string; - quote?: string; - quote_name?: string; - trade_quotes?: string[] | null; - fee?: string; - min_base_amount?: string; - min_quote_amount?: string; - max_base_amount?: string; - max_quote_amount?: string; - amount_precision?: number; - precision?: number; - trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; - sell_start?: number; - buy_start?: number; - type: string; - delisting_time?: number; - trade_url?: string; - up_rate?: string; // v4.106.4: Maximum price increase percentage - down_rate?: string; // v4.106.4: Maximum price decrease percentage - market_order_max_stock?: string | null; - market_order_max_money?: string | null; -} +import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- -up_rate?: string; // v4.106.4: Maximum price increase percentage -down_rate?: string; // v4.106.4: Maximum price decrease percentage +export interface RestClientOptions { + /** Your API key */ + apiKey?: string; -================ -File: .npmrc -================ -min-release-age=30 -save-exact=true + /** Your API secret */ + apiSecret?: string; -================ -File: .nvmrc -================ -v24.18.0 + /** + * 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; -================ -File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts -================ -import { readFileSync } from 'fs'; + /** 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; +} ⋮---- -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; +/** Your API key */ ⋮---- -async function submitOTCBankPersonalSupplementExample() +/** 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 +⋮---- +/** Global TestNet REST host. Gate docs: spot and futures. */ +⋮---- +// Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. +⋮---- +export function getRestBaseUrl(restClientOptions: RestClientOptions): string +⋮---- +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} +⋮---- +export function isMessageEvent(msg: unknown): msg is MessageEventLike ================ File: src/types/request/alpha.ts @@ -6539,6 +6121,99 @@ export interface P2PMerchantUploadChatFileReq { base64_img: string; } +================ +File: src/types/request/stock.ts +================ +/** Stock / TradFi Spot API request types */ +⋮---- +export interface GetStockUserAssetsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; +} +⋮---- +export interface GetStockSymbolsReq { + symbols?: string; + exchange?: string; // us | hk | jp + with_desc_i18n?: boolean; + page?: number; + page_size?: number; +} +⋮---- +exchange?: string; // us | hk | jp +⋮---- +export interface GetStockSymbolDetailReq { + symbols?: string; + exchange?: string; // us | hk | jp + page?: number; + page_size?: number; +} +⋮---- +exchange?: string; // us | hk | jp +⋮---- +export interface GetStockOrdersReq { + symbol?: string; +} +⋮---- +export interface CreateStockOrderReq { + volume: string; + symbol: string; + side: 1 | 2; + price_type: 'market' | 'limit'; + /** Limit: all only; market: regular only */ + trading_session: 'all' | 'regular'; + time_in_force: 'day'; + price?: string; + client_order_id?: string; +} +⋮---- +/** Limit: all only; market: regular only */ +⋮---- +export interface GetStockOrderHistoryReq { + symbol?: string; + order_ids?: string; + begin_time?: number; + end_time?: number; + side?: 1 | 2; + page?: number; + page_size?: number; +} +⋮---- +export interface UpdateStockOrderReq { + volume: string; + price: string; +} +⋮---- +export interface GetStockPositionsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; + symbol?: string; + exchange?: string; // us | hk | jp +} +⋮---- +exchange?: string; // us | hk | jp +⋮---- +export interface CloseStockPositionReq { + symbol: string; + close_type: 1 | 2; + close_volume?: string; +} +⋮---- +export interface GetStockTransactionsReq { + begin_time?: number; + end_time?: number; + ref_id?: string; + type?: string; + page?: number; + page_size?: number; +} +⋮---- +export interface CreateStockTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; + ref_id: string; +} + ================ File: src/types/response/p2pMerchant.ts ================ @@ -6835,8020 +6510,7846 @@ restClientRegex.ts testfile.ts ================ -File: docs/GATE_SDK_QUICKSTART_GUIDE.md +File: examples/Rest/futures/testnet.ts ================ - - -# Gate API JavaScript Tutorial for Node.js - - - -> [!TIP] -> Read this guide in tutorial format on the Siebly website: [Gate JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/gate/javascript/tutorial) - - - -This tutorial uses [`gateio-api`](https://www.npmjs.com/package/gateio-api), Siebly's Node.js, JavaScript, and TypeScript SDK for Gate.com. It covers public and private REST API calls, Spot and Futures TestNet orders, live WebSocket streams, WebSocket API commands, API hosts, and proxies. - -The SDK handles REST API request signing, private WebSocket authentication, product-specific WebSocket routing, heartbeats, reconnects, resubscriptions, and WebSocket API response matching. Request and response types are included for TypeScript users. - -**Key links** - -- Gate JavaScript SDK by Siebly: [`gateio-api`](https://siebly.io/sdk/gate/javascript) -- npm package: [`gateio-api`](https://www.npmjs.com/package/gateio-api) -- GitHub repository: [`sieblyio/gateio-api`](https://github.com/sieblyio/gateio-api) -- SDK examples: [Gate SDK examples](https://siebly.io/examples/Gate) -- SDK endpoint map: [Gate JavaScript endpoint reference](./endpointFunctionList.md) -- Gate REST API documentation: [Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) -- Gate Spot WebSocket documentation: [Spot WebSocket API](https://www.gate.com/docs/developers/apiv4/ws/) -- Gate Futures WebSocket documentation: [Futures WebSocket API](https://www.gate.com/docs/developers/futures/ws/) -- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) -- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) - -## Why use `gateio-api`? - -The JavaScript SDK handles all the complexities of integrating with Gate's REST APIs & WebSockets, so you can focus on your system without wasting excessive time on plumbing. - -Private Gate REST API requests require a timestamp and HMAC-SHA512 signature. Private WebSocket subscriptions require authentication, and each product family has its own WebSocket connection. A Spot subscription cannot be sent through a USDT perpetual Futures connection. - -`gateio-api` handles those mechanics and gives each job a focused client: +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) +⋮---- +// Define the account object with API key and secret +⋮---- +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret +⋮---- +// Initialize the RestClient with the API credentials +⋮---- +async function submitFuturesOrder() +⋮---- +// Submit a market order for futures trading +⋮---- +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract +size: 20, // Order size: positive for long, negative for short +price: '0', // Market order, so price is set to '0' +tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) +⋮---- +console.log('Response: ', result); // Log the response to the console +⋮---- +console.error('Error in execution: ', e); // Log any errors that occur +⋮---- +// Execute the function to submit a futures order -| Client | Use it for | -| -------------------- | ------------------------------------------------------------ | -| `RestClient` | Public and private REST API calls across Gate product groups | -| `WebsocketClient` | Public and private WebSocket subscriptions | -| `WebsocketAPIClient` | Promise-based Spot and Futures order commands over WebSocket | - -`WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. - -## Install the SDK - -```bash -npm install gateio-api -``` - -The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. - -## Create Gate API keys - -Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. - -Create and manage keys from the [Gate API key page](https://www.gate.com/myaccount/api_key_manage). Start with the least access your application needs: - -- Use a read-only key while building account views and recovery code. -- Enable Spot read-write access only for Spot order workflows. -- Enable perpetual-contract read-write access only for Futures order workflows. -- Add an IP whitelist when your outbound IP is stable. -- Keep live and TestNet credentials separate. -- Allow a few minutes for API key and permission changes to take effect. -- Do not enable withdrawal permission for anything in this tutorial. - -Set these live credential names in your shell, secret manager, or deployment environment: - -- `GATE_API_KEY` -- `GATE_API_SECRET` - -Use separate names for TestNet: - -- `GATE_TESTNET_API_KEY` -- `GATE_TESTNET_API_SECRET` -- `GATE_PLACE_TESTNET_ORDER=true` - -The order examples check `GATE_PLACE_TESTNET_ORDER` before sending an order. Do not log API keys or secrets, and never put them in browser code. - -## Gate products and request vocabulary - -Several short fields determine where a request goes and what its values mean: - -| Field | Example | Meaning | -| --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- | -| `currency_pair` | `BTC_USDT` | A Spot or margin market | -| `account` | `spot` | The account used by a Spot order or query | -| `settle` | `usdt` | The settlement currency for a Futures or Delivery REST API request | -| `contract` | `BTC_USDT` | The exact Futures, Delivery, or Options contract | -| `size` | `1` or `-1` | Futures contract count, not a BTC or USDT amount | -| `text` | `t-my-order-123` | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id) | -| `wsKey` | `WS_KEY_MAP.perpFuturesUSDTV4` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) that selects a product connection | - -For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. - -For USDT perpetual Futures, use `settle: 'usdt'` and a contract such as `BTC_USDT`. The `size` is a number of contracts. In one-way mode, a positive size buys and a negative size sells. The contract's `quanto_multiplier` tells you how much underlying currency one contract represents. - -Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. - - - -## Start building: first calls and streams - -Run each example on its own. Start with public data, then add authenticated account state and live streams. - -### 1. Make public REST API calls - -Public calls need no API key. Gate response bodies are endpoint-specific: server time and order books are objects, tickers are arrays, and candles are tuple arrays. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient(); - -async function main() { - try { - const time = await client.getServerTime(); - console.log('Server time:', time.server_time); - } catch (error) { - console.error('Server time request failed:', error); - } - - try { - const pair = await client.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - console.log('BTC_USDT metadata:', pair); - } catch (error) { - console.error('Currency pair request failed:', error); - } - - try { - const tickers = await client.getSpotTicker({ - currency_pair: 'BTC_USDT', - }); - console.log('BTC_USDT ticker:', tickers[0]); - } catch (error) { - console.error('Ticker request failed:', error); - } - - try { - const orderBook = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - console.log('Best bid:', orderBook.bids[0]); - console.log('Best ask:', orderBook.asks[0]); - } catch (error) { - console.error('Order book request failed:', error); - } - - try { - const candles = await client.getSpotCandles({ - currency_pair: 'BTC_USDT', - interval: '1h', - limit: 10, - }); - console.log('Latest candle:', candles[0]); - } catch (error) { - console.error('Candles request failed:', error); - } +================ +File: src/types/request/earn.ts +================ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ +⋮---- +/** GET /earn/dual/investment_plan */ +export interface GetDualInvestmentPlansReq { + plan_id?: number | string; + coin?: string; + type?: string; + quote_currency?: string; + /** `apy` | `short-period` | `multiple` */ + sort?: string; + page?: number; + page_size?: number; } - -main(); -``` - -The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. - -Each Spot candle is a tuple: - -```text -[ - timestamp, - quoteVolume, - close, - high, - low, - open, - baseVolume, - closed -] -``` - -Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. - -### 2. Make private REST API calls - -Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -async function main() { - try { - const balances = await client.getSpotAccounts(); - console.log('Spot balances:', balances); - } catch (error) { - console.error('Balance request failed:', error); - } - - try { - const openOrders = await client.getSpotOpenOrders({ - account: 'spot', - }); - console.log('Open Spot orders grouped by pair:', openOrders); - } catch (error) { - console.error('Open-order request failed:', error); - } - - try { - const recentOrders = await client.getSpotOrders({ - currency_pair: 'BTC_USDT', - status: 'finished', - account: 'spot', - limit: 20, - }); - console.log('Recent BTC_USDT orders:', recentOrders); - } catch (error) { - console.error('Order-history request failed:', error); - } - - try { - const trades = await client.getSpotTradingHistory({ - currency_pair: 'BTC_USDT', - account: 'spot', - limit: 20, - }); - console.log('Recent BTC_USDT trades:', trades); - } catch (error) { - console.error('Trade-history request failed:', error); - } +⋮---- +/** `apy` | `short-period` | `multiple` */ +⋮---- +/** GET /earn/dual/orders */ +export interface GetDualInvestmentOrdersReq { + from?: number; + to?: number; + type?: string; + status?: string; + coin?: string; + page?: number; + limit?: number; } - -main(); -``` - -`getSpotAccounts()`, `getSpotOrders()`, and `getSpotTradingHistory()` return arrays. `getSpotOpenOrders()` returns an array whose entries group open orders by currency pair. Other private endpoints return objects or different array shapes, so check the [SDK endpoint map](./endpointFunctionList.md) instead of assuming a common format. - -### 3. Subscribe to public WebSocket streams - -Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. - - - -```javascript -import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const ws = new WebsocketClient(); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('WebSocket update:', update); -}); - -ws.on('reconnect', ({ wsKey }) => { - console.log('Reconnecting:', wsKey); -}); - -ws.on('reconnected', (event) => { - console.log('Reconnected:', event.wsKey); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Spot subscription failed:', error); +⋮---- +/** GET /earn/dual/order-refund-preview */ +export interface GetDualOrderRefundPreviewReq { + order_id: string; } - -try { - ws.subscribe( - { - topic: 'futures.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.perpFuturesUSDTV4, - ); -} catch (error) { - console.error('Futures subscription failed:', error); +⋮---- +/** POST /earn/dual/order-refund */ +export interface SubmitDualOrderRefundParams { + order_id: string; + /** From order-refund-preview */ + req_id: string; } - -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -Gate sends Spot ticker data as an object in `result`, while a Futures ticker update can contain an array. The SDK adds `wsKey` to each update so one event handler can identify the source connection. - -The main WebSocket events are: - -| Event | Meaning | -| --------------- | ------------------------------------------------------------- | -| `open` | A connection opened for the reported `wsKey` | -| `response` | Subscription, unsubscription, or request response | -| `update` | Market or account data | -| `authenticated` | A private connection authenticated successfully | -| `reconnect` | The connection dropped and a reconnect is starting | -| `reconnected` | The connection is open and cached subscriptions were restored | -| `close` | A connection closed for the reported `wsKey` | -| `exception` | The client or connection reported an error | - -A successful `response` event confirms the [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). It does not mean that a market update has arrived yet. - -### 4. Subscribe to private Spot streams - -Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. - - - -```javascript -import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -ws.on('authenticated', ({ wsKey }) => { - console.log('Authenticated:', wsKey); -}); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('Private Spot update:', update); -}); - -ws.on('reconnected', (event) => { - console.log('Reconnected:', event.wsKey); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Balance subscription failed:', error); +⋮---- +/** From order-refund-preview */ +⋮---- +/** POST /earn/dual/modify-order-reinvest */ +export interface UpdateDualOrderReinvestParams { + order_id?: number; + /** 0 off, 1 on */ + status?: number; + /** Effective duration in seconds; default 86400 */ + effective_time_duration?: number; } - -try { - ws.subscribe( - { - topic: 'spot.orders', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Order subscription failed:', error); +⋮---- +/** 0 off, 1 on */ +⋮---- +/** Effective duration in seconds; default 86400 */ +⋮---- +/** GET /earn/dual/project-recommend */ +export interface GetDualProjectRecommendReq { + mode?: string; + coin?: string; + type?: string; + /** Comma-separated project IDs to exclude */ + history_pids?: string; } - -try { - ws.subscribe( - { - topic: 'spot.usertrades', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Trade subscription failed:', error); +⋮---- +/** Comma-separated project IDs to exclude */ +⋮---- +/** Request params for POST /earn/dual/orders */ +export interface PlaceDualInvestmentOrderParams { + plan_id: string; + /** Subscription amount. Mutually exclusive with copies. */ + amount: string; + /** Units. Mutually exclusive with amount. */ + copies?: string; + /** Custom order info, must start with t- */ + text?: string; } +⋮---- +/** Subscription amount. Mutually exclusive with copies. */ +⋮---- +/** Units. Mutually exclusive with amount. */ +⋮---- +/** Custom order info, must start with t- */ +⋮---- +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ +⋮---- +export interface GetEarnFixedTermProductsReq { + asset?: string; + type?: number; // 1 regular, 2 VIP + page: number; + limit: number; +} +⋮---- +type?: number; // 1 regular, 2 VIP +⋮---- +export interface GetEarnFixedTermProductsByAssetReq { + /** Product type: "" or 1 regular, 2 VIP, 0 all */ + type?: string; +} +⋮---- +/** Product type: "" or 1 regular, 2 VIP, 0 all */ +⋮---- +export interface CreateEarnFixedTermLendReq { + product_id: number; + amount: string; + year_rate?: string; + reinvest_status?: number; // 0 off, 1 on + redeem_account_type?: number; // 1 spot + financial_rate_id?: number; // interest boost coupon id, 0 = none + sub_business?: number; +} +⋮---- +reinvest_status?: number; // 0 off, 1 on +redeem_account_type?: number; // 1 spot +financial_rate_id?: number; // interest boost coupon id, 0 = none +⋮---- +export interface GetEarnFixedTermLendsReq { + product_id?: number; + order_id?: number; + asset?: string; + order_type: '1' | '2'; // 1 current, 2 historical + page: number; + limit: number; + sub_business?: number; + business_filter?: string; +} +⋮---- +order_type: '1' | '2'; // 1 current, 2 historical +⋮---- +export interface EarnFixedTermPreRedeemReq { + order_id: string; +} +⋮---- +export interface GetEarnFixedTermHistoryReq { + product_id?: number; + order_id?: string; + asset?: string; + type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus + page: number; + limit: number; + start_at?: number; + end_at?: number; + sub_business?: number; + business_filter?: string; +} +⋮---- +type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -Use the `authenticated` event as a connection-level signal. Use private updates as [private stream confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) of account and order changes. - -Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. - -### 5. Subscribe to private Futures streams - -Futures private channels use your Gate user ID. Contract-specific channels also include the contract. Retrieve the user ID once from the REST API, then use the payload required by each channel. - -```javascript -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -ws.on('authenticated', ({ wsKey }) => { - console.log('Authenticated:', wsKey); -}); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('Private Futures update:', update); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -async function main() { - let account; - - try { - account = await rest.getAccountDetail(); - console.log('Gate user ID:', account.user_id); - } catch (error) { - console.error('Account detail request failed:', error); - return; - } - - const userId = String(account.user_id); - const payload = [userId, 'BTC_USDT']; - const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; - - try { - ws.subscribe( - { - topic: 'futures.orders', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Order subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.usertrades', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Trade subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.balances', - payload: [userId], - }, - wsKey, - ); - } catch (error) { - console.error('Balance subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.positions', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Position subscription failed:', error); - } +================ +File: src/types/request/unified.ts +================ +export interface SubmitUnifiedBorrowOrRepayReq { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; +} +⋮---- +export interface GetUnifiedLoansReq { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; +} +⋮---- +export interface GetUnifiedLoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + page?: number; + limit?: number; +} +export interface GetUnifiedInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'platform' | 'margin'; +} +⋮---- +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + use_funding?: boolean; + options?: boolean; + }; +} +⋮---- +export interface PortfolioMarginCalculatorReq { + spot_balances?: { + currency: string; + equity: string; + }[]; + spot_orders?: { + currency_pairs: string; + order_price: string; + count?: string; + left: string; + type: 'sell' | 'buy'; + }[]; + futures_positions?: { + contract: string; + size: string; + }[]; + futures_orders?: { + contract: string; + size: string; + left: string; + }[]; + options_positions?: { + options_name: string; + size: string; + }[]; + options_orders?: { + options_name: string; + size: string; + left: string; + }[]; + spot_hedge?: boolean; +} +⋮---- +export interface GetUnifiedHistoryLendingRateReq { + currency: string; + tier?: string; + page?: number; + limit?: number; +} +⋮---- +export interface SubmitUnifiedLoanRepayReq { + currency: string; + amount: string; + currency_pair?: string; +} +⋮---- +export interface SetUnifiedCollateralCurrenciesReq { + collateral_type?: 0 | 1; + enable_list?: string[]; + disable_list?: string[]; +} +⋮---- +export interface CreateQuickRepaymentReq { + debt_currencies: string[]; + available_currencies: string[]; +} +⋮---- +/** POST /unified/delta_neutral — v4.106.97 */ +export interface SetUnifiedDeltaNeutralReq { + enabled: boolean; +} +⋮---- +/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ +export interface SetUserLeverageReq { + leverage?: string; } -process.once('SIGINT', () => { - ws.closeAll(); -}); - -main(); -``` - -Keep the `wsKey` aligned with the settlement currency and product. USDT perpetual Futures use `WS_KEY_MAP.perpFuturesUSDTV4`; BTC perpetual Futures use `WS_KEY_MAP.perpFuturesBTCV4`. - -Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. - -### 6. Place and cancel a Spot order in TestNet - -Gate TestNet uses separate credentials and API hosts. This example: - -1. Checks the explicit order opt-in. -2. Loads current `BTC_USDT` trading rules and the order book. -3. Calculates an amount that meets the pair's base and quote minimums. -4. Places a post-only limit buy at the current best bid. -5. Queries the order and cancels it if it remains open. - -The order uses `time_in_force: 'poc'`, Gate's post-only setting. A fast market can move before the request arrives, in which case Gate can reject or finish the order instead of leaving it on the book. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let pair; - - try { - pair = await client.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - } catch (error) { - console.error('Currency pair request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { - console.error('BTC_USDT is not currently buyable.'); - return; - } - - const price = orderBook.bids[0]?.[0]; - const amountPrecision = pair.amount_precision; - const minBase = Number(pair.min_base_amount); - const minQuote = Number(pair.min_quote_amount); - const priceNumber = Number(price); - - if ( - !price || - amountPrecision === undefined || - !Number.isFinite(minBase) || - !Number.isFinite(minQuote) || - !Number.isFinite(priceNumber) || - priceNumber <= 0 - ) { - console.error('Required market metadata is unavailable.'); - return; - } - - const amountStep = 10 ** -amountPrecision; - const minimumAmount = Math.max(minBase, minQuote / priceNumber); - const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; - const amount = amountNumber.toFixed(amountPrecision); - - if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { - console.error('Could not derive a valid TestNet order.'); - return; - } - - const maxBase = Number(pair.max_base_amount); - const maxQuote = Number(pair.max_quote_amount); - - if ( - (Number.isFinite(maxBase) && amountNumber > maxBase) || - (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) - ) { - console.error('Derived amount exceeds the pair limits.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - let placedOrder; - - try { - placedOrder = await client.submitSpotOrder({ - currency_pair: 'BTC_USDT', - account: 'spot', - side: 'buy', - type: 'limit', - amount, - price, - time_in_force: 'poc', - text, - }); - console.log('Placed Spot order:', placedOrder); - } catch (error) { - console.error('Spot order placement failed:', error); - return; - } - - if (!placedOrder.id) { - console.error('Gate did not return an order ID.'); - return; - } - - let currentOrder; - - try { - currentOrder = await client.getSpotOrder({ - order_id: placedOrder.id, - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Current Spot order:', currentOrder); - } catch (error) { - console.error('Spot order query failed:', error); - } - - if (currentOrder && currentOrder.status !== 'open') { - console.log('Order is no longer open:', currentOrder.status); - return; - } - - try { - const cancelledOrder = await client.cancelSpotOrder({ - order_id: placedOrder.id, - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Cancelled Spot order:', cancelledOrder); - } catch (error) { - console.error('Spot order cancellation failed:', error); - } +================ +File: src/types/request/wallet.ts +================ +/** GET /wallet/sub_account_balances */ +export interface GetSubAccountBalancesReq { + sub_uid?: string; + page?: number; + limit?: number; +} +⋮---- +export interface GetWithdrawalDepositRecordsReq { + currency?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface SubmitTransferReq { + currency: string; + from: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; + to: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; + amount: string; + currency_pair?: string; + settle?: string; + client_order_id?: string; +} +⋮---- +export interface GetMainSubTransfersReq { + sub_uid?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface GetSavedAddressReq { + currency?: string; // v4.106.94: Optional filter by currency + chain?: string; + limit?: string; + page?: number; + verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +} +⋮---- +currency?: string; // v4.106.94: Optional filter by currency +⋮---- +verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +⋮---- +export interface GetSmallBalanceHistoryReq { + currency?: string; + page?: number; + limit?: number; +} +⋮---- +export interface ListPushOrdersReq { + id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; + transaction_type?: string; +} +⋮---- +export interface SubmitSubToSubTransferReq { + currency: string; + sub_account_from: string; + sub_account_from_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; + sub_account_to: string; + sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; + amount: string; + sub_account_type?: string; +} +⋮---- +export interface SubmitMainSubTransferReq { + currency: string; + sub_account: string; + direction: 'to' | 'from'; + amount: string; + client_order_id?: string; + sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; +} +⋮---- +/** GET /wallet/transfers */ +export interface GetTransferReq { + tx_id: string; } -main(); -``` - -The extra amount increment avoids falling just below the quote minimum after decimal rounding. Before using another pair, read its `amount_precision`, `precision`, minimums, maximums, and `trade_status`. - -### 7. Place and cancel a USDT perpetual order in TestNet - -A Futures `size` is a contract count. It is not an amount of BTC or USDT. This example reads the contract's minimum size and current price, and it only runs when the account is in one-way mode. It does not change account or position settings. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let contract; - - try { - contract = await client.getFuturesContract({ - settle: 'usdt', - contract: 'BTC_USDT', - }); - } catch (error) { - console.error('Contract request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await client.getFuturesOrderBook({ - settle: 'usdt', - contract: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - let account; - - try { - account = await client.getFuturesAccount({ - settle: 'usdt', - }); - } catch (error) { - console.error('Futures account request failed:', error); - return; - } - - const oneWayMode = account.position_mode - ? account.position_mode === 'single' - : !account.in_dual_mode; - - if (!oneWayMode) { - console.error('This example requires one-way Futures position mode.'); - return; - } - - if (contract.status && contract.status !== 'trading') { - console.error('BTC_USDT Futures is not currently trading.'); - return; - } - - const price = orderBook.bids[0]?.p; - const size = Number(contract.order_size_min); - - if ( - !price || - !Number.isFinite(Number(price)) || - Number(price) <= 0 || - !Number.isFinite(size) || - size <= 0 || - (contract.enable_decimal === false && !Number.isInteger(size)) - ) { - console.error('Required contract metadata is unavailable.'); - return; - } - - console.log('One contract represents:', contract.quanto_multiplier, 'BTC'); - console.log('Price increment:', contract.order_price_round); - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - let placedOrder; - - try { - placedOrder = await client.submitFuturesOrder({ - settle: 'usdt', - contract: 'BTC_USDT', - size, - price, - tif: 'poc', - text, - }); - console.log('Placed Futures order:', placedOrder); - } catch (error) { - console.error('Futures order placement failed:', error); - return; - } - - if (placedOrder.id === undefined) { - console.error('Gate did not return an order ID.'); - return; - } - - const orderId = String(placedOrder.id); - let currentOrder; - - try { - currentOrder = await client.getFuturesOrder({ - settle: 'usdt', - order_id: orderId, - }); - console.log('Current Futures order:', currentOrder); - } catch (error) { - console.error('Futures order query failed:', error); - } - - if (currentOrder && currentOrder.status !== 'open') { - console.log('Order is no longer open:', currentOrder.status); - return; - } - - try { - const cancelledOrder = await client.cancelFuturesOrder({ - settle: 'usdt', - order_id: orderId, - }); - console.log('Cancelled Futures order:', cancelledOrder); - } catch (error) { - console.error('Futures order cancellation failed:', error); - } +================ +File: src/types/response/stock.ts +================ +export type StockCategory = + | 'CS' + | 'ETF' + | 'ADRC' + | 'ADR' + | 'ETV' + | 'PFD' + | 'ETS' + | 'ETN' + | 'FUND'; +⋮---- +export type StockAssetType = 'STOCK' | 'ETF'; +⋮---- +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; +⋮---- +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; +⋮---- +export interface StockApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: string; } - -main(); -``` - -In one-way mode, a positive `size` buys and a negative `size` sells. Dual-side mode uses different position semantics, so handle it in account-specific code after reading the [official Gate API v4 documentation](https://www.gate.com/docs/developers/apiv4/en/). - -The contract metadata supplies the size and price rules: - -- `order_size_min`: minimum contract count -- `order_price_round`: permitted price increment -- `quanto_multiplier`: underlying amount represented by one contract -- `enable_decimal`: whether fractional contract sizes are supported - -Do not derive a Futures order size from Spot precision rules. - -### 8. Send a Spot order through the WebSocket API - -`WebsocketAPIClient` turns Gate WebSocket API commands into promises. It connects and authenticates automatically on the first private command, adds a request ID, matches the response, and resolves the promise. - -This TestNet example uses the REST API only to read current market rules and the order book. The order, query, and cancellation use the WebSocket API. - - - -```javascript -import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let pair; - - try { - pair = await rest.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - } catch (error) { - console.error('Currency pair request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await rest.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { - console.error('BTC_USDT is not currently buyable.'); - return; - } - - const price = orderBook.bids[0]?.[0]; - const amountPrecision = pair.amount_precision; - const minBase = Number(pair.min_base_amount); - const minQuote = Number(pair.min_quote_amount); - const priceNumber = Number(price); - - if ( - !price || - amountPrecision === undefined || - !Number.isFinite(minBase) || - !Number.isFinite(minQuote) || - !Number.isFinite(priceNumber) || - priceNumber <= 0 - ) { - console.error('Required market metadata is unavailable.'); - return; - } - - const amountStep = 10 ** -amountPrecision; - const minimumAmount = Math.max(minBase, minQuote / priceNumber); - const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; - const amount = amountNumber.toFixed(amountPrecision); - - if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { - console.error('Could not derive a valid TestNet order.'); - return; - } - - const maxBase = Number(pair.max_base_amount); - const maxQuote = Number(pair.max_quote_amount); - - if ( - (Number.isFinite(maxBase) && amountNumber > maxBase) || - (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) - ) { - console.error('Derived amount exceeds the pair limits.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - const wsKey = WS_KEY_MAP.spotV4; - - try { - let placedResponse; - - try { - placedResponse = await wsApi.submitNewSpotOrder( - { - currency_pair: 'BTC_USDT', - account: 'spot', - side: 'buy', - type: 'limit', - amount, - price, - time_in_force: 'poc', - text, - }, - wsKey, - ); - console.log('Command status:', placedResponse.header.status); - console.log('Placed Spot order:', placedResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API placement failed:', error); - return; - } - - const orderId = placedResponse.data.result.id; - let statusResponse; - - try { - statusResponse = await wsApi.getSpotOrderStatus( - { - order_id: orderId, - currency_pair: 'BTC_USDT', - account: 'spot', - }, - wsKey, - ); - console.log('Current Spot order:', statusResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API query failed:', error); - } - - if (statusResponse && statusResponse.data.result.status !== 'open') { - console.log( - 'Order is no longer open:', - statusResponse.data.result.status, - ); - return; - } - - try { - const cancelledResponse = await wsApi.cancelSpotOrder( - { - order_id: orderId, - currency_pair: 'BTC_USDT', - account: 'spot', - }, - wsKey, - ); - console.log('Cancelled Spot order:', cancelledResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API cancellation failed:', error); - } - } finally { - wsApi.getWSClient().closeAll(); - } +⋮---- +export interface StockListData { + list?: T[]; + total?: number; + total_page?: number; } - -main(); -``` - -### 9. Send a USDT perpetual order through the WebSocket API - -Futures WebSocket API commands use a product-specific WebSocket key. Pass it explicitly so the contract and connection remain clear. - - - -```javascript -import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/futures/usdt', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let contract; - - try { - contract = await rest.getFuturesContract({ - settle: 'usdt', - contract: 'BTC_USDT', - }); - } catch (error) { - console.error('Contract request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await rest.getFuturesOrderBook({ - settle: 'usdt', - contract: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - let account; - - try { - account = await rest.getFuturesAccount({ - settle: 'usdt', - }); - } catch (error) { - console.error('Futures account request failed:', error); - return; - } - - const oneWayMode = account.position_mode - ? account.position_mode === 'single' - : !account.in_dual_mode; - - if (!oneWayMode) { - console.error('This example requires one-way Futures position mode.'); - return; - } - - if (contract.status && contract.status !== 'trading') { - console.error('BTC_USDT Futures is not currently trading.'); - return; - } - - const price = orderBook.bids[0]?.p; - const size = Number(contract.order_size_min); - - if ( - !price || - !Number.isFinite(Number(price)) || - Number(price) <= 0 || - !Number.isFinite(size) || - size <= 0 || - (contract.enable_decimal === false && !Number.isInteger(size)) - ) { - console.error('Required contract metadata is unavailable.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; - - try { - let placedResponse; - - try { - placedResponse = await wsApi.submitNewFuturesOrder( - { - contract: 'BTC_USDT', - size, - price, - tif: 'poc', - text, - }, - wsKey, - ); - console.log('Command status:', placedResponse.header.status); - console.log('Placed Futures order:', placedResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API placement failed:', error); - return; - } - - const orderId = String(placedResponse.data.result.id); - let statusResponse; - - try { - statusResponse = await wsApi.getFuturesOrderStatus( - { - order_id: orderId, - }, - wsKey, - ); - console.log('Current Futures order:', statusResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API query failed:', error); - } - - if (statusResponse && statusResponse.data.result.status !== 'open') { - console.log( - 'Order is no longer open:', - statusResponse.data.result.status, - ); - return; - } - - try { - const cancelledResponse = await wsApi.cancelFuturesOrder( - { - order_id: orderId, - }, - wsKey, - ); - console.log('Cancelled Futures order:', cancelledResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API cancellation failed:', error); - } - } finally { - wsApi.getWSClient().closeAll(); - } +⋮---- +export interface StockUserAssets { + equity?: string; + balance?: string; + available?: string; + position_market_value?: string; + position_pnl?: string; + today_pnl?: string; + user_exists?: boolean; + option_position_market_value?: string; + option_position_pnl?: string; + option_today_pnl?: string; } - -main(); -``` - -Successful commands have `header.status === '200'`, and the endpoint result is in `data.result`. The SDK rejects a command promise when Gate returns a non-success status. - -An accepted command is not proof that an order later filled, remained open, or was cancelled. Treat the response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then confirm the final state through the private order stream or a REST API query. - - - -## Work with the Gate REST API - -`RestClient` covers Gate's product groups through named methods. Public methods work without credentials. Private methods use the API key and secret passed to the client. - -### Understand response shapes - -The client resolves to the endpoint's response body: - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient(); - -async function main() { - try { - const result = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - }); - console.log(result); - } catch (error) { - console.error('Order book request failed:', error); - } +⋮---- +export interface StockSymbolDescI18n { + lang?: string; + value?: string; } - -main(); -``` - -There is no shared response envelope. Check the [SDK endpoint map](./endpointFunctionList.md) before deciding how to handle `result`. - -| Method | Response shape | -| ----------------------- | ------------------------------------------ | -| `getServerTime()` | Object with `server_time` | -| `getSpotCurrencyPair()` | Currency-pair object | -| `getSpotTicker()` | Array of ticker objects | -| `getSpotOrderBook()` | Object with tuple-array `bids` and `asks` | -| `getSpotCandles()` | Array of candle tuples | -| `getFuturesContract()` | Contract object | -| `getFuturesTickers()` | Array of ticker objects | -| `getFuturesOrderBook()` | Object with `{ p, s }` bid and ask entries | -| `getFuturesAccount()` | Account object | -| `getFuturesPositions()` | Array of position objects | - -Prices and quantities are commonly returned as strings. Keep them as strings while passing them between Gate API methods. Convert them deliberately when doing calculations, and round the result back to the product's required precision. - -### Read account state - -An authenticated integration usually needs these views: - -| State | Spot method | USDT perpetual method | -| ------------------- | ------------------------- | ---------------------------------------------------------- | -| Balances or account | `getSpotAccounts()` | `getFuturesAccount({ settle: 'usdt' })` | -| Positions | Not applicable | `getFuturesPositions({ settle: 'usdt' })` | -| Open orders | `getSpotOpenOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'open' })` | -| Recent orders | `getSpotOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'finished' })` | -| Trades | `getSpotTradingHistory()` | `getFuturesTradingHistory({ settle: 'usdt' })` | - -These REST API views form a reliable [account state](https://siebly.io/reference/glossary#accountstate) baseline before stream updates are applied. - -### Explore other Gate product groups - -The same `RestClient` also covers the following APIs. Start with read methods and check account eligibility, permissions, and product-specific rules before using any write method. - -| Product group | Representative SDK methods | -| ----------------------- | --------------------------------------------------------------------------- | -| Margin and cross margin | `getMarginAccounts()`, `getCrossMarginAccount()`, `getMarginUserAccounts()` | -| Universal margin loans | `getMarginUNILoans()`, `getMarginUNIMaxBorrow()` | -| Unified Account | `getUnifiedAccountInfo()`, `getUnifiedAccountMode()`, `getUnifiedLoans()` | -| Delivery | `getAllDeliveryContracts()`, `getDeliveryAccount()`, `getDeliveryOrders()` | -| Options | `getOptionsContracts()`, `getOptionsAccount()`, `getOptionsOrders()` | -| Wallet and transfers | `getBalances()`, `submitTransfer()`, `getTransferStatus()` | -| Multi-collateral loans | `getMultiLoanOrders()`, `getMultiLoanSupportedCurrencies()` | -| Flash Swap | `getFlashSwapCurrencyPairs()`, `getFlashSwapOrders()` | -| Earn and lending | `getEarnFixedTermProducts()`, `getEarnFixedTermLends()` | -| Auto Invest | `getAutoInvestCoins()`, `getAutoInvestPlans()`, `getAutoInvestOrders()` | -| Subaccounts | `getSubAccounts()`, `getSubBalance()`, `getSubFuturesBalances()` | -| Rebates and partners | `getPartnerTransactionHistory()`, `getPartnerCommissionHistory()` | -| OTC | `getOTCBankList()`, `getOTCFiatOrderList()` | -| P2P Merchant | `getP2PMerchantUserInfo()`, `getP2PMerchantPendingTransactionList()` | -| CrossEx | `getCrossExSymbols()`, `getCrossExAccounts()`, `getCrossExPositions()` | -| Alpha | `getAlphaCurrencies()`, `getAlphaTickers()`, `getAlphaOrders()` | -| TradFi | `getTradFiSymbols()`, `getTradFiAssets()`, `getTradFiOrders()` | - -See the [complete SDK endpoint map](./endpointFunctionList.md) for every supported method, its authentication requirement, HTTP method, and Gate path. - - - -## Build with WebSocket streams - -Use `WebsocketClient` for ongoing market and account updates. A subscription request has two independent parts: - -- `topic` and `payload` select the Gate channel and its data. -- `wsKey` selects the product connection that carries the subscription. - -One `subscribe()` call can contain several topics when they share the same `wsKey`. Use separate calls for topics on different product connections. - -### Choose the correct WebSocket key - -| Product connection | SDK key | -| ---------------------- | ---------------------------------- | -| Spot | `WS_KEY_MAP.spotV4` | -| USDT perpetual Futures | `WS_KEY_MAP.perpFuturesUSDTV4` | -| BTC perpetual Futures | `WS_KEY_MAP.perpFuturesBTCV4` | -| USDT Delivery | `WS_KEY_MAP.deliveryFuturesUSDTV4` | -| BTC Delivery | `WS_KEY_MAP.deliveryFuturesBTCV4` | -| Options | `WS_KEY_MAP.optionsV4` | -| Announcements | `WS_KEY_MAP.announcementsV4` | - -Do not infer the connection from a symbol alone. `BTC_USDT` can appear in more than one product family. - -Useful public topics include: - -| Product | Starting topics | -| ------- | -------------------------------------------------------------------------------------------------------------- | -| Spot | `spot.tickers`, `spot.trades`, `spot.order_book`, `spot.order_book_update`, `spot.candlesticks` | -| Futures | `futures.tickers`, `futures.trades`, `futures.order_book`, `futures.order_book_update`, `futures.candlesticks` | -| Options | `options.tickers`, `options.trades`, `options.order_book`, `options.ul_tickers` | - -### Treat responses and updates differently - -The `response` event tells you whether Gate accepted a subscribe, unsubscribe, or request message. Check its `error` and `result`. - -The `update` event carries channel data. Inspect `channel`, `event`, `result`, and the SDK-added `wsKey` before updating local state. A subscription response and a data update can have different result shapes. - -### Recover after a reconnect - -The SDK reconnects and restores cached subscriptions. A stream gap can still hide balance, order, trade, or position changes. Reload the affected state from the REST API after `reconnected`. - -This Spot example reloads balances, open orders, and recent trades in sequence: - -```javascript -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -let recoveryRunning = false; -let spotState; - -async function recoverSpotState() { - if (recoveryRunning) { - return; - } - - recoveryRunning = true; - - try { - let balances; - - try { - balances = await rest.getSpotAccounts(); - } catch (error) { - console.error('Balance recovery failed:', error); - return; - } - - let openOrders; - - try { - openOrders = await rest.getSpotOpenOrders({ - account: 'spot', - }); - } catch (error) { - console.error('Open-order recovery failed:', error); - return; - } - - let trades; - - try { - trades = await rest.getSpotTradingHistory({ - currency_pair: 'BTC_USDT', - account: 'spot', - limit: 100, - }); - } catch (error) { - console.error('Trade recovery failed:', error); - return; - } - - spotState = { - balances, - openOrders, - trades, - recoveredAt: Date.now(), - }; - - console.log('Recovered Spot state:', spotState); - } finally { - recoveryRunning = false; - } +⋮---- +export interface StockSymbolItem { + symbol?: string; + exchange?: string; + exchange_desc?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + symbol_desc?: string; + category?: StockCategory | string; + asset_type?: StockAssetType; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; + order_fill_timing?: number; + icon_link?: string; + quote_currency_symbol?: string; + price_precision?: number; + volume_precision?: number; + is_ipo?: boolean; + ipo_price?: string; + sell_price_protection?: string; + buy_price_protection?: string; + symbol_descs?: StockSymbolDescI18n[]; + timestamp?: number; } - -ws.on('reconnected', async ({ wsKey }) => { - if (wsKey !== WS_KEY_MAP.spotV4) { - return; - } - - await recoverSpotState(); -}); - -ws.on('update', (update) => { - console.log('Private Spot update:', update); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Balance subscription failed:', error); +⋮---- +export interface StockSymbolDetailItem { + symbol?: string; + exchange?: string; + exchange_desc?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + symbol_desc?: string; + category?: StockCategory | string; + asset_type?: StockAssetType; + settlement_currency?: string; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + volume_precision?: number; + is_ipo?: boolean; + ipo_price?: string; + price_protection?: string; + sell_price_protection?: string; + buy_price_protection?: string; + slippage_rate?: string; + commission_rate?: string; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; + order_fill_timing?: number; + symbol_descs?: StockSymbolDescI18n[]; + [key: string]: unknown; } - -try { - ws.subscribe( - { - topic: 'spot.orders', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Order subscription failed:', error); +⋮---- +export interface StockOrderBookLevel { + p?: string; + user_order?: boolean; + [key: string]: unknown; } - -try { - ws.subscribe( - { - topic: 'spot.usertrades', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Trade subscription failed:', error); +⋮---- +export interface StockOrderBook { + symbol?: string; + bids?: StockOrderBookLevel[]; + asks?: StockOrderBookLevel[]; + timestamp?: number; } - -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration) applied as [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery). The example replaces `spotState` only after all three reads succeed. Reload only the state that may have changed on the affected connection, then reconcile it before trusting new updates. - -For a wider recovery design, see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows). - - - -## Use the Gate WebSocket API - -`WebsocketAPIClient` is for request and response commands over WebSocket. It is not the same as a subscription stream. - -The client: - -1. Opens the selected WebSocket connection. -2. Authenticates automatically. -3. Adds a unique request ID. -4. Sends the command. -5. Matches Gate's response to the pending promise. -6. Resolves with `header`, `data.result`, `request_id`, and `wsKey`. - -Authentication happens automatically on the first command. `connectWSAPI(wsKey)` is available when an application wants to open and authenticate the connection early. Automatic WebSocket API reauthentication after a reconnect is enabled by default. - -Spot methods include: - -- `submitNewSpotOrder()` -- `getSpotOrderStatus()` -- `getSpotOrders()` -- `updateSpotOrder()` -- `cancelSpotOrder()` -- `cancelSpotOrderById()` -- `cancelSpotOrderForSymbol()` - -Futures methods include: - -- `submitNewFuturesOrder()` -- `submitNewFuturesBatchOrder()` -- `getFuturesOrderStatus()` -- `getFuturesOrders()` -- `updateFuturesOrder()` -- `cancelFuturesOrder()` - -Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: - -```javascript -import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; - -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -async function main() { - try { - const response = await wsApi.getFuturesOrders( - { - contract: 'BTC_USDT', - status: 'open', - limit: 20, - }, - WS_KEY_MAP.perpFuturesUSDTV4, - ); - - console.log(response.header.status); - console.log(response.data.result); - } catch (error) { - console.error('WebSocket API order request failed:', error); - } finally { - wsApi.getWSClient().closeAll(); - } +⋮---- +export interface StockOrderItem { + order_id?: string; + symbol?: string; + exchange?: string; + quote_currency?: string; + fx_rate?: string; + symbol_desc?: string; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; + price_type?: string; + side?: number; + status?: StockOrderStatus; + volume?: string; + fill_volume?: string; + price?: string; + time_setup?: number; + time_update?: number; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + price_protection?: string; + sell_price_protection?: string; + buy_price_protection?: string; + commission_rate?: string; + slippage_rate?: string; + [key: string]: unknown; +} +⋮---- +export interface StockCreateOrderResult { + id?: string; +} +⋮---- +export interface StockOrderHistoryItem { + order_id?: string; + symbol?: string; + exchange?: string; + quote_currency?: string; + fx_rate?: string; + symbol_desc?: string; + price_type?: string; + status?: StockOrderStatus; + status_desc?: string; + status_detail?: { title?: string; message?: string } | null; + finish_as?: StockOrderFinishAs; + side?: number; + time_in_force?: string; + volume?: string; + fill_volume?: string; + price?: string; + avg_fill_price?: string | null; + commission?: string; + time_setup?: number; + time_done?: number; + [key: string]: unknown; +} +⋮---- +export interface StockUpdateOrderResult { + order_id?: number; +} +⋮---- +export interface StockPositionItem { + symbol?: string; + exchange?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + trade_status?: StockTradeStatus; + symbol_desc?: string; + position_pnl?: string; + today_pnl?: string; + pnl_rate?: string; + today_sell_amount?: string; + today_buy_amount?: string; + today_sell_volume?: string; + today_buy_volume?: string; + yesterday_volume?: string; + volume?: string; + available?: string; + transfer_out_pending_qty?: string; + avg_cost_price?: string; + diluted_cost_price?: string; + last_price?: string; + extended_last_price?: string | null; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + price_protection?: string; + [key: string]: unknown; +} +⋮---- +export interface StockClosePositionResult { + order_id?: number; +} +⋮---- +export interface StockTransactionItem { + asset?: string; + symbol?: string; + symbol_display?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + ref_id?: string; + time?: number; + unit_text?: string; + detail?: object; +} +⋮---- +export interface StockExchangeItem { + exchange?: string; + exchange_desc?: string; + icon_link?: string; + support_transfer?: boolean; +} +⋮---- +export interface StockFeeRateItem { + vip_level?: number; + maker_fee?: string; + taker_fee?: string; } -main(); -``` - -The response confirms the command outcome. Use private order streams or a REST API query to confirm the resulting exchange state. - - - -## Use Gate TestNet - -Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. - -| Interface | Current TestNet host | -| ------------------------ | ---------------------------------------------- | -| REST API | `https://api-testnet.gateapi.io/api/v4` | -| Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | -| USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | - -Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: - -- Spot WebSocket TestNet is not wired through `useTestnet: true` in this SDK. The Spot testnet map entry is a stub (`NoTestnetForSpotWebsockets!`), so set `wsUrl` to the Spot TestNet host above. -- For Futures-only REST TestNet, the SDK also accepts `baseUrlKey: 'futuresTestnet'`, which resolves to `https://fx-api-testnet.gateio.ws/api/v4`. The Global TestNet REST host in the table is the host used by the Spot and Futures order examples in this guide. - -```javascript -import { RestClient, WebsocketClient } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -const spotWs = new WebsocketClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', -}); -``` - -Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. - -Fund the required Spot or Futures TestNet account with test assets before running an order example. - - - -## Connect to Global and regional REST API hosts - -Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. - -| Environment or account | REST API base URL | Official reference | -| ------------------------ | --------------------------------------- | -------------------------------------------------------------------- | -| Global live | `https://api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Global TestNet | `https://api-testnet.gateapi.io/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Futures live alternative | `https://fx-api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Gate US live | `https://api.gate.us/api/v4` | [Gate US API v4](https://us.gate.com/en-us/docs/developers/apiv4/) | -| Gate EU live | `https://api.gateeu.com/api/v4` | [Gate EU API v4](https://eu.gate.com/docs/developers/apiv4/en/) | - -Global live is the SDK default. Set `baseUrl` for another supported account host: - -```javascript -import { RestClient } from 'gateio-api'; - -const gateUs = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gate.us/api/v4', -}); - -const gateEu = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gateeu.com/api/v4', -}); -``` - -Use only the client that matches the account. Regional APIs can expose different products and endpoint sets. Check the regional documentation before calling a method, and use the region's own credentials. - -This guide does not assign regional WebSocket URLs. Use a regional WebSocket host only when the official documentation for that account region provides it. - - - -## Use a proxy with the REST API and WebSockets - -`gateio-api` accepts standard Node.js agents. Configure the agent in both places when all Gate traffic must use the proxy: - -- Pass `httpsAgent` in the second `RestClient` argument and set `proxy: false`. -- Pass the same agent as `wsOptions.agent` to `WebsocketClient` or `WebsocketAPIClient`. - -See [Using proxies with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. - -### HTTP and HTTPS proxy - -Install the proxy agent: - -```bash -npm install https-proxy-agent -``` - -Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. - -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -async function main() { - const proxyUrl = process.env.GATE_PROXY_URL; - - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } - - const agent = new HttpsProxyAgent(proxyUrl); - - const rest = new RestClient( - {}, - { - httpsAgent: agent, - proxy: false, - }, - ); - - const ws = new WebsocketClient({ - wsOptions: { - agent, - }, - }); - - ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through proxy:', wsKey); - }); - - ws.on('response', (response) => { - console.log('Subscription response:', response); - }); - - ws.on('update', (update) => { - console.log('Ticker update through proxy:', update); - ws.closeAll(); - }); - - ws.on('exception', () => { - console.error('WebSocket proxy connection failed.'); - }); - - try { - const time = await rest.getServerTime(); - console.log('Server time through proxy:', time.server_time); - } catch { - console.error('REST API proxy request failed.'); - } - - try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('WebSocket proxy subscription failed.'); - } - - process.once('SIGINT', () => { - ws.closeAll(); - }); +================ +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; } - -main(); -``` - -For an authenticated HTTP or HTTPS proxy, include the username and password in `GATE_PROXY_URL`. Percent-encode reserved characters in each credential component. - -### SOCKS5 proxy - -Install the SOCKS agent: - -```bash -npm install socks-proxy-agent -``` - -Set `GATE_SOCKS_PROXY_URL` to a `socks5://` URL: - -```javascript -import { SocksProxyAgent } from 'socks-proxy-agent'; -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -async function main() { - const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; - - if (!proxyUrl) { - console.error('Set GATE_SOCKS_PROXY_URL.'); - return; - } - - const agent = new SocksProxyAgent(proxyUrl); - - const rest = new RestClient( - {}, - { - httpsAgent: agent, - proxy: false, - }, - ); - - const ws = new WebsocketClient({ - wsOptions: { - agent, - }, - }); - - ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through SOCKS5:', wsKey); - }); - - ws.on('response', (response) => { - console.log('Subscription response:', response); - }); - - ws.on('update', (update) => { - console.log('Ticker update through SOCKS5:', update); - ws.closeAll(); - }); - - ws.on('exception', () => { - console.error('SOCKS5 WebSocket connection failed.'); - }); - - try { - const time = await rest.getServerTime(); - console.log('Server time through SOCKS5:', time.server_time); - } catch { - console.error('SOCKS5 REST API request failed.'); - } - - try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('SOCKS5 WebSocket subscription failed.'); - } - - process.once('SIGINT', () => { - ws.closeAll(); - }); +⋮---- +/** GET /wallet/sub_account_balances item */ +export interface SubAccountBalance { + uid: string; + available: { [key: string]: string }; + /** Locked amount per currency */ + locking?: { [key: string]: string }; } - -main(); -``` - -### Private REST API, stream, and WebSocket API traffic - -Use the same agent and credentials for private REST API calls, private subscriptions, and WebSocket API connections: - -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { - RestClient, - WebsocketAPIClient, - WebsocketClient, - WS_KEY_MAP, -} from 'gateio-api'; - -async function main() { - const proxyUrl = process.env.GATE_PROXY_URL; - - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } - - const agent = new HttpsProxyAgent(proxyUrl); - - const rest = new RestClient( - { - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - }, - { - httpsAgent: agent, - proxy: false, - }, - ); - - const streams = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); - - const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); - - streams.on('authenticated', ({ wsKey }) => { - console.log('Private stream authenticated:', wsKey); - }); - - streams.on('update', (update) => { - console.log('Private update through proxy:', update); - }); - - streams.on('exception', () => { - console.error('Private stream proxy connection failed.'); - }); - - try { - const balances = await rest.getSpotAccounts(); - console.log('Spot balances through proxy:', balances); - } catch { - console.error('Private REST API proxy request failed.'); - } - - try { - streams.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('Private stream subscription failed.'); - } - - try { - await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); - console.log('WebSocket API authenticated through proxy.'); - } catch { - console.error('WebSocket API proxy connection failed.'); - } - - process.once('SIGINT', () => { - streams.closeAll(); - wsApi.getWSClient().closeAll(); - }); -} - -main(); -``` - -To combine a proxy with TestNet or a regional API, keep `baseUrl` or `wsUrl` in the first client argument and the agent in the same positions shown above. - -The proxy's egress IP is the address Gate sees. Add that address to the API key whitelist when whitelisting is enabled. Use a stable proxy endpoint, monitor its latency, and never use a proxy to bypass account or regional restrictions. - -A proxy changes the network path, not request signing, account eligibility, or regional product access. Test public REST API and WebSocket traffic first. Treat HTTP 407 responses, TLS failures, and repeated reconnects as network faults. The SDK does not rotate proxy endpoints. - - - -## Production checklist - -### Keep request time accurate - -Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. - -Synchronize the host clock with NTP. Use `getServerTime()` for diagnosis, but fix the system clock rather than adding a permanent application offset for a drifting machine. - -### Respect rate limits - -Rate limits vary by product and endpoint. Read the current [Gate API rate-limit documentation](https://www.gate.com/docs/developers/apiv4/en/#frequency-limit-rule) and monitor rejection labels. - -Retry temporary network failures and rate-limit responses with bounded exponential backoff and jitter. Do not blindly retry an order command after an ambiguous timeout. First reconcile by the order's `text` value or query current order state. - -### Use custom order IDs - -Set a unique `text` value beginning with `t-` on each application-owned order. Store it with your local request record. This gives retries, restarts, stream updates, and REST API recovery a common identifier. - -### Apply product metadata - -Before placing an order: - -- Check that the pair or contract is tradable. -- Apply minimum and maximum amounts. -- Round prices and quantities to the permitted increments. -- Treat Futures `size` as a contract count. -- Read `quanto_multiplier` before translating contract size into underlying exposure. -- Keep one-way, dual-side, and split position modes explicit. - -Refresh metadata regularly and when Gate rejects an order for a precision or size rule. - -### Confirm final state - -A REST API response or WebSocket API response can arrive before later fills, cancellations, or amendments. Record the command response, then confirm final state through private streams or a REST API query. - -After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. - -### Scope credentials and network access - -- Use separate keys for live and TestNet. -- Grant only the product permissions the process needs. -- Use read-only keys for monitoring services. -- Do not grant withdrawal permission. -- Add IP whitelists when egress addresses are stable. -- Keep secrets in a server-side secret manager or deployment environment. -- Monitor proxy availability and egress IP changes. - -### Shut down connections - -Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. - -## FAQ - -### Does `gateio-api` work with plain JavaScript? - -Yes. Every example in this guide is plain JavaScript. The examples use ESM imports, so save them as `.mjs` files or set `"type": "module"` in `package.json`. The package also includes a CommonJS build and TypeScript declarations. - -### Which client should I use? - -Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. - -### Do public Gate API calls need credentials? - -No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. - -### Why did a REST API call return an object when another returned an array? - -Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. - -### Why does `getSpotTicker()` return an array for one pair? - -That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. - -### How are Spot candles structured? - -Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. - -### Why does Gate use `BTC_USDT`? - -Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. - -### What do `account` and `settle` change? - -`account` selects the account used by a Spot order or query. `settle` selects the settlement currency and REST API path for Futures or Delivery requests. - -### What is the `text` order field? - -`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. - -### Why am I not receiving WebSocket updates? - -Check the topic payload, `wsKey`, API host, credentials, and permissions. Then inspect `response`, `authenticated`, and `exception` events. A successful subscription response confirms registration, but an update only arrives when the subscribed data changes. - -### Which `WS_KEY_MAP` value should I use? - -Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. - -### Why do private Futures topics use my Gate user ID? - -It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. - -### What is the difference between a stream and the WebSocket API? - -Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. - -### Does a successful WebSocket API response mean the order filled? - -No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. - -### Why was a post-only order rejected or immediately finished? - -The best bid or ask can move between the order-book request and order placement. Gate will not let a post-only order take liquidity. Read the returned status and `finish_as`, then decide whether to refresh the book and submit a new order with a new `text`. - -### Why does a Futures order size look too small? - -Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. - -### Can live credentials be used in TestNet? - -No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. - -### Can I use Gate US or Gate EU with the SDK? - -Yes, for endpoints available to that account region. Set the documented regional `baseUrl`, use credentials from the same region, and check its official API documentation for product coverage. - -### Can REST API and WebSocket traffic use the same proxy? - -Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. - -### Does a proxy change signing or account eligibility? - -No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. - -### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? - -Common causes are a drifting system clock, the wrong API secret, credentials from another environment, or an API request reaching the wrong host. Verify the clock, credential source, and API host without logging the secret. - -## Next steps - -- Browse the [Gate SDK examples](https://siebly.io/examples/Gate). -- Find methods in the [complete endpoint map](./endpointFunctionList.md). -- Review the [Gate SDK page](https://siebly.io/sdk/gate/javascript). -- Install or update [`gateio-api` from npm](https://www.npmjs.com/package/gateio-api). -- Browse the [`gateio-api` source repository](https://github.com/sieblyio/gateio-api). -- Read the official [Gate REST API documentation](https://www.gate.com/docs/developers/apiv4/en/). -- Read the official [Gate Spot WebSocket documentation](https://www.gate.com/docs/developers/apiv4/ws/). -- Read the official [Gate Futures WebSocket documentation](https://www.gate.com/docs/developers/futures/ws/). -- Review [Exchange State](https://siebly.io/reference/exchange-state) before building private state management. -- Use [Runtime Workflows](https://siebly.io/reference/runtime-workflows) when designing startup, reconnect, and reconciliation behavior. -- Open the [Siebly glossary](https://siebly.io/reference/glossary) for order, stream, and recovery terms. -- Report SDK issues in the [`gateio-api` GitHub repository](https://github.com/sieblyio/gateio-api/issues). - -================ -File: src/types/request/earn.ts -================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ ⋮---- -/** GET /earn/dual/investment_plan */ -export interface GetDualInvestmentPlansReq { - plan_id?: number | string; - coin?: string; - type?: string; - quote_currency?: string; - /** `apy` | `short-period` | `multiple` */ - sort?: string; - page?: number; - page_size?: number; -} +/** Locked amount per currency */ ⋮---- -/** `apy` | `short-period` | `multiple` */ -⋮---- -/** GET /earn/dual/orders */ -export interface GetDualInvestmentOrdersReq { - from?: number; - to?: number; - type?: string; - status?: string; - coin?: string; - page?: number; - limit?: number; -} -⋮---- -/** GET /earn/dual/order-refund-preview */ -export interface GetDualOrderRefundPreviewReq { - order_id: string; -} -⋮---- -/** POST /earn/dual/order-refund */ -export interface SubmitDualOrderRefundParams { - order_id: string; - /** From order-refund-preview */ - req_id: string; -} -⋮---- -/** From order-refund-preview */ -⋮---- -/** POST /earn/dual/modify-order-reinvest */ -export interface UpdateDualOrderReinvestParams { - order_id?: number; - /** 0 off, 1 on */ - status?: number; - /** Effective duration in seconds; default 86400 */ - effective_time_duration?: number; +export interface DepositRecord { + id: string; + txid: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'BLOCKED' // Deposit Blocked + | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock + | 'DONE' // Funds Credited to Spot Account + | 'INVALID' // Invalid Transaction + | 'MANUAL' // Manual Review Required + | 'PEND' // Processing + | 'REVIEW' // Under Compliance Review + | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit + chain: string; + refund_status?: // v4.106.95: Blocked deposit refund status + 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; } ⋮---- -/** 0 off, 1 on */ +| '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 ⋮---- -/** Effective duration in seconds; default 86400 */ +refund_status?: // v4.106.95: Blocked deposit refund status ⋮---- -/** GET /earn/dual/project-recommend */ -export interface GetDualProjectRecommendReq { - mode?: string; - coin?: string; - type?: string; - /** Comma-separated project IDs to exclude */ - history_pids?: string; +export interface CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; } ⋮---- -/** Comma-separated project IDs to exclude */ -⋮---- -/** Request params for POST /earn/dual/orders */ -export interface PlaceDualInvestmentOrderParams { - plan_id: string; - /** Subscription amount. Mutually exclusive with copies. */ +export interface SubAccountTransferRecord { + currency: string; + sub_account: string; + direction: 'to' | 'from'; amount: string; - /** Units. Mutually exclusive with amount. */ - copies?: string; - /** Custom order info, must start with t- */ - text?: string; + uid: string; + client_order_id: string; + timest: string; + source: string; + sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- -/** Subscription amount. Mutually exclusive with copies. */ -⋮---- -/** Units. Mutually exclusive with amount. */ -⋮---- -/** Custom order info, must start with t- */ -⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ -⋮---- -export interface GetEarnFixedTermProductsReq { - asset?: string; - type?: number; // 1 regular, 2 VIP - page: number; - limit: number; +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 }; } ⋮---- -type?: number; // 1 regular, 2 VIP -⋮---- -export interface GetEarnFixedTermProductsByAssetReq { - /** Product type: "" or 1 regular, 2 VIP, 0 all */ - type?: 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; + }; } ⋮---- -/** Product type: "" or 1 regular, 2 VIP, 0 all */ -⋮---- -export interface CreateEarnFixedTermLendReq { - product_id: number; - amount: string; - year_rate?: string; - reinvest_status?: number; // 0 off, 1 on - redeem_account_type?: number; // 1 spot - financial_rate_id?: number; // interest boost coupon id, 0 = none - sub_business?: number; +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; + }; + }; + }; } ⋮---- -reinvest_status?: number; // 0 off, 1 on -redeem_account_type?: number; // 1 spot -financial_rate_id?: number; // interest boost coupon id, 0 = none -⋮---- -export interface GetEarnFixedTermLendsReq { - product_id?: number; - order_id?: number; - asset?: string; - order_type: '1' | '2'; // 1 current, 2 historical - page: number; - limit: number; - sub_business?: number; - business_filter?: string; +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; + }; } ⋮---- -order_type: '1' | '2'; // 1 current, 2 historical -⋮---- -export interface EarnFixedTermPreRedeemReq { - order_id: string; +export interface SavedAddress { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; } ⋮---- -export interface GetEarnFixedTermHistoryReq { - product_id?: number; - order_id?: string; - asset?: string; - type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus - page: number; - limit: number; - start_at?: number; - end_at?: number; - sub_business?: number; - business_filter?: string; -} -⋮---- -type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus - -================ -File: src/types/request/otc.ts -================ -import { GateMultipartFile } from '../../lib/multipartUtil.js'; -⋮---- -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ -⋮---- -export interface CreateOTCQuoteReq { - side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount - pay_coin: string; // Currency the user pays - get_coin: string; // Currency the user receives - pay_amount?: string; // User payment currency amount (required if side is PAY) - get_amount?: string; // Amount of currency received by user (required if side is GET) - create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement - promotion_code?: string; // Promotion code (optional) +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; } ⋮---- -side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount -pay_coin: string; // Currency the user pays -get_coin: string; // Currency the user receives -pay_amount?: string; // User payment currency amount (required if side is PAY) -get_amount?: string; // Amount of currency received by user (required if side is GET) -create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement -promotion_code?: string; // Promotion code (optional) -⋮---- -export interface CreateOTCFiatOrderReq { - type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) - side: string; // Quote direction returned by the quote API (used for order validation) - crypto_currency: string; // Cryptocurrency - fiat_currency: string; // Fiat currency - crypto_amount: string; // Amount of cryptocurrency - fiat_amount: string; // Fiat amount - promotion_code?: string; // Promotion code - quote_token: string; // Parameter returned by the quote API - /** From GET /otc/bank/list; default card has is_default=1 */ - bank_id: string; - receive_type?: string; +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; + }; + }; } ⋮---- -type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) -side: string; // Quote direction returned by the quote API (used for order validation) -crypto_currency: string; // Cryptocurrency -fiat_currency: string; // Fiat currency -crypto_amount: string; // Amount of cryptocurrency -fiat_amount: string; // Fiat amount -promotion_code?: string; // Promotion code -quote_token: string; // Parameter returned by the quote API -/** From GET /otc/bank/list; default card has is_default=1 */ -⋮---- -export interface CreateOTCStablecoinOrderReq { - pay_coin: string; // Currency paid by the user - get_coin: string; // Currency to be received by the user - pay_amount: string; // User payment currency amount - get_amount: string; // Amount of currency received by the user - side: string; // Quote direction returned by the quote API (used for order validation) - quote_token: string; // Parameter returned by the quote API - promotion_code?: string; // Promotion code (optional) +export interface SmallBalanceRecord { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } ⋮---- -pay_coin: string; // Currency paid by the user -get_coin: string; // Currency to be received by the user -pay_amount: string; // User payment currency amount -get_amount: string; // Amount of currency received by the user -side: string; // Quote direction returned by the quote API (used for order validation) -quote_token: string; // Parameter returned by the quote API -promotion_code?: string; // Promotion code (optional) -⋮---- -export interface MarkOTCOrderAsPaidReq { - order_id: string; // Order ID - client_order_id?: string; // Client order ID (gateway/Inner Pay paths) - payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB - payment_receipt?: string; // Alias compatible with payment_receipt_file_key +export interface SmallBalanceHistoryRecord { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; } ⋮---- -order_id: string; // Order ID -client_order_id?: string; // Client order ID (gateway/Inner Pay paths) -payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB -payment_receipt?: string; // Alias compatible with payment_receipt_file_key -⋮---- -export interface CancelOTCOrderReq { - order_id: string; // Order ID +export interface PushOrder { + id: string; + push_uid: number; + receive_uid: number; + currency: string; + amount: string; + create_time: number; + status: + | 'CREATING' + | 'PENDING' + | 'CANCELLING' + | 'CANCELLED' + | 'REFUSING' + | 'REFUSED' + | 'RECEIVING' + | 'RECEIVED'; + message: string; } ⋮---- -order_id: string; // Order ID -⋮---- -export interface GetOTCFiatOrderListReq { - type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) - fiat_currency?: string; // Fiat currency - crypto_currency?: string; // Digital currency - start_time?: string; // Start Time - end_time?: string; // End time - status?: string; // DONE: Completed - pn?: string; // Page number - ps?: string; // Number of items per page +/** GET /wallet/transfers — AccountTransferDetail */ +export interface AccountTransferDetail { + tx_id: string; + status: 'pending' | 'success' | 'fail'; + currency: string; + amount: string; + from_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + to_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + settle?: string | null; + currency_pair?: string | null; } + +================ +File: src/types/shared.ts +================ +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'testnet' + | 'futuresTestnet'; ⋮---- -type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) -fiat_currency?: string; // Fiat currency -crypto_currency?: string; // Digital currency -start_time?: string; // Start Time -end_time?: string; // End time -status?: string; // DONE: Completed -pn?: string; // Page number -ps?: string; // Number of items per page +// interfaces ⋮---- -export interface GetOTCStablecoinOrderListReq { - page_size?: string; // Number of records per page - page_number?: string; // Page number - coin_name?: string; // Order currency - start_time?: string; // Start Time - end_time?: string; // End time - status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed +export interface FromToPageLimit { + from: number; + to: number; + page: number; + limit: number; } ⋮---- -page_size?: string; // Number of records per page -page_number?: string; // Page number -coin_name?: string; // Order currency -start_time?: string; // Start Time -end_time?: string; // End time -status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed -⋮---- -export interface GetOTCFiatOrderDetailReq { - order_id: string; // Order ID +// Used for spot and flash swap +export interface CurrencyPair { + id?: string; + base?: string; + base_name?: string; + quote?: string; + quote_name?: string; + trade_quotes?: string[] | null; + fee?: string; + min_base_amount?: string; + min_quote_amount?: string; + max_base_amount?: string; + max_quote_amount?: string; + amount_precision?: number; + precision?: number; + trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; + sell_start?: number; + buy_start?: number; + type: string; + delisting_time?: number; + trade_url?: string; + up_rate?: string; // v4.106.4: Maximum price increase percentage + down_rate?: string; // v4.106.4: Maximum price decrease percentage + market_order_max_stock?: string | null; + market_order_max_money?: string | null; } ⋮---- -order_id: string; // Order ID +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage + +================ +File: webpack/webpack.config.cjs +================ +function generateConfig(name) ⋮---- -export interface OTCBankIdReq { - bank_id: string; -} +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -export interface GetOTCBankSupplementChecklistReq { - bank_id: string; -} +// Node.js core modules not available in browsers +// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers ⋮---- -export interface CreateOTCBankReq { - bank_account_name: string; - bank_name: string; - bank_country: string; - bank_address: string; - iban: string; - swift: string; - remittance_line_number?: string; - agent_bank_name?: string; - agent_bank_swift?: string; - documentation_file?: GateMultipartFile; - documentation_file_key?: string; - file_type?: string; -} +// Code is already transpiled from TypeScript, no additional loaders needed + +================ +File: src/lib/BaseRestClient.ts +================ +import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; +// NOTE: https.Agent is Node.js-only and not available in browser environments +// Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings +import https from 'https'; ⋮---- -export interface SubmitOTCBankPersonalSupplementReq { - bank_id: string; - id_document_front: GateMultipartFile; - id_document_back: GateMultipartFile; - address_proof: GateMultipartFile; -} +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -export interface SubmitOTCBankEnterpriseSupplementReq { - bank_id: string; - certificate: GateMultipartFile; - share_holders: GateMultipartFile; - passport: GateMultipartFile; - share_holding_structure: GateMultipartFile; - uid?: string; - funds_statement?: GateMultipartFile; - additional?: GateMultipartFile; +/** + * 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; } ⋮---- -export interface CreateOTCUploadPreUploadReq { - content_type: string; - scene: 'general' | 'bank' | 'assessment' | 'credit'; +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; } - -================ -File: src/types/request/spot.ts -================ -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== +⋮---- +type SignMethod = 'gateV4'; +⋮---- +/** + * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. + * This type anticipates these are possible in any combination. + * + * The request builder will automatically handle where parameters should go. */ +type ParamsInQueryBodyOrHeader = { + query?: object; + body?: object; + headers?: object; + /** multipart/form-data body; mutually exclusive with `body` */ + multipart?: FormData; +}; ⋮---- -/** Limit-order take-profit / stop-loss on create */ -export interface SpotOrderTPSL { - trigger_price: string; - order_price: string; -} +/** multipart/form-data body; mutually exclusive with `body` */ ⋮---- -/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ -export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ ⋮---- -export interface GetSpotOrderBookReq { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; -} +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, ⋮---- -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; -} +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void ⋮---- -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 abstract class BaseRestClient ⋮---- -export interface GetSpotAccountBookReq { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - /** - * BizType / business type filter. Sub-account transfer internal BizType values include - * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. - */ - type?: string; - code?: string; -} +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- /** - * BizType / business type filter. Sub-account transfer internal BizType values include - * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + * Create an instance of the REST client. Pass API credentials in the object in the first parameter. + * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity + * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios */ +constructor( + restClientOptions: RestClientOptions = {}, + networkOptions: AxiosRequestConfig = {}, +) ⋮---- -export interface SubmitSpotClosePosCrossDisabledReq { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} +/** Throw errors if any request params are empty */ ⋮---- -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'; -} +/** in ms == 5 minutes by default */ ⋮---- -export interface CancelSpotBatchOrdersReq { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - xGateExptime?: number; -} +// If enabled, configure a https agent with keepAlive enabled +// NOTE: This is Node.js-only functionality. In browser environments, this code is skipped +// as the 'https' module is excluded via webpack fallback configuration. +// Browser connection pooling is handled automatically by the browser itself. ⋮---- -export interface GetSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; -} +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -export interface GetSpotTradingHistoryReq { - currency_pair?: string; - limit?: number; - page?: number; - order_id?: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; -} +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties ⋮---- -export interface UpdateSpotBatchOrdersReq { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -export interface GetSpotInsuranceHistoryReq { - business: 'margin' | 'unified'; - currency: string; - from: number; - to: number; - page?: number; - limit?: number; -} +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -export interface GetSpotAutoOrdersReq { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; - limit?: number; - offset?: number; -} +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -export interface SubmitSpotOrderReq { - xGateExptime?: number; - side: 'buy' | 'sell'; - amount: string; - text?: string; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - stp_act?: string; - action_mode?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; - post_only?: boolean; - trade_quote?: string; -} +protected get(endpoint: string, params?: object) ⋮---- -export interface UpdateSpotOrderReq { - xGateExptime?: number; - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - amount?: string; - price?: string; - amend_text?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} +// GET only supports params in the query string ⋮---- -/** GET /spot/pov_orders */ -export interface GetSpotPovOrdersReq { - status: 'open' | 'finished'; - currency_pair?: string; - side?: 'buy' | 'sell'; - page?: number; - limit?: number; -} +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -/** POST /spot/pov_orders */ -export interface CreateSpotPovOrderReq { - currency_pair: string; - side: 'buy' | 'sell'; - amount: string; - participation_rate: 5 | 10 | 20 | 40; - ttl: '1h' | '6h' | '12h' | '1d' | '2d' | '3d' | '4d' | '5d' | '6d' | '7d'; - limit_price?: string; - trigger_price?: string; - text?: string; -} +protected getPrivate(endpoint: string, params?: object) ⋮---- -/** DELETE /spot/pov_orders */ -export interface CancelSpotPovOrdersReq { - currency_pair?: string; -} - -================ -File: src/types/request/tradfi.ts -================ -/** TradFi API request types */ +// GET only supports params in the query string ⋮---- -export interface TradFiGetSymbolDetailParams { - symbols: string; -} +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface TradFiGetKlinesParams { - kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; - begin_time?: number; - end_time?: number; - limit?: number; -} +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, +) ⋮---- -export interface TradFiCreateTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; -} +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -export interface TradFiGetTransactionsParams { - begin_time?: number; - end_time?: number; - type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; - page?: number; - page_size?: number; -} +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface TradFiCreateOrderReq { - price: string; - price_type: 'trigger' | 'market'; - side: 1 | 2; - symbol: string; - volume: string; - price_tp?: string; - price_sl?: string; - leverage?: number; -} +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface TradFiModifyOrderReq { - price: string; - price_tp?: string | null; - price_sl?: string | null; -} +/** + * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. + */ +private async _call( + method: Method, + endpoint: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, +): Promise ⋮---- -export interface TradFiModifyPositionReq { - price_tp?: string | null; - price_sl?: string | null; -} +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -export interface TradFiClosePositionReq { - close_type: 1 | 2; - close_volume?: string | null; -} +// Build a request and handle signature process ⋮---- -export interface TradFiGetOrderHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - side?: 1 | 2; -} +// Dispatch request ⋮---- -export interface TradFiGetPositionHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - position_dir?: 'Long' | 'Short'; - page?: number; - page_size?: number; -} +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -/** GET /tradfi/symbols/commissions */ -export interface TradFiGetSymbolCommissionsParams { - symbols?: string; - category_code?: string; -} - -================ -File: src/types/request/unified.ts -================ -export interface SubmitUnifiedBorrowOrRepayReq { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; -} +// Throw API rejections by parsing the response code from the body ⋮---- -export interface GetUnifiedLoansReq { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; -} +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- -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'; -} +// Something happened in setting up the request that triggered an error ⋮---- -export interface SetUnifiedAccountModeReq { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - use_funding?: boolean; - options?: boolean; - }; -} +// request made but no response received ⋮---- -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; -} +// The request was made and the server responded with a status code +// that falls out of the range of 2xx ⋮---- -export interface GetUnifiedHistoryLendingRateReq { - currency: string; - tier?: string; - page?: number; - limit?: number; -} +// console.error('err: ', response?.data); ⋮---- -export interface SubmitUnifiedLoanRepayReq { - currency: string; - amount: string; - currency_pair?: string; -} +// Prevent credentials from leaking into error messages ⋮---- -export interface SetUnifiedCollateralCurrenciesReq { - collateral_type?: 0 | 1; - enable_list?: string[]; - disable_list?: string[]; -} +/** + * @private sign request and set recv window + */ +private async signRequest< + T extends ParamsInQueryBodyOrHeader | undefined = {}, + >( + data: T, + endpoint: string, + method: Method, + signMethod: SignMethod, +): Promise> ⋮---- -export interface CreateQuickRepaymentReq { - debt_currencies: string[]; - available_currencies: string[]; -} +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- -/** POST /unified/delta_neutral — v4.106.97 */ -export interface SetUnifiedDeltaNeutralReq { - enabled: boolean; -} +// recvWindow: this.options.recvWindow, ⋮---- -/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ -export interface SetUserLeverageReq { - leverage?: string; -} +// It's possible to override the recv window on a per rquest level +⋮---- +// console.log('sign params: ', { +// requestBodyToHash, +// paramsStr: toSign, +// url: this.baseUrl, +// urlPath: this.baseUrlPath, +// }); +⋮---- +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: true, + ): Promise>; +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: false | undefined, + ): Promise>; +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: boolean, +) +⋮---- +/** Returns an axios request object. Handles signing process automatically if this is a private API call */ +private async buildRequest( + method: Method, + endpoint: string, + url: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, +): Promise ================ -File: src/types/request/wallet.ts +File: src/types/request/otc.ts ================ -/** GET /wallet/sub_account_balances */ -export interface GetSubAccountBalancesReq { - sub_uid?: string; - page?: number; - limit?: number; -} +import { GateMultipartFile } from '../../lib/multipartUtil.js'; ⋮---- -export interface GetWithdrawalDepositRecordsReq { - currency?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ +⋮---- +export interface CreateOTCQuoteReq { + side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount + pay_coin: string; // Currency the user pays + get_coin: string; // Currency the user receives + pay_amount?: string; // User payment currency amount (required if side is PAY) + get_amount?: string; // Amount of currency received by user (required if side is GET) + create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement + promotion_code?: string; // Promotion code (optional) } ⋮---- -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; +side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount +pay_coin: string; // Currency the user pays +get_coin: string; // Currency the user receives +pay_amount?: string; // User payment currency amount (required if side is PAY) +get_amount?: string; // Amount of currency received by user (required if side is GET) +create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement +promotion_code?: string; // Promotion code (optional) +⋮---- +export interface CreateOTCFiatOrderReq { + type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + side: string; // Quote direction returned by the quote API (used for order validation) + crypto_currency: string; // Cryptocurrency + fiat_currency: string; // Fiat currency + crypto_amount: string; // Amount of cryptocurrency + fiat_amount: string; // Fiat amount + promotion_code?: string; // Promotion code + quote_token: string; // Parameter returned by the quote API + /** From GET /otc/bank/list; default card has is_default=1 */ + bank_id: string; + receive_type?: string; } ⋮---- -export interface GetMainSubTransfersReq { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; +type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) +side: string; // Quote direction returned by the quote API (used for order validation) +crypto_currency: string; // Cryptocurrency +fiat_currency: string; // Fiat currency +crypto_amount: string; // Amount of cryptocurrency +fiat_amount: string; // Fiat amount +promotion_code?: string; // Promotion code +quote_token: string; // Parameter returned by the quote API +/** From GET /otc/bank/list; default card has is_default=1 */ +⋮---- +export interface CreateOTCStablecoinOrderReq { + pay_coin: string; // Currency paid by the user + get_coin: string; // Currency to be received by the user + pay_amount: string; // User payment currency amount + get_amount: string; // Amount of currency received by the user + side: string; // Quote direction returned by the quote API (used for order validation) + quote_token: string; // Parameter returned by the quote API + promotion_code?: string; // Promotion code (optional) } ⋮---- -export interface GetSavedAddressReq { - currency?: string; // v4.106.94: Optional filter by currency - chain?: string; - limit?: string; - page?: number; - verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +pay_coin: string; // Currency paid by the user +get_coin: string; // Currency to be received by the user +pay_amount: string; // User payment currency amount +get_amount: string; // Amount of currency received by the user +side: string; // Quote direction returned by the quote API (used for order validation) +quote_token: string; // Parameter returned by the quote API +promotion_code?: string; // Promotion code (optional) +⋮---- +export interface MarkOTCOrderAsPaidReq { + order_id: string; // Order ID + client_order_id?: string; // Client order ID (gateway/Inner Pay paths) + payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB + payment_receipt?: string; // Alias compatible with payment_receipt_file_key } ⋮---- -currency?: string; // v4.106.94: Optional filter by currency +order_id: string; // Order ID +client_order_id?: string; // Client order ID (gateway/Inner Pay paths) +payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB +payment_receipt?: string; // Alias compatible with payment_receipt_file_key ⋮---- -verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +export interface CancelOTCOrderReq { + order_id: string; // Order ID +} ⋮---- -export interface GetSmallBalanceHistoryReq { - currency?: string; - page?: number; - limit?: number; +order_id: string; // Order ID +⋮---- +export interface GetOTCFiatOrderListReq { + type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + fiat_currency?: string; // Fiat currency + crypto_currency?: string; // Digital currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // DONE: Completed + pn?: string; // Page number + ps?: string; // Number of items per page } ⋮---- -export interface ListPushOrdersReq { - id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; - transaction_type?: string; +type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) +fiat_currency?: string; // Fiat currency +crypto_currency?: string; // Digital currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // DONE: Completed +pn?: string; // Page number +ps?: string; // Number of items per page +⋮---- +export interface GetOTCStablecoinOrderListReq { + page_size?: string; // Number of records per page + page_number?: string; // Page number + coin_name?: string; // Order currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed } ⋮---- -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; +page_size?: string; // Number of records per page +page_number?: string; // Page number +coin_name?: string; // Order currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed +⋮---- +export interface GetOTCFiatOrderDetailReq { + order_id: string; // Order ID } ⋮---- -export interface SubmitMainSubTransferReq { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; +order_id: string; // Order ID +⋮---- +export interface OTCBankIdReq { + bank_id: string; } ⋮---- -/** GET /wallet/transfers */ -export interface GetTransferReq { - tx_id: string; +export interface GetOTCBankSupplementChecklistReq { + bank_id: string; +} +⋮---- +export interface CreateOTCBankReq { + bank_account_name: string; + bank_name: string; + bank_country: string; + bank_address: string; + iban: string; + swift: string; + remittance_line_number?: string; + agent_bank_name?: string; + agent_bank_swift?: string; + documentation_file?: GateMultipartFile; + documentation_file_key?: string; + file_type?: string; +} +⋮---- +export interface SubmitOTCBankPersonalSupplementReq { + bank_id: string; + id_document_front: GateMultipartFile; + id_document_back: GateMultipartFile; + address_proof: GateMultipartFile; +} +⋮---- +export interface SubmitOTCBankEnterpriseSupplementReq { + bank_id: string; + certificate: GateMultipartFile; + share_holders: GateMultipartFile; + passport: GateMultipartFile; + share_holding_structure: GateMultipartFile; + uid?: string; + funds_statement?: GateMultipartFile; + additional?: GateMultipartFile; +} +⋮---- +export interface CreateOTCUploadPreUploadReq { + content_type: string; + scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ -File: src/types/response/wallet.ts +File: src/types/request/spot.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; -} +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ ⋮---- -/** GET /wallet/sub_account_balances item */ -export interface SubAccountBalance { - uid: string; - available: { [key: string]: string }; - /** Locked amount per currency */ - locking?: { [key: string]: string }; +/** Limit-order take-profit / stop-loss on create */ +export interface SpotOrderTPSL { + trigger_price: string; + order_price: string; } ⋮---- -/** Locked amount per currency */ +/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ +export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- -export interface DepositRecord { - id: string; - txid: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'BLOCKED' // Deposit Blocked - | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock - | 'DONE' // Funds Credited to Spot Account - | 'INVALID' // Invalid Transaction - | 'MANUAL' // Manual Review Required - | 'PEND' // Processing - | 'REVIEW' // Under Compliance Review - | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit - chain: string; - refund_status?: // v4.106.95: Blocked deposit refund status - 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; + limit?: number; + with_id?: boolean; } ⋮---- -| 'BLOCKED' // Deposit Blocked -| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock -| 'DONE' // Funds Credited to Spot Account -| 'INVALID' // Invalid Transaction -| 'MANUAL' // Manual Review Required -| 'PEND' // Processing -| 'REVIEW' // Under Compliance Review -| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit -⋮---- -refund_status?: // v4.106.95: Blocked deposit refund status +export interface GetSpotTradesReq { + currency_pair: string; + limit?: number; + last_id?: string; + reverse?: boolean; + from?: number; + to?: number; + page?: number; +} ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: 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 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 GetSpotAccountBookReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + /** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + */ + type?: string; + code?: string; } ⋮---- -export interface 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 }; +/** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + */ +⋮---- +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface SubAccountMarginBalance { +export interface GetSpotOrdersReq { 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; - }; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + side?: 'buy' | 'sell'; } ⋮---- -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 CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -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 DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: number; } ⋮---- -export interface SavedAddress { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; +export interface GetSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; } ⋮---- -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 GetSpotTradingHistoryReq { + currency_pair?: string; + limit?: number; + page?: number; + order_id?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: 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 UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; } ⋮---- -export interface SmallBalanceRecord { +export interface GetSpotInsuranceHistoryReq { + business: 'margin' | 'unified'; currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; + from: number; + to: number; + page?: number; + limit?: number; } ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; + limit?: number; + offset?: number; } ⋮---- -export interface PushOrder { - id: string; - push_uid: number; - receive_uid: number; - currency: string; +export interface SubmitSpotOrderReq { + xGateExptime?: number; + side: 'buy' | 'sell'; amount: string; - create_time: number; - status: - | 'CREATING' - | 'PENDING' - | 'CANCELLING' - | 'CANCELLED' - | 'REFUSING' - | 'REFUSED' - | 'RECEIVING' - | 'RECEIVED'; - message: string; + text?: string; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + stp_act?: string; + action_mode?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; + post_only?: boolean; + trade_quote?: string; } ⋮---- -/** GET /wallet/transfers — AccountTransferDetail */ -export interface AccountTransferDetail { - tx_id: string; - status: 'pending' | 'success' | 'fail'; - currency: string; +export interface UpdateSpotOrderReq { + xGateExptime?: number; + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; +} +⋮---- +/** GET /spot/pov_orders */ +export interface GetSpotPovOrdersReq { + status: 'open' | 'finished'; + currency_pair?: string; + side?: 'buy' | 'sell'; + page?: number; + limit?: number; +} +⋮---- +/** POST /spot/pov_orders */ +export interface CreateSpotPovOrderReq { + currency_pair: string; + side: 'buy' | 'sell'; amount: string; - from_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - to_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - settle?: string | null; - currency_pair?: string | null; + participation_rate: 5 | 10 | 20 | 40; + ttl: '1h' | '6h' | '12h' | '1d' | '2d' | '3d' | '4d' | '5d' | '6d' | '7d'; + limit_price?: string; + trigger_price?: string; + text?: string; +} +⋮---- +/** DELETE /spot/pov_orders */ +export interface CancelSpotPovOrdersReq { + currency_pair?: string; } ================ -File: src/types/websockets/client.ts +File: src/types/request/tradfi.ts ================ -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; +/** TradFi API request types */ ⋮---- -/** - * Event args for subscribing/unsubscribing - */ +export interface TradFiGetSymbolDetailParams { + symbols: string; +} ⋮---- -// export type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +export interface TradFiGetKlinesParams { + kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; + begin_time?: number; + end_time?: number; + limit?: number; +} ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +export interface TradFiCreateTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; +} ⋮---- -/** General configuration for the WebsocketClient */ -export interface WSClientConfigurableOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - useTestnet?: boolean; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - requestOptions?: {}; - - wsUrl?: string; - - wsOptions?: { - protocols?: string[]; - agent?: any; - } & ( - | Omit, 'agent'> - | Omit, 'agent'> - ); - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ - customSignMessageFn?: (message: string, secret: string) => Promise; - - /** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ - reauthWSAPIOnReconnect?: boolean; +export interface TradFiGetTransactionsParams { + begin_time?: number; + end_time?: number; + type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; + page?: number; + page_size?: number; } ⋮---- -/** 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 */ +export interface TradFiCreateOrderReq { + price: string; + price_type: 'trigger' | 'market'; + side: 1 | 2; + symbol: string; + volume: string; + price_tp?: string; + price_sl?: string; + leverage?: number; +} ⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ +export interface TradFiModifyOrderReq { + price: string; + price_tp?: string | null; + price_sl?: string | null; +} ⋮---- -/** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ +export interface TradFiModifyPositionReq { + price_tp?: string | null; + price_sl?: string | null; +} ⋮---- -/** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) - */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pingInterval: number; - pongTimeout: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; - reauthWSAPIOnReconnect: boolean; +export interface TradFiClosePositionReq { + close_type: 1 | 2; + close_volume?: string | null; } - -================ -File: webpack/webpack.config.cjs -================ -function generateConfig(name) ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +export interface TradFiGetOrderHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + side?: 1 | 2; +} ⋮---- -// Node.js core modules not available in browsers -// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +export interface TradFiGetPositionHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + position_dir?: 'Long' | 'Short'; + page?: number; + page_size?: number; +} ⋮---- -// Code is already transpiled from TypeScript, no additional loaders needed +/** GET /tradfi/symbols/commissions */ +export interface TradFiGetSymbolCommissionsParams { + symbols?: string; + category_code?: string; +} ================ -File: src/types/request/crossex.ts +File: src/types/response/earn.ts ================ /**========================================================================================================================== - * CROSSEX + * EARN * ========================================================================================================================== */ ⋮---- -export interface GetCrossExSymbolsReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface DualInvestmentProduct { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_amount?: string; + min_copies: number; + max_copies: number; + /** @deprecated */ + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas +/** @deprecated */ ⋮---- -export interface GetCrossExRiskLimitsReq { - symbols: string; // Trading Pair List, multiple separated by commas +/** GET /earn/dual/order-refund-preview */ +export interface DualOrderRefundPreview { + create_timest: number; + delivery_timest: number; + exercise_price: string; + invest_amount: string; + invest_currency: string; + name: string; + order_id: number; + req_id: string; + refund_service_charge: number; + settle_price: string; + settlement_amount: string; + settlement_currency: string; + settlement_interest: string; + settlement_principle: string; + type: string; + money_back_timest: number; } ⋮---- -symbols: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface GetCrossExTransferCoinsReq { - coin?: string; // Currency +/** GET /earn/dual/project-recommend item */ +export interface DualProjectRecommend { + id: number; + category: number; + type: string; + invest_currency: string; + exercise_currency: string; + apy_display: string; + exercise_price: string; + delivery_timest: number; + min_amount: string; + max_amount: string; + min_copies: number; + max_copies: number; + invest_days: number; + invest_hours: string; } ⋮---- -coin?: string; // Currency -⋮---- -export interface CreateCrossExTransferReq { - coin: string; // Currency - amount: string; // Transfer amount - from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. - to: string; - text?: string; // User-defined ID +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; } ⋮---- -coin: string; // Currency -amount: string; // Transfer amount -from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. -⋮---- -text?: string; // User-defined ID +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ ⋮---- -export interface GetCrossExTransferHistoryReq { - coin?: string; // Query by specified currency name - order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) - from?: number; // Start timestamp for the query - to?: number; // End timestamp for the query, defaults to current time if not specified - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 +export interface FixedTermLadderApr { + apr: string; + left: string; + right: string; } ⋮---- -coin?: string; // Query by specified currency name -order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) -from?: number; // Start timestamp for the query -to?: number; // End timestamp for the query, defaults to current time if not specified -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 -⋮---- -export interface CreateCrossExOrderReq { - text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only - symbol: string; // Unique identifier Exchange_Business_Base_Counter - side: 'BUY' | 'SELL'; - type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) - time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement - qty?: string; // Order quantity (required unless spot market buy) - price?: string; // Limit Order Price (Required for Limit Orders) - quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders - reduce_only?: 'true' | 'false'; // Reduce-only - position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified +export interface FixedTermProductInfo { + pre_redeem: number; + reinvest: number; + redeem_account: number; + min_vip: number; + max_vip: number; } ⋮---- -text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only -symbol: string; // Unique identifier Exchange_Business_Base_Counter -⋮---- -type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) -time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement -qty?: string; // Order quantity (required unless spot market buy) -price?: string; // Limit Order Price (Required for Limit Orders) -quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders -reduce_only?: 'true' | 'false'; // Reduce-only -position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified -⋮---- -export interface GetCrossExMarketTickersReq { - symbols?: string; -} -⋮---- -export interface GetCrossExMarketFundingInfoReq { - symbols?: string; -} -⋮---- -/** Either order_id or text required; order_id wins if both set */ -export interface CancelBatchCrossExOrdersReq { - order_id?: string; - text?: string; -} -⋮---- -export interface ModifyCrossExOrderReq { - qty?: string; // modify amount - price?: string; // modify price -} -⋮---- -qty?: string; // modify amount -price?: string; // modify price -⋮---- -export interface CreateCrossExConvertQuoteReq { - exchange_type: string; // Exchange Type - from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) - to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) - from_amount: string; // Amount to sell -} -⋮---- -exchange_type: string; // Exchange Type -from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) -to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) -from_amount: string; // Amount to sell -⋮---- -export interface CreateCrossExConvertOrderReq { - quote_id: string; // Inquiry ID +export interface FixedTermBonusInfo { + id?: number; + product_id?: number; + asset?: string; + bonus_asset?: string; + kyc_limit?: string; + ladder_apr?: FixedTermLadderApr[]; + total_bonus_amount?: string; + user_total_bonus_amount?: string; + status?: number; + start_time?: string; + end_time?: string; + create_time?: string; + start_at?: number; + end_at?: number; + total_issued_amount?: string; + user_total_issued_amount?: string; + bonus_asset_price?: string; + product_asset_price?: string; + product_year_rate?: string; } ⋮---- -quote_id: string; // Inquiry ID -⋮---- -export interface UpdateCrossExAccountReq { - position_mode?: string; // Futures position mode (SINGLE/DUAL) - account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) - exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) +export interface FixedTermCouponInfo { + id?: number; + business?: number; + user_id?: number; + asset?: string; + order_id?: number; + financial_rate_id?: number; + buy_limit_low?: string; + buy_limit_high?: string; + rate_day?: number; + rate_ratio?: string; + coupon_days?: number; + coupon_principal?: string; + coupon_year_rate?: string; + coupon_interest?: string; + status?: number; + finish_time?: string; + create_time?: string; } ⋮---- -position_mode?: string; // Futures position mode (SINGLE/DUAL) -account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) -exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) -⋮---- -export interface GetCrossExAccountsReq { - exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) +export interface FixedTermLendOrder { + id?: number; + business?: number; + order_id?: number; + user_id?: number; + asset?: string; + product_id?: number; + lock_up_period?: number; + principal?: string; + year_rate?: string; + product_type?: number; + interest?: string; + status?: number; + reinvest_status?: number; + redeem_account_type?: number; + origin_order?: string; + redeem_type?: number; + redeem_time?: string; + finish_time?: string; + create_time?: string; + year_rate_perent?: string; + total_year_rate_percent?: string; + total_interest?: string; + product_info?: FixedTermProductInfo; + bonus_info?: FixedTermBonusInfo; + coupon_info?: FixedTermCouponInfo; + redeem_at?: number; + finish_at?: number; + create_at?: number; + icon?: string; } ⋮---- -exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) -⋮---- -export interface SetCrossExPositionLeverageReq { - symbol: string; // Currency pair - leverage: string; // leverage +export interface FixedTermProduct { + id?: number; + name?: string; + asset?: string; + lock_up_period?: number; + min_lend_amount?: string; + user_max_lend_amount?: string; + total_lend_amount?: string; + year_rate?: string; + type?: number; + pre_redeem?: number; + reinvest?: number; + redeem_account?: number; + min_vip?: number; + max_vip?: number; + status?: number; + create_time?: string; + user_max_lend_volume?: string; + user_total_amount?: string; + sale_status?: number; } ⋮---- -symbol: string; // Currency pair -leverage: string; // leverage -⋮---- -export interface GetCrossExPositionLeverageReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface FixedTermProductSimple { + id?: number; + asset?: string; + lock_up_period?: number; + year_rate?: string; + type?: number; + pre_redeem?: number; + reinvest?: number; + simple_earn?: number; + min_vip?: number; + max_vip?: number; + sale_status?: number; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface SetCrossExMarginPositionLeverageReq { - symbol: string; // Currency pair - leverage: string; // leverage +export interface GetEarnFixedTermProductsResponse { + code: number; + message: string; + data: { + list: FixedTermProduct[]; + total: number; + }; + timestamp: number; } ⋮---- -symbol: string; // Currency pair -leverage: string; // leverage -⋮---- -export interface GetCrossExMarginPositionLeverageReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface GetEarnFixedTermProductsByAssetResponse { + code: number; + message: string; + data: { + list: FixedTermProductSimple[]; + }; + timestamp: number; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface CloseCrossExPositionReq { - symbol: string; // Trading Pair - position_side?: string; // Position Direction +export interface CreateEarnFixedTermLendResponse { + code?: number; + message?: string; + data?: { + order_id?: number; + }; + timestamp?: number; } ⋮---- -symbol: string; // Trading Pair -position_side?: string; // Position Direction -⋮---- -export interface GetCrossExInterestRateReq { - coin?: string; // Currency - exchange_type?: string; // Exchange +export interface GetEarnFixedTermLendsResponse { + code: number; + message: string; + data: { + list: FixedTermLendOrder[]; + total: number; + }; + timestamp: number; } ⋮---- -coin?: string; // Currency -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExPositionsReq { - symbol?: string; // Trading Pair - exchange_type?: string; // Exchange +export interface CreateEarnFixedTermPreRedeemResponse { + code?: number; + message?: string; + data?: Record; + timestamp?: number; } ⋮---- -symbol?: string; // Trading Pair -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExMarginPositionsReq { - symbol?: string; // Currency pair - exchange_type?: string; // Exchange +export interface FixedTermHistoryRecord { + id?: number; + order_id?: number; + user_id?: number; + asset?: string; + uniq_time?: string; + bonus_id?: number; + product_id?: number; + bonus_asset?: string; + total_principal?: string; + amount?: string; + asset_price?: string; + status?: number; + detail?: string; + create_time?: string; + create_at?: number; + lock_up_period?: number; } ⋮---- -symbol?: string; // Currency pair -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExAdlRankReq { - symbol: string; // Trading Pair +export interface GetEarnFixedTermHistoryResponse { + code?: number; + message?: string; + data?: { + list?: FixedTermHistoryRecord[]; + total?: number; + }; + timestamp?: number; } -⋮---- -symbol: string; // Trading Pair -⋮---- -export interface GetCrossExOpenOrdersReq { - symbol?: string; // Trading Pair - exchange_type?: string; // Exchange - business_type?: string; // Business Type + +================ +File: src/types/response/unified.ts +================ +export interface UnifiedAccountInfo { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin + user_id: number; + refresh_time: number; + locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin + balances: { + [key: string]: { + available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode + freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode + borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) + equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode + total_freeze: string; // Total frozen (deprecated, to be removed) + total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes + funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin + funding_version: string; // Funding version + cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode + iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode + im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled + balance_version?: number; // Balance version number (int64) + }; + }; + total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) + borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode + total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode + unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode + unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode + leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) + spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode + options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode + spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled + margin_mode?: string; + total_balance?: string; + cross_leverage?: string; + portfolio_margin?: string; + risk_level?: string; + is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all + borrow_amount?: string; + cross_margin_leverage?: string; + use_funding?: boolean; // Whether Earn funds are used as margin } ⋮---- -symbol?: string; // Trading Pair -exchange_type?: string; // Exchange -business_type?: string; // Business Type -⋮---- -export interface GetCrossExHistoryOrdersReq { - page?: number; // Page number - limit?: number; // Maximum number of records returned in a single list - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp - /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ - attributes?: string; -} +mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- -page?: number; // Page number -limit?: number; // Maximum number of records returned in a single list +locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp -/** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ +available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode +freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode +borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) +equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode +total_freeze: string; // Total frozen (deprecated, to be removed) +total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes +funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin +funding_version: string; // Funding version +cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode +iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode +im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled +balance_version?: number; // Balance version number (int64) ⋮---- -export interface GetCrossExHistoryPositionsReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp -} +total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) +borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode +total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode +unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode +unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode +leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) +spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode +options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode +spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +use_funding?: boolean; // Whether Earn funds are used as margin ⋮---- -export interface GetCrossExHistoryMarginPositionsReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp +export interface UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 -⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp -⋮---- -export interface GetCrossExHistoryMarginInterestsReq { - symbol?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - exchange_type?: string; +export interface 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 GetCrossExHistoryTradesReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp +export interface UnifiedInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +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; + }[]; +} ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +export interface UnifiedCurrencyDiscountTiers { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: string; + }[]; +} ⋮---- -export interface GetCrossExAccountBookReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - coin?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp +export interface UserCurrencyLeverageConfig { + current_leverage: string; + min_leverage: string; + max_leverage: string; + debit: string; + available_margin: string; + borrowable: string; + except_leverage_borrowable: string; } ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +export interface UnifiedLoanCurrency { + name: string; + prec: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + loan_status: string; +} ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +export interface UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; +} ⋮---- -export interface GetCrossExCoinDiscountRateReq { - coin?: string; - exchange_type?: string; // OKX/GATE/BINANCE/BYBIT +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: string; } ⋮---- -exchange_type?: string; // OKX/GATE/BINANCE/BYBIT +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 UpdateCrossExPositionsMarginReq { - symbol: string; - margin: string; - position_side?: 'NONE' | 'LONG' | 'SHORT'; +export interface UnifiedCollateralCurrenciesResp { + is_success: boolean; } - -================ -File: src/types/response/crossex.ts -================ -/**========================================================================================================================== - * CROSSEX - * ========================================================================================================================== - */ ⋮---- -export interface CrossExSymbol { - symbol: string; - exchange_type: string; - business_type: string; - state: string; - min_size: string; - min_notional: string; - lot_size: string; - tick_size: string; - max_num_orders: string; - max_market_size: string; - max_limit_size: string; - contract_size: string; - liquidation_fee: string; - delist_time: string; - support_rpi?: string; // true/false whether RPI orders are supported - support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders +export interface UnifiedQuickRepayDebtItem { + currency?: string; + debt_amount?: string; + estimated_usd?: string; + borrowed?: string; + neg_balance?: string; } ⋮---- -support_rpi?: string; // true/false whether RPI orders are supported -support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders +export interface UnifiedQuickRepayAvailableItem { + currency?: string; + available?: string; + estimated_usd?: string; +} ⋮---- -export interface CrossExRiskLimitTier { - min_risk_limit_value: string; // Minimum risk limit value - max_risk_limit_value: string; // Maximum risk limit value - leverage_max: string; // Maximum leverage - maintenance_rate: string; // Maintenance margin rate - tier: string; // Tier - quick_cal_amount: string; // Quick-calculation amount for this risk tier +export interface QuickEstimatedRepayment { + debt_currencies?: UnifiedQuickRepayDebtItem[]; + available_currencies?: UnifiedQuickRepayAvailableItem[]; } ⋮---- -min_risk_limit_value: string; // Minimum risk limit value -max_risk_limit_value: string; // Maximum risk limit value -leverage_max: string; // Maximum leverage -maintenance_rate: string; // Maintenance margin rate -tier: string; // Tier -quick_cal_amount: string; // Quick-calculation amount for this risk tier +export interface QuickRepayRepaidInfo { + currency: string; + repaid: string; + left: string; +} ⋮---- -export interface CrossExRiskLimit { - symbol: string; - tiers: CrossExRiskLimitTier[]; +export interface QuickRepayUsedInfo { + currency: string; + used: string; } ⋮---- -export interface CrossExTransferCoin { - coin: string; // Currency - min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) - est_fee: number; // Estimated Fee - precision: number; // Precision - is_disabled: number; // If it is disabled. 0 means NOT being disabled +export interface QuickRepaymentResp { + order_id: string; + repaid_infos: QuickRepayRepaidInfo[]; + used_infos: QuickRepayUsedInfo[]; } ⋮---- -coin: string; // Currency -min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) -est_fee: number; // Estimated Fee -precision: number; // Precision -is_disabled: number; // If it is disabled. 0 means NOT being disabled +/** GET/POST /unified/delta_neutral — v4.106.97 */ +export interface DeltaNeutralEnabled { + enabled: boolean; +} ⋮---- -export interface CreateCrossExTransferResp { - tx_id: string; // Order ID - text: string; // User-defined Order ID +/** POST /unified/leverage/user_setting failed currency entry */ +export interface LeverageFailedCurrency { + currency: string; + reason: string; } + +================ +File: src/types/websockets/client.ts +================ +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -tx_id: string; // Order ID -text: string; // User-defined Order ID +/** + * Event args for subscribing/unsubscribing + */ ⋮---- -export interface CrossExTransferHistory { - id: string; // Order ID - text: string; // Client Custom ID - from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) - to_account_type: string; - coin: string; // Currency - amount: string; // Transfer amount, the amount requested for the transfer - actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) - status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress - fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) - create_time: number; // Creation time of order - update_time: number; // Order Update Time +// export type WsTopicSubscribePrivateArgsV2 = +// | WsTopicSubscribePrivateInstIdArgsV2 +// | WsTopicSubscribePrivateCoinArgsV2; +⋮---- +// export type WsTopicSubscribeEventArgsV2 = +// | WsTopicSubscribePublicArgsV2 +// | WsTopicSubscribePrivateArgsV2; +⋮---- +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + /** Use the Gate TestNet WebSocket hosts. */ + useTestnet?: boolean; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + requestOptions?: {}; + + wsUrl?: string; + + wsOptions?: { + protocols?: string[]; + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; + + /** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ + reauthWSAPIOnReconnect?: boolean; } ⋮---- -id: string; // Order ID -text: string; // Client Custom ID -from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) +/** Your API key */ ⋮---- -coin: string; // Currency -amount: string; // Transfer amount, the amount requested for the transfer -actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) -status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress -fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) -create_time: number; // Creation time of order -update_time: number; // Order Update Time +/** Your API secret */ ⋮---- -export interface CreateCrossExOrderResp { - order_id: number | string; - text: string; // User-defined Order ID -} +/** Use the Gate TestNet WebSocket hosts. */ ⋮---- -text: string; // User-defined Order ID +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- -export interface CancelCrossExOrderResp { - order_id: number; - text: string; -} +/** How often to check if the connection is alive */ ⋮---- -export interface ModifyCrossExOrderResp { - order_id: number; - text: string; -} +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -export interface CrossExOrder { - user_id: string; // User ID - order_id: string; // Order ID - text: string; // Client Order ID - state: string; // Order Status - symbol: string; // Currency pair - side: string; // direction - type: string; // type - attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT - exchange_type: string; // Exchange - business_type: string; // Business Type - qty: string; // Base Currency Quantity - quote_qty: string; // Quote Currency Quantity - price: string; // Price - time_in_force: string; // Time in Force Strategy - executed_qty: string; // Filled Quantity - executed_amount: string; // Filled Amount - executed_avg_price: string; // Average Filled Price - fee_coin: string; // Fee currency - fee: string; // fee - reduce_only: string; // Reduce Position Only - leverage: string; // leverage - reason: string; // Reason - last_executed_qty: string; // Latest Filled Quantity - last_executed_price: string; // Latest Filled Price - last_executed_amount: string; // Latest Filled Amount - position_side: string; // Position Direction - create_time: string; // Created time - update_time: string; // Update time -} -⋮---- -user_id: string; // User ID -order_id: string; // Order ID -text: string; // Client Order ID -state: string; // Order Status -symbol: string; // Currency pair -side: string; // direction -type: string; // type -attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT -exchange_type: string; // Exchange -business_type: string; // Business Type -qty: string; // Base Currency Quantity -quote_qty: string; // Quote Currency Quantity -price: string; // Price -time_in_force: string; // Time in Force Strategy -executed_qty: string; // Filled Quantity -executed_amount: string; // Filled Amount -executed_avg_price: string; // Average Filled Price -fee_coin: string; // Fee currency -fee: string; // fee -reduce_only: string; // Reduce Position Only -leverage: string; // leverage -reason: string; // Reason -last_executed_qty: string; // Latest Filled Quantity -last_executed_price: string; // Latest Filled Price -last_executed_amount: string; // Latest Filled Amount -position_side: string; // Position Direction -create_time: string; // Created time -update_time: string; // Update time -⋮---- -export interface CreateCrossExConvertQuoteResp { - quote_id: string; // Quote ID - valid_ms: string; // Valid time (milliseconds timestamp) - from_coin: string; // Asset Sold - to_coin: string; // Asset Bought - from_amount: string; // Amount to sell - to_amount: string; // Amount to buy - price: string; // Price -} -⋮---- -quote_id: string; // Quote ID -valid_ms: string; // Valid time (milliseconds timestamp) -from_coin: string; // Asset Sold -to_coin: string; // Asset Bought -from_amount: string; // Amount to sell -to_amount: string; // Amount to buy -price: string; // Price -⋮---- -export interface CreateCrossExConvertOrderResp { - order_id: string; // Order ID - text: string; // User-defined order ID text -} -⋮---- -order_id: string; // Order ID -text: string; // User-defined order ID text -⋮---- -export interface UpdateCrossExAccountResp { - position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) - account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) - exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) -} -⋮---- -position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) -account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) -exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) -⋮---- -export interface CrossExAccountAsset { - user_id: string; // User ID - coin: string; // Currency - exchange_type: string; // Exchange - balance: string; // Balance - upnl: string; // Unrealized P&L - equity: string; // Equity (only USDT has a value; other assets are 0) - futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) - futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) - borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) - borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) - available_balance: string; // Available Balance - liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) -} -⋮---- -user_id: string; // User ID -coin: string; // Currency -exchange_type: string; // Exchange -balance: string; // Balance -upnl: string; // Unrealized P&L -equity: string; // Equity (only USDT has a value; other assets are 0) -futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) -futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) -borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) -borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) -available_balance: string; // Available Balance -liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) -⋮---- -export interface CrossExAccount { - user_id: string; // User ID - available_margin: string; // Available Margin - margin_balance: string; // margin balance - initial_margin: string; // Initial Margin - maintenance_margin: string; // Maintenance margin - initial_margin_rate: string; // Initial margin rate - maintenance_margin_rate: string; // Maintenance margin rate - position_mode: string; // Contract Position Mode - account_limit: string; // Account limit - create_time: string; // Created time - update_time: string; // Update time - account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode - exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange - assets: CrossExAccountAsset[]; -} -⋮---- -user_id: string; // User ID -available_margin: string; // Available Margin -margin_balance: string; // margin balance -initial_margin: string; // Initial Margin -maintenance_margin: string; // Maintenance margin -initial_margin_rate: string; // Initial margin rate -maintenance_margin_rate: string; // Maintenance margin rate -position_mode: string; // Contract Position Mode -account_limit: string; // Account limit -create_time: string; // Created time -update_time: string; // Update time -account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode -exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange -⋮---- -export interface SetCrossExPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage -} -⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage -⋮---- -export interface CrossExPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; -} -⋮---- -symbol: string; // Currency pair -⋮---- -export interface SetCrossExMarginPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage -} -⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage -⋮---- -export interface CrossExMarginPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; -} -⋮---- -symbol: string; // Currency pair -⋮---- -export interface CloseCrossExPositionResp { - order_id: string; // Order ID - text: string; // User-defined Order ID -} -⋮---- -order_id: string; // Order ID -text: string; // User-defined Order ID -⋮---- -export interface CrossExInterestRate { - coin: string; // Currency - exchange_type: string; // Exchange - hour_interest_rate: string; // Hourly Interest Rate - time: string; // Millisecond Timestamp -} -⋮---- -coin: string; // Currency -exchange_type: string; // Exchange -hour_interest_rate: string; // Hourly Interest Rate -time: string; // Millisecond Timestamp -⋮---- -export interface CrossExSpecialFee { - symbol: string; // Currency pair - taker_fee_rate: string; // Taker fee rate - maker_fee_rate: string; // Maker fee rate - rpi_fee_rate?: string; // RPI order maker fee rate -} -⋮---- -symbol: string; // Currency pair -taker_fee_rate: string; // Taker fee rate -maker_fee_rate: string; // Maker fee rate -rpi_fee_rate?: string; // RPI order maker fee rate -⋮---- -export interface CrossExFeeRate { - exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) - spot_maker_fee: string; // spot Maker fee rate - spot_taker_fee: string; // spot Taker fee rate - spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate - future_maker_fee: string; // contract Maker fee rate - future_taker_fee: string; // contract Taker fee rate - future_rpi_maker_fee?: string; // Futures RPI order maker fee rate - special_fee_list: CrossExSpecialFee[]; -} +/** Delay in milliseconds before respawning the connection */ ⋮---- -exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) -spot_maker_fee: string; // spot Maker fee rate -spot_taker_fee: string; // spot Taker fee rate -spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate -future_maker_fee: string; // contract Maker fee rate -future_taker_fee: string; // contract Taker fee rate -future_rpi_maker_fee?: string; // Futures RPI order maker fee rate +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ ⋮---- -export interface CrossExMarketTicker { - symbol: string; - last_price: string; - open_24h: string; - low_24h: string; - high_24h: string; - volume_24h_base: string; - volume_24h_quote: string; - mark_price: string; - index_price: string; - open_interest: string; - open_interest_quote: string; - timestamp: string; -} +/** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ ⋮---- -export interface CrossExMarketFundingInfo { - symbol: string; - funding_rate: string; - funding_interval: string; - funding_time: string; // Next funding time +/** + * 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; } -⋮---- -funding_time: string; // Next funding time -⋮---- -export interface CancelBatchCrossExOrdersResp { - order_id: string; - text: string; - accepted: string; // "true" | "false" - label: string; - message: string; -} -⋮---- -accepted: string; // "true" | "false" -⋮---- -export interface CrossExPosition { - user_id: string; // User ID - position_id: string; // Position ID - symbol: string; // Currency pair - position_side: string; // Position Direction - initial_margin: string; // Initial Margin - maintenance_margin: string; // Maintenance margin - position_qty: string; // Position Quantity - position_value: string; // Position Value - upnl: string; // Unrealized P&L - upnl_rate: string; // Unrealized P&L Ratio - entry_price: string; // Position Average Entry Price - mark_price: string; // Mark price - leverage: string; // Position Leverage - max_leverage: string; // Maximum leverage - risk_limit: string; // Position risk limit - fee: string; // Position Fee - funding_fee: string; // Position Funding Fee - funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) - create_time: string; // Position Creation Time - update_time: string; // Position Update Time - closed_pnl: string; // Realized PnL -} -⋮---- -user_id: string; // User ID -position_id: string; // Position ID -symbol: string; // Currency pair -position_side: string; // Position Direction -initial_margin: string; // Initial Margin -maintenance_margin: string; // Maintenance margin -position_qty: string; // Position Quantity -position_value: string; // Position Value -upnl: string; // Unrealized P&L -upnl_rate: string; // Unrealized P&L Ratio -entry_price: string; // Position Average Entry Price -mark_price: string; // Mark price -leverage: string; // Position Leverage -max_leverage: string; // Maximum leverage -risk_limit: string; // Position risk limit -fee: string; // Position Fee -funding_fee: string; // Position Funding Fee -funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) -create_time: string; // Position Creation Time -update_time: string; // Position Update Time -closed_pnl: string; // Realized PnL -⋮---- -export interface CrossExMarginPosition { - user_id: string; // User ID - position_id: string; // Leveraged Position ID - symbol: string; // Trading Pair - position_side: string; // Position Direction - initial_margin: string; // Initial position margin - maintenance_margin: string; // Position maintenance margin - asset_qty: string; // Position Asset Quantity - asset_coin: string; // Position Asset Currency - position_value: string; // Position Value - liability: string; // Debt Quantity - liability_coin: string; // Debt Currency - interest: string; // Deducted Interest - max_position_qty: string; // Max Trade Size - entry_price: string; // Position Cost Price (Average Opening Price) - index_price: string; // Index price - upnl: string; // Unrealized P&L - upnl_rate: string; // Unrealized P&L Ratio - leverage: string; // Opening Leverage - max_leverage: string; // Maximum leverage - create_time: string; // Created time - update_time: string; // Update time -} -⋮---- -user_id: string; // User ID -position_id: string; // Leveraged Position ID -symbol: string; // Trading Pair -position_side: string; // Position Direction -initial_margin: string; // Initial position margin -maintenance_margin: string; // Position maintenance margin -asset_qty: string; // Position Asset Quantity -asset_coin: string; // Position Asset Currency -position_value: string; // Position Value -liability: string; // Debt Quantity -liability_coin: string; // Debt Currency -interest: string; // Deducted Interest -max_position_qty: string; // Max Trade Size -entry_price: string; // Position Cost Price (Average Opening Price) -index_price: string; // Index price -upnl: string; // Unrealized P&L -upnl_rate: string; // Unrealized P&L Ratio -leverage: string; // Opening Leverage -max_leverage: string; // Maximum leverage -create_time: string; // Created time -update_time: string; // Update time -⋮---- -export interface CrossExAdlRank { - user_id: string; // User ID - symbol: string; // Currency pair - crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) - exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) -} -⋮---- -user_id: string; // User ID -symbol: string; // Currency pair -crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) -exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) -⋮---- -export interface CrossExHistoryPosition { - position_id: string; // Position ID - user_id: string; // User ID - symbol: string; // Currency pair - closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) - closed_pnl: string; // Close Position P&L - closed_pnl_rate: string; // Close Position P&L Ratio - open_avg_price: string; // Average Opening Price - closed_avg_price: string; // Average Close Price - max_position_qty: string; // Max Trade Size - closed_qty: string; // Close Position Quantity - closed_value: string; // Close Position Value - fee: string; // Position Accumulated Fees - liq_fee: string; // Liquidation Fee - funding_fee: string; // Funding Fee - position_side: string; // Position Direction Before Close - position_mode: string; // Position Mode at Close - leverage: string; // Leverage at Close - margin_mode?: 'CROSS' | 'ISOLATED'; - business_type: string; // Business Type - create_time: string; // Created time - update_time: string; // Update time -} -⋮---- -position_id: string; // Position ID -user_id: string; // User ID -symbol: string; // Currency pair -closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) -closed_pnl: string; // Close Position P&L -closed_pnl_rate: string; // Close Position P&L Ratio -open_avg_price: string; // Average Opening Price -closed_avg_price: string; // Average Close Price -max_position_qty: string; // Max Trade Size -closed_qty: string; // Close Position Quantity -closed_value: string; // Close Position Value -fee: string; // Position Accumulated Fees -liq_fee: string; // Liquidation Fee -funding_fee: string; // Funding Fee -position_side: string; // Position Direction Before Close -position_mode: string; // Position Mode at Close -leverage: string; // Leverage at Close -⋮---- -business_type: string; // Business Type -create_time: string; // Created time -update_time: string; // Update time -⋮---- -export interface CrossExHistoryMarginPosition { - position_id: string; // Position ID - user_id: string; // User ID - symbol: string; // Currency pair - closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) - closed_pnl: string; // Close Position P&L - closed_pnl_rate: string; // Close Position P&L Ratio - open_avg_price: string; // Average Opening Price - closed_avg_price: string; // Average Close Price - max_position_qty: string; // Max Trade Size - closed_qty: string; // Close Position Quantity - closed_value: string; // Close Position Value - liq_fee: string; // Liquidation Fee - position_side: string; // Position Direction Before Close - leverage: string; // Leverage at Close - interest: string; // Total Deducted Interest - business_type: string; // Position Business Type - create_time: string; // Created time - update_time: string; // Update time -} -⋮---- -position_id: string; // Position ID -user_id: string; // User ID -symbol: string; // Currency pair -closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) -closed_pnl: string; // Close Position P&L -closed_pnl_rate: string; // Close Position P&L Ratio -open_avg_price: string; // Average Opening Price -closed_avg_price: string; // Average Close Price -max_position_qty: string; // Max Trade Size -closed_qty: string; // Close Position Quantity -closed_value: string; // Close Position Value -liq_fee: string; // Liquidation Fee -position_side: string; // Position Direction Before Close -leverage: string; // Leverage at Close -interest: string; // Total Deducted Interest -business_type: string; // Position Business Type -create_time: string; // Created time -update_time: string; // Update time -⋮---- -export interface CrossExHistoryMarginInterest { - userId: string; // User ID - symbol: string; // Trading Pair - interest_id: string; // Interest Deduction ID - liability_id: string; // Debt Source ID, can be Order ID or Position ID - liability: string; // Debt Quantity - liability_coin: string; // Debt Currency - interest: string; // Interest - interest_rate: string; // interest rate - interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) - create_time: string; // Created time - exchange_type: string; // Exchange -} -⋮---- -userId: string; // User ID -symbol: string; // Trading Pair -interest_id: string; // Interest Deduction ID -liability_id: string; // Debt Source ID, can be Order ID or Position ID -liability: string; // Debt Quantity -liability_coin: string; // Debt Currency -interest: string; // Interest -interest_rate: string; // interest rate -interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) -create_time: string; // Created time -exchange_type: string; // Exchange -⋮---- -export interface CrossExHistoryTrade { - user_id: string; // User ID - transaction_id: string; // filled records ID - order_id: string; // Order ID - text: string; // User Order ID - symbol: string; // Currency pair - exchange_type: string; // Exchange - business_type: string; // Business Type - side: string; // Buy/Sell Direction - qty: string; // Trading size - price: string; // Fill Price - fee: string; // fee - fee_coin: string; // Fee currency - fee_rate: string; // Fee Rate - match_role: string; // Filled Role - rpnl: string; // Realized P&L - position_mode: string; // Position Mode - position_side: string; // Position Direction - create_time: string; // Created time -} -⋮---- -user_id: string; // User ID -transaction_id: string; // filled records ID -order_id: string; // Order ID -text: string; // User Order ID -symbol: string; // Currency pair -exchange_type: string; // Exchange -business_type: string; // Business Type -side: string; // Buy/Sell Direction -qty: string; // Trading size -price: string; // Fill Price -fee: string; // fee -fee_coin: string; // Fee currency -fee_rate: string; // Fee Rate -match_role: string; // Filled Role -rpnl: string; // Realized P&L -position_mode: string; // Position Mode -position_side: string; // Position Direction -create_time: string; // Created time -⋮---- -export interface CrossExAccountBook { - id: string; // Account Change Record ID - user_id: string; // User ID - business_id: string; // Business ID - type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY - exchange_type: string; // Exchange - coin: string; // Currency - change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) - balance: string; // Balance after change - create_time: string; // Created time -} -⋮---- -id: string; // Account Change Record ID -user_id: string; // User ID -business_id: string; // Business ID -type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY -exchange_type: string; // Exchange -coin: string; // Currency -change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) -balance: string; // Balance after change -create_time: string; // Created time -⋮---- -export interface CrossExCoinDiscountRate { - coin: string; // Currency - exchange_type: string; // Exchange - tier: string; // Tier - min_value: string; // Minimum value - max_value: string; // Maximum value - discount_rate: string; // Discount rate -} -⋮---- -coin: string; // Currency -exchange_type: string; // Exchange -tier: string; // Tier -min_value: string; // Minimum value -max_value: string; // Maximum value -discount_rate: string; // Discount rate -⋮---- -export interface UpdateCrossExPositionsMarginResp { - symbol?: string; - margin?: string; - position_side?: 'NONE' | 'LONG' | 'SHORT'; -} - -================ -File: src/types/response/earn.ts -================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ -⋮---- -export interface DualInvestmentProduct { - id: number; - instrument_name: string; - invest_currency: string; - exercise_currency: string; - exercise_price: number; - delivery_time: number; - min_amount?: string; - min_copies: number; - max_copies: number; - /** @deprecated */ - per_value: string; - apy_display: string; - start_time: number; - end_time: number; - status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; -} -⋮---- -/** @deprecated */ -⋮---- -/** GET /earn/dual/order-refund-preview */ -export interface DualOrderRefundPreview { - create_timest: number; - delivery_timest: number; - exercise_price: string; - invest_amount: string; - invest_currency: string; - name: string; - order_id: number; - req_id: string; - refund_service_charge: number; - settle_price: string; - settlement_amount: string; - settlement_currency: string; - settlement_interest: string; - settlement_principle: string; - type: string; - money_back_timest: number; -} -⋮---- -/** GET /earn/dual/project-recommend item */ -export interface DualProjectRecommend { - id: number; - category: number; - type: string; - invest_currency: string; - exercise_currency: string; - apy_display: string; - exercise_price: string; - delivery_timest: number; - min_amount: string; - max_amount: string; - min_copies: number; - max_copies: number; - invest_days: number; - invest_hours: string; -} -⋮---- -export interface DualInvestmentOrder { - id: number; - plan_id: number; - copies: string; - invest_amount: string; - settlement_amount: string; - create_time: number; - complete_time: number; - status: - | 'INIT' - | 'SETTLEMENT_SUCCESS' - | 'SETTLEMENT_PROCESSING' - | 'CANCELED' - | 'FAILED'; - invest_currency: string; - exercise_currency: string; - exercise_price: string; - settlement_price: string; - settlement_currency: string; - apy_display: string; - apy_settlement: string; - delivery_time: number; - text: string; -} -⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ -⋮---- -export interface FixedTermLadderApr { - apr: string; - left: string; - right: string; -} -⋮---- -export interface FixedTermProductInfo { - pre_redeem: number; - reinvest: number; - redeem_account: number; - min_vip: number; - max_vip: number; -} -⋮---- -export interface FixedTermBonusInfo { - id?: number; - product_id?: number; - asset?: string; - bonus_asset?: string; - kyc_limit?: string; - ladder_apr?: FixedTermLadderApr[]; - total_bonus_amount?: string; - user_total_bonus_amount?: string; - status?: number; - start_time?: string; - end_time?: string; - create_time?: string; - start_at?: number; - end_at?: number; - total_issued_amount?: string; - user_total_issued_amount?: string; - bonus_asset_price?: string; - product_asset_price?: string; - product_year_rate?: string; -} -⋮---- -export interface FixedTermCouponInfo { - id?: number; - business?: number; - user_id?: number; - asset?: string; - order_id?: number; - financial_rate_id?: number; - buy_limit_low?: string; - buy_limit_high?: string; - rate_day?: number; - rate_ratio?: string; - coupon_days?: number; - coupon_principal?: string; - coupon_year_rate?: string; - coupon_interest?: string; - status?: number; - finish_time?: string; - create_time?: string; -} -⋮---- -export interface FixedTermLendOrder { - id?: number; - business?: number; - order_id?: number; - user_id?: number; - asset?: string; - product_id?: number; - lock_up_period?: number; - principal?: string; - year_rate?: string; - product_type?: number; - interest?: string; - status?: number; - reinvest_status?: number; - redeem_account_type?: number; - origin_order?: string; - redeem_type?: number; - redeem_time?: string; - finish_time?: string; - create_time?: string; - year_rate_perent?: string; - total_year_rate_percent?: string; - total_interest?: string; - product_info?: FixedTermProductInfo; - bonus_info?: FixedTermBonusInfo; - coupon_info?: FixedTermCouponInfo; - redeem_at?: number; - finish_at?: number; - create_at?: number; - icon?: string; -} -⋮---- -export interface FixedTermProduct { - id?: number; - name?: string; - asset?: string; - lock_up_period?: number; - min_lend_amount?: string; - user_max_lend_amount?: string; - total_lend_amount?: string; - year_rate?: string; - type?: number; - pre_redeem?: number; - reinvest?: number; - redeem_account?: number; - min_vip?: number; - max_vip?: number; - status?: number; - create_time?: string; - user_max_lend_volume?: string; - user_total_amount?: string; - sale_status?: number; -} -⋮---- -export interface FixedTermProductSimple { - id?: number; - asset?: string; - lock_up_period?: number; - year_rate?: string; - type?: number; - pre_redeem?: number; - reinvest?: number; - simple_earn?: number; - min_vip?: number; - max_vip?: number; - sale_status?: number; -} -⋮---- -export interface GetEarnFixedTermProductsResponse { - code: number; - message: string; - data: { - list: FixedTermProduct[]; - total: number; - }; - timestamp: number; -} -⋮---- -export interface GetEarnFixedTermProductsByAssetResponse { - code: number; - message: string; - data: { - list: FixedTermProductSimple[]; - }; - timestamp: number; -} -⋮---- -export interface CreateEarnFixedTermLendResponse { - code?: number; - message?: string; - data?: { - order_id?: number; - }; - timestamp?: number; -} -⋮---- -export interface GetEarnFixedTermLendsResponse { - code: number; - message: string; - data: { - list: FixedTermLendOrder[]; - total: number; - }; - timestamp: number; -} -⋮---- -export interface CreateEarnFixedTermPreRedeemResponse { - code?: number; - message?: string; - data?: Record; - timestamp?: number; -} -⋮---- -export interface FixedTermHistoryRecord { - id?: number; - order_id?: number; - user_id?: number; - asset?: string; - uniq_time?: string; - bonus_id?: number; - product_id?: number; - bonus_asset?: string; - total_principal?: string; - amount?: string; - asset_price?: string; - status?: number; - detail?: string; - create_time?: string; - create_at?: number; - lock_up_period?: number; -} -⋮---- -export interface GetEarnFixedTermHistoryResponse { - code?: number; - message?: string; - data?: { - list?: FixedTermHistoryRecord[]; - total?: number; - }; - timestamp?: number; -} - -================ -File: src/types/response/otc.ts -================ -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ -⋮---- -export interface OTCActionResp { - code: number; - message: string; - timestamp: number; -} -⋮---- -export interface CreateOTCQuoteResp { - code: number; - message: string; - data: { - type: string; // BUY (on-ramp) or SELL (off-ramp) - pay_coin: string; - get_coin: string; - pay_amount: string; - get_amount: string; - rate: string; - rate_reci: string; // Reciprocal of the exchange rate - promotion_code: string; - side: string; - order_type: string; // FIAT or STABLE - quote_token: string; // Quote token required when placing an order - url?: string; - memo?: string; - has_signature?: string; - validity_period?: string; - ex_rate?: string; - usdc_rate?: string; - is_need_file?: string; - gate_bank_id?: string; - gate_bank_name?: string; - refresh_limit?: number; - refresh_limit_msg?: string; - }; - timestamp: number; -} -⋮---- -type: string; // BUY (on-ramp) or SELL (off-ramp) -⋮---- -rate_reci: string; // Reciprocal of the exchange rate -⋮---- -order_type: string; // FIAT or STABLE -quote_token: string; // Quote token required when placing an order -⋮---- -export type CreateOTCFiatOrderResp = OTCActionResp; -⋮---- -export interface CreateOTCStablecoinOrderResp { - code: number; - message: string; - timestamp: number; -} -⋮---- -export interface OTCBankListItem { - id: string; // Bank ID (required for order placement) - bank_account_name: string; - bank_name: string; - bank_country?: string; - bank_address?: string; - bank_code?: string; - branch_code?: string; - iban?: string; - swift?: string; - remittance_line_number?: string; - agent_bank_name?: string; - agent_bank_swift?: string; - submit_time?: string; - update_time?: string; - status?: string; - documentation_file_type?: string; - memo?: string; - /** 1 = default bank card, 0 = not default */ - is_default?: 0 | 1; - bank_id?: string; - documentation_file_key_url?: string; -} -⋮---- -id: string; // Bank ID (required for order placement) -⋮---- -/** 1 = default bank card, 0 = not default */ -⋮---- -export interface GetOTCBankListResp { - code: number; - message: string; - data: { - lists: OTCBankListItem[]; - }; - timestamp: number; -} -⋮---- -export interface CreateOTCBankResp { - code: number; - message: string; - data: { - bank_id: number; - status: number; - }; - timestamp?: number; -} -⋮---- -export interface OTCBankSupplementChecklistItem { - description: string; - code?: string; - zh?: string; - en?: string; - required?: boolean; -} -⋮---- -export interface GetOTCBankSupplementChecklistResp { - code: number; - message: string; - data: { - user_type: 'personal' | 'enterprise'; - items: OTCBankSupplementChecklistItem[]; - }; - timestamp?: number; -} -⋮---- -export type MarkOTCOrderAsPaidResp = OTCActionResp; -⋮---- -export type CancelOTCOrderResp = OTCActionResp; -⋮---- -export interface OTCFiatOrderListItem { - time: string; // Current time - timestamp: number; // Current timestamp - order_id: string; - trade_no: string; // Trade number - type: string; // Quote direction buy/sell/all - status: string; // Order Status (includes DISBURSED) - db_status: string; - fiat_currency: string; // Fiat type - fiat_currency_info: { - name: string; - icon: string; - }; - fiat_amount: string; // Fiat amount - crypto_currency: string; // Stablecoin - crypto_currency_info: { - name: string; - icon: string; - }; - crypto_amount: string; // Stablecoin amount - rate: string; // Exchange rate - transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) - reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders - gate_bank_account_iban: string; // Bank account - promotion_code: string; // Promotion code -} -⋮---- -time: string; // Current time -timestamp: number; // Current timestamp -⋮---- -trade_no: string; // Trade number -type: string; // Quote direction buy/sell/all -status: string; // Order Status (includes DISBURSED) -⋮---- -fiat_currency: string; // Fiat type -⋮---- -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin -⋮---- -crypto_amount: string; // Stablecoin amount -rate: string; // Exchange rate -transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) -reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders -gate_bank_account_iban: string; // Bank account -promotion_code: string; // Promotion code -⋮---- -export interface GetOTCFiatOrderListResp { - code: number; - message: string; - data: { - pn: number; - ps: number; - total_pn: number; - count: number; - list: OTCFiatOrderListItem[]; - }; -} -⋮---- -export interface OTCStablecoinOrderListItem { - id: number; // Order ID - trade_no: string; // Transaction reference number - pay_coin: string; // Payment currency - pay_amount: string; // Payment amount - get_coin: string; // Received currency - get_amount: string; // Received amount - rate: string; // Exchange rate - rate_reci: string; // Reciprocal of the exchange rate - status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed - create_timest: number; // Timestamp - create_time: string; // Created time - pay_icon?: string; - get_icon?: string; -} -⋮---- -id: number; // Order ID -trade_no: string; // Transaction reference number -pay_coin: string; // Payment currency -pay_amount: string; // Payment amount -get_coin: string; // Received currency -get_amount: string; // Received amount -rate: string; // Exchange rate -rate_reci: string; // Reciprocal of the exchange rate -status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed -create_timest: number; // Timestamp -create_time: string; // Created time -⋮---- -export interface GetOTCStablecoinOrderListResp { - code: number; - message: string; - data: { - total: number; - page_size: number; - page_number: number; - total_page: number; - list: OTCStablecoinOrderListItem[]; - }; -} -⋮---- -export interface OTCFiatOrderDetail { - order_id: string; // Order ID - uid: string; // User ID - type: string; // Order Type - fiat_currency: string; // Fiat type - fiat_amount: string; // Fiat amount - crypto_currency: string; // Stablecoin - crypto_amount: string; // Stablecoin amount - rate: string; // Exchange rate - transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) - reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders - status: string; // Status - db_status: string; - create_time: string; // Created time - memo: string; // Cancellation or rejection reason - side: string; // Quote direction - promotion_code: string; // Promotion code - trade_no: string; // Trade number -} -⋮---- -order_id: string; // Order ID -uid: string; // User ID -type: string; // Order Type -fiat_currency: string; // Fiat type -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin -crypto_amount: string; // Stablecoin amount -rate: string; // Exchange rate -transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) -reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders -status: string; // Status -⋮---- -create_time: string; // Created time -memo: string; // Cancellation or rejection reason -side: string; // Quote direction -promotion_code: string; // Promotion code -trade_no: string; // Trade number -⋮---- -export interface GetOTCFiatOrderDetailResp { - message: string; - code: number; - data: OTCFiatOrderDetail; -} -⋮---- -export interface CreateOTCUploadPreUploadFields { - key?: string; - content_type?: string; - x_amz_credential?: string; - x_amz_algorithm?: string; - x_amz_date?: string; - policy?: string; - x_amz_signature?: string; -} -⋮---- -export interface CreateOTCUploadPreUploadData { - file_key?: string; - url?: string; - fields?: CreateOTCUploadPreUploadFields; - expires_in?: number; -} -⋮---- -export interface CreateOTCUploadPreUploadResp { - code?: number; - message?: string; - timestamp?: number; - data?: CreateOTCUploadPreUploadData; -} - -================ -File: src/types/response/tradfi.ts -================ -/** TradFi API response types */ -⋮---- -export interface TradFiApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; -} -⋮---- -export interface TradFiListData { - list?: T[]; - total?: number; - total_page?: number; -} -⋮---- -export interface TradFiMT5Account { - mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility - leverage?: number; - stop_out_level?: string; - status?: number; -} -⋮---- -mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility -⋮---- -export interface TradFiCategoryItem { - category_id?: number; - is_favorite?: boolean; - category_name?: string; -} -⋮---- -export interface TradFiSymbolItem { - symbol?: string; - symbol_desc?: string; - category_id?: number; - status?: string; - trade_mode?: string; - icon_link?: string; - close_time?: number; - open_time?: number; - next_open_time?: number; - settlement_currency?: string; - settlement_currency_symbol?: string; - price_precision?: number; -} -⋮---- -export interface TradFiSymbolDetailItem { - symbol?: string; - symbol_desc?: string; - category_name?: string; - contract_volume?: string; - settlement_currency?: string; - max_order_volume?: string; - min_order_volume?: string; - leverage?: string; - price_precision?: number; - price_sl_level?: string; - swap_cost_type?: string; - buy_swap_cost_rate?: string; - sell_swap_cost_rate?: string; - swap_cost_3day?: string; - trade_timezone?: string; - trade_mode?: string; - icon_link?: string; - [key: string]: unknown; -} -⋮---- -export interface TradFiKlineItem { - o?: string; - c?: string; - h?: string; - l?: string; - t?: number; -} -⋮---- -export interface TradFiTicker { - highest_price?: string; - lowest_price?: string; - price_change?: string; - price_change_amount?: string; - today_open_price?: string; - last_today_close_price?: string; - last_price?: string; - bid_price?: string; - ask_price?: string; - favorite?: boolean; - status?: string; - close_time?: number; - open_time?: number; - next_open_time?: number; - trade_mode?: string; - category_name?: string; -} -⋮---- -export interface TradFiCreateUserResult { - status?: number; - leverage?: number; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -} -⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -⋮---- -export interface TradFiAssets { - equity?: string; - margin_level?: string; - balance?: string; - margin?: string; - margin_free?: string; - unrealized_pnl?: string; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -} -⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -⋮---- -export interface TradFiTransactionRecord { - asset?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - time?: number; -} -⋮---- -export interface TradFiTransactionListData { - total?: number; - total_page?: number; - list?: TradFiTransactionRecord[]; -} -⋮---- -export interface TradFiCreateOrderResult { - id?: string; -} -⋮---- -export interface TradFiOrderItem { - order_id?: number; - symbol?: string; - symbol_desc?: string; - price_type?: string; - state?: number; - state_desc?: string; - finished?: number; - side?: number; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; - time_setup?: number; -} -⋮---- -export interface TradFiOrderListData { - list?: TradFiOrderItem[]; - timestamp?: number; -} -⋮---- -export interface TradFiModifyOrderResult { - order_id?: number; - symbol?: string; - state?: string; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; -} -⋮---- -export interface TradFiOrderHistoryItem { - order_id?: number; - symbol?: string; - symbol_desc?: string; - price_type?: string; - order_opt_type?: number; - state?: number; - state_desc?: string; - side?: number; - volume?: string; - fill_volume?: string; - close_pnl?: string; - price?: string; - trigger_price?: string; - price_tp?: string; - price_sl?: string; - time_setup?: number; - time_done?: number; -} -⋮---- -export interface TradFiPositionItem { - position_id?: number; - symbol?: string; - symbol_desc?: string; - margin?: string; - unrealized_pnl?: string; - unrealized_pnl_rate?: string; - volume?: string; - price_open?: string; - position_dir?: string; - price_tp?: string; - price_sl?: string; - counterparty_price?: string; - time_create?: number; -} -⋮---- -export interface TradFiPositionListData { - list?: TradFiPositionItem[]; - timestamp?: number; -} -⋮---- -export interface TradFiPositionHistoryItem { - position_id?: number; - symbol?: string; - realized_pnl?: string; - realized_pnl_rate?: string; - volume?: string; - volume_closed?: string; - price_open?: string; - position_dir?: string; - price_tp?: string; - price_sl?: string; - counterparty_price?: string; - close_price?: string; - time_create?: string; - time_close?: string; - position_status?: string; - close_detail?: Record | null; - realized_pnl_detail?: { - closed_pnl?: string; - swap?: string; - fee?: string; - }; -} -⋮---- -/** GET /tradfi/orders/log/{log_id} — v4.106.94 */ -export interface TradFiOrderLog { - order_id?: number; - log_id?: number; - symbol?: string; - price_type?: 'market' | 'trigger'; - state?: number; - side?: number; - volume?: string; - price?: string; - [key: string]: unknown; -} -⋮---- -export interface TradFiSymbolCommissionItem { - category_code?: string; - symbol?: string; - fee_per_lot?: string; -} - -================ -File: src/index.ts -================ -// Request Types -⋮---- -// Response Types -⋮---- -// Websockets Types -⋮---- -// Shared Types - -================ -File: src/types/request/futures.ts -================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ -⋮---- -export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; -⋮---- -export interface GetFuturesOrderBookReq { - settle: FuturesSettle; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; -} -⋮---- -export interface GetFuturesTradesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; -} -⋮---- -export interface GetFuturesCandlesReq { - settle: FuturesSettle; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; -} -⋮---- -export interface GetFuturesStatsReq { - settle: FuturesSettle; - contract: string; - from?: number; - interval?: string; - limit?: number; -} -⋮---- -export interface GetFundingRatesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - from?: number; - to?: number; -} -⋮---- -export interface BatchFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd1'; - contracts: string[]; -} -⋮---- -export interface GetLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; -} -⋮---- -export interface GetRiskLimitTiersReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; -} -⋮---- -export interface GetRiskLimitTableReq { - settle: FuturesSettle; - table_id: string; -} -⋮---- -export interface GetFuturesAccountBookReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; -} -⋮---- -export interface GetFuturesADLRiskStatesReq { - settle: 'btc' | 'usdt' | 'usd1'; -} -⋮---- -export interface GetFuturesPositionsReq { - settle: FuturesSettle; - holding?: boolean; - limit?: number; // deprecated, use positions_limit instead - positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 - offset?: number; - position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support - hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter -} -⋮---- -limit?: number; // deprecated, use positions_limit instead -positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 -⋮---- -position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support -hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter -⋮---- -export interface UpdateDualModePositionMarginReq { - settle: FuturesSettle; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; -} -⋮---- -export interface UpdateDualModePositionLeverageReq { - settle: FuturesSettle; - contract: string; - leverage: string; - cross_leverage_limit?: string; -} -⋮---- -export interface SubmitFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - tpsl_tp_trigger_price?: string; - tpsl_sl_trigger_price?: string; - pos_margin_mode?: 'isolated' | 'cross'; -} -⋮---- -export interface GetFuturesOrdersReq { - settle: FuturesSettle; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; -} -⋮---- -export interface DeleteAllFuturesOrdersReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - side?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} -⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface UpdateFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - order_id: string; - size?: number; - price?: string; - amend_text?: string; -} -⋮---- -export interface GetFuturesTradingHistoryReq { - settle: FuturesSettle; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; -} -⋮---- -export interface GetFuturesTradingHistoryByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - role?: 'maker' | 'taker'; -} -⋮---- -export interface GetFuturesPositionHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; -} -⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - at?: number; -} -⋮---- -export interface SubmitFuturesTriggeredOrderReq { - initial: { - contract: string; - size?: number; - /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ - amount?: string; - price: string; // Required: Order price. Set to 0 to use market price - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price: string; // Required: Price value for price trigger - rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) - expiration?: number; - }; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - settle: FuturesSettle; -} -⋮---- -/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ -⋮---- -price: string; // Required: Order price. Set to 0 to use market price -⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) -⋮---- -export interface GetFuturesAutoOrdersReq { - settle: FuturesSettle; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} -⋮---- -/** - * Modify contract order parameters - */ -export interface BatchAmendOrderReq { - order_id?: number; // Order id, order_id and text must contain at least one - text?: string; // User-defined order text, at least one of order_id and text must be passed - size?: number; // The new order size, including the executed order size - price?: string; // New order price - amend_text?: string; // Custom info during amending order -} -⋮---- -order_id?: number; // Order id, order_id and text must contain at least one -text?: string; // User-defined order text, at least one of order_id and text must be passed -size?: number; // The new order size, including the executed order size -price?: string; // New order price -amend_text?: string; // Custom info during amending order -⋮---- -// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request -export interface GetFuturesPositionCloseHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} -⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: FuturesSettle; - limit?: number; -} -⋮---- -export interface UpdateFuturesPriceTriggeredOrderReq { - settle: FuturesSettle; - order_id: number | string; - contract?: string; - size?: number; - /** Same semantics as `size` (decimal contract size) */ - amount?: string; - price?: string; - /** When fully closing in single-position mode, set true */ - close?: boolean; - trigger_price?: string; - price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price - auto_size?: string; // Not required in single position mode -} -⋮---- -/** Same semantics as `size` (decimal contract size) */ -⋮---- -/** When fully closing in single-position mode, set true */ -⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode -⋮---- -/** GET /futures/{settle}/get_leverage/{contract} — v4.106.43: pos_margin_mode and dual_side required */ -export interface GetFuturesContractLeverageReq { - settle: FuturesSettle; - contract: string; - pos_margin_mode: 'isolated' | 'cross'; - dual_side: 'dual_long' | 'dual_short'; -} -⋮---- -/** Trail order (autoorder/v1/trail) request types */ -export interface CreateTrailOrderReq { - settle: 'btc' | 'usdt'; - contract: string; - amount: string; - activation_price?: string; - is_gte?: boolean; - price_type?: 1 | 2 | 3; - price_offset?: string; - reduce_only?: boolean; - position_related?: boolean; - text?: string; - pos_margin_mode?: string; - position_mode?: string; -} -⋮---- -export interface TerminateTrailOrderReq { - settle: 'btc' | 'usdt'; - id?: number; - text?: string; -} -⋮---- -export interface BatchTerminateTrailOrdersReq { - settle: 'btc' | 'usdt'; - contract?: string; - related_position?: 1 | 2; -} -⋮---- -export interface GetTrailOrderListReq { - settle: 'btc' | 'usdt'; - contract?: string; - is_finished?: boolean; - start_at?: number; - end_at?: number; - page_num?: number; - page_size?: number; - sort_by?: 1 | 2; - hide_cancel?: boolean; - related_position?: 1 | 2; - sort_by_trigger?: boolean; - reduce_only?: 1 | 2; - side?: 1 | 2; -} -⋮---- -export interface GetTrailOrderDetailReq { - settle: 'btc' | 'usdt'; - id: number; -} -⋮---- -export interface UpdateTrailOrderReq { - settle: 'btc' | 'usdt'; - id: number; - amount?: string; - activation_price?: string; - is_gte_str?: string; - price_type?: 0 | 1 | 2 | 3; - price_offset?: string; -} -⋮---- -export interface GetTrailOrderChangeLogReq { - settle: 'btc' | 'usdt'; - id: number; - page_num?: number; - page_size?: number; -} -⋮---- -/** Chase limit order (autoorder/v1/chase) request types */ -export interface CreateChaseOrderReq { - settle: FuturesSettle; - contract: string; - amount: string; - price_limit: string; - offset_limit?: string; - reduce_only?: boolean; - text?: string; - is_dual_mode?: boolean; - price_type?: number; - price_gap_type?: number; - price_gap_value?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; - position_mode?: string; -} -⋮---- -export interface StopChaseOrderReq { - settle: FuturesSettle; - id?: string; - text?: string; -} -⋮---- -export interface StopAllChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; -} -⋮---- -export interface GetChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - is_finished?: boolean; - start_at?: number; - end_at?: number; - page_num?: number; - page_size?: number; - /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ - sort_by: 1 | 2; - hide_cancel?: boolean; - reduce_only?: 0 | 1 | 2; - side?: 0 | 1 | 2; -} -⋮---- -/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ -⋮---- -export interface GetChaseOrderDetailReq { - settle: FuturesSettle; - id: string; -} - -================ -File: src/types/response/spot.ts -================ -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ -⋮---- -/** Limit-order take-profit / stop-loss on order responses (not re-exported; use request types for submits) */ -interface SpotOrderTPSL { - trigger_price: string; - order_price: string; -} -⋮---- -/** `{}` cancels TP/SL; `null` leaves unchanged */ -type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; -⋮---- -export interface SpotCurrencyChain { - name: string; - addr?: string; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; -} -⋮---- -export interface SpotCurrency { - currency: string; - name: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - chain: string; - chains: SpotCurrencyChain[]; - /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ - category?: string[]; -} -⋮---- -/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ -⋮---- -export interface SpotTicker { - currency_pair: string; - last: string; - lowest_ask: string; - lowest_size: string; - highest_bid: string; - highest_size: string; - change_percentage: string; - change_utc0: string; - change_utc8: string; - base_volume: string; - quote_volume: string; - high_24h: string; - low_24h: string; - etf_net_value: string; - etf_pre_net_value: string | null; - etf_pre_timestamp: number | null; - etf_leverage: string | null; -} -⋮---- -export interface SpotOrderBook { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; -} -⋮---- -export interface SpotTrade { - id: string; - create_time: string; - create_time_ms: string; - currency_pair: string; - side: 'buy' | 'sell'; - role: 'taker' | 'maker'; - amount: string; - price: string; - order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; - trade_quote?: string; -} -⋮---- -export type SpotCandle = [ - string, // Unix timestamp with second precision - string, // Trading volume in quote currency - string, // Closing price - string, // Highest price - string, // Lowest price - string, // Opening price - string, // Trading volume in base currency - boolean, // Whether the window is closed -]; -⋮---- -string, // Unix timestamp with second precision -string, // Trading volume in quote currency -string, // Closing price -string, // Highest price -string, // Lowest price -string, // Opening price -string, // Trading volume in base currency -boolean, // Whether the window is closed -⋮---- -export interface SpotFeeRates { - user_id: number; - taker_fee: string; // For spot trading - maker_fee: string; // For spot trading - gt_discount: boolean; - gt_taker_fee: string; - gt_maker_fee: string; - loan_fee: string; - point_type: string; - currency_pair: string; - debit_fee: number; -} -⋮---- -taker_fee: string; // For spot trading -maker_fee: string; // For spot trading -⋮---- -export interface SpotAccount { - currency: string; - available: string; - locked: string; - update_id: number; - refresh_time: number; - last_update_time?: number; - trading_fee_rate?: string; -} -⋮---- -export interface SpotAccountBook { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - code: string; - text: string; -} -⋮---- -export interface SubmitSpotBatchOrdersResp { - order_id: string; - amend_text: string; - text: string; - succeeded: boolean; - label: string; - message: string; - id: string; - create_time: string; - update_time: string; - create_time_ms: number; - update_time_ms: number; - status: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type: 'limit' | 'market'; - account: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; - price: string; - time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg: string; - auto_repay: boolean; - left: string; - filled_amount: string; - fill_price: string; - filled_total: string; - avg_deal_price: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - gt_discount: boolean; - rebated_fee: string; - rebated_fee_currency: string; - stp_id: number; - stp_act: 'cn' | 'co' | 'cb' | '-'; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; -} -⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ -⋮---- -export interface SpotOrder { - id?: string; - text?: string; - amend_text?: string; - create_time?: string; - update_time?: string; - create_time_ms?: number; - update_time_ms?: number; - status?: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; - price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - left?: string; - filled_amount?: string; - fill_price?: string; - filled_total?: string; - avg_deal_price?: string; - fee?: string; - fee_currency?: string; - point_fee?: string; - gt_fee?: string; - gt_maker_fee?: string; - gt_taker_fee?: string; - gt_discount?: boolean; - rebated_fee?: string; - rebated_fee_currency?: string; - stp_id?: number; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; - trade_quote?: string; -} -⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ -⋮---- -export interface SpotInsuranceHistory { - currency: string; - balance: string; - time: number; -} -⋮---- -export interface SpotPriceTriggeredOrder { - trigger: { - price: string; - rule: '>=' | '<='; - expiration?: number; - }; - put: { - type?: 'limit' | 'market'; - side: 'buy' | 'sell'; - price: string; - amount: string; - account: 'normal' | 'margin' | 'cross_margin'; - time_in_force: 'gtc' | 'ioc'; - text?: string; - }; - id?: number; - user?: number; - market: string; - ctime?: number; - ftime?: number; - fired_order_id?: number; - status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; - reason?: string; -} -⋮---- -export interface GetSpotOpenOrdersResp { - currency_pair: string; - total: number; - orders: SpotOrder[]; -} -⋮---- -export interface DeleteSpotBatchOrdersResp { - currency_pair: string; - id: string; - succeeded: boolean; - label: string; - message: string; - account: string; - text: string; -} -⋮---- -export interface SpotHistoricTradeRecord { - id: string; - create_time: string; - create_time_ms: string; - currency_pair: string; - side: 'buy' | 'sell'; - role: 'taker' | 'maker'; - amount: string; - price: string; - order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; - deal?: string; // v4.105.29: Total Executed Value - trade_quote?: string; -} -⋮---- -deal?: string; // v4.105.29: Total Executed Value -⋮---- -export type SpotPovOrderStatus = - | 'CREATED' - | 'CANCELING' - | 'RUNNING' - | 'COMPLETED' - | 'EXPIRED' - | 'TERMINATED'; -⋮---- -export interface SpotPovOrder { - id?: string; - currency_pair?: string; - side?: string; - amount?: string; - participation_rate?: number; - ttl?: string; - limit_price?: string; - trigger_price?: string; - status?: SpotPovOrderStatus | string; - terminated_as?: string; - start_time_ms?: number; - end_time_ms?: number; - expire_time_ms?: number; - create_time_ms?: number; - update_time_ms?: number; - text?: string; -} - -================ -File: src/types/response/unified.ts -================ -export interface UnifiedAccountInfo { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin - user_id: number; - refresh_time: number; - locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin - balances: { - [key: string]: { - available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode - freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode - borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) - equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode - total_freeze: string; // Total frozen (deprecated, to be removed) - total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes - funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin - funding_version: string; // Funding version - cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode - iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode - im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled - balance_version?: number; // Balance version number (int64) - }; - }; - total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) - borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode - total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode - unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode - unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode - leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) - spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode - options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode - spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled - margin_mode?: string; - total_balance?: string; - cross_leverage?: string; - portfolio_margin?: string; - risk_level?: string; - is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all - borrow_amount?: string; - cross_margin_leverage?: string; - use_funding?: boolean; // Whether Earn funds are used as margin -} -⋮---- -mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin -⋮---- -locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin -⋮---- -available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode -freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode -borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) -equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode -total_freeze: string; // Total frozen (deprecated, to be removed) -total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes -funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin -funding_version: string; // Funding version -cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode -iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode -im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled -balance_version?: number; // Balance version number (int64) -⋮---- -total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) -borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode -total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode -unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode -unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode -leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) -spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode -options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode -spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled -⋮---- -is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all -⋮---- -use_funding?: boolean; // Whether Earn funds are used as margin -⋮---- -export interface UnifiedLoan { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; -} -⋮---- -export interface UnifiedLoanRecord { - id: number; - type: 'borrow' | 'repay'; - repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; - currency_pair: string; - currency: string; - amount: string; - create_time: number; - borrow_type: string; -} -export interface UnifiedInterestRecord { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; -} -⋮---- -export interface UnifiedRiskUnitDetails { - user_id: number; - spot_hedge: boolean; - risk_units: { - symbol: string; - spot_in_use: string; - maintain_margin: string; - initial_margin: string; - delta: string; - gamma: string; - theta: string; - vega: string; - }[]; -} -⋮---- -export interface UnifiedCurrencyDiscountTiers { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - leverage: string; - }[]; -} -⋮---- -export interface UserCurrencyLeverageConfig { - current_leverage: string; - min_leverage: string; - max_leverage: string; - debit: string; - available_margin: string; - borrowable: string; - except_leverage_borrowable: string; -} -⋮---- -export interface UnifiedLoanCurrency { - name: string; - prec: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - loan_status: string; -} -⋮---- -export interface UnifiedHistoryLendingRate { - currency: string; - tier: string; - tier_up_rate: string; - rates: { - time: number; - rate: string; - }[]; -} -⋮---- -export interface MarginTier { - tier: string; - margin_rate: string; - lower_limit: string; - upper_limit: string; -} -⋮---- -export interface PortfolioMarginCalculation { - maintain_margin_total: string; - initial_margin_total: string; - calculate_time: number; - risk_unit: { - symbol: string; - spot_in_use: string; - maintain_margin: string; - initial_margin: string; - margin_result: { - type: - | 'original_position' - | 'long_delta_original_position' - | 'short_delta_original_position'; - profit_loss_ranges: { - price_percentage: string; - implied_volatility_percentage: string; - profit_loss: string; - }[]; - max_loss: { - price_percentage: string; - implied_volatility_percentage: string; - profit_loss: string; - }; - mr1: string; - mr2: string; - mr3: string; - mr4: string; - delta: string; - gamma: string; - theta: string; - vega: string; - }[]; - }[]; -} -⋮---- -export interface UnifiedCollateralCurrenciesResp { - is_success: boolean; -} -⋮---- -export interface UnifiedQuickRepayDebtItem { - currency?: string; - debt_amount?: string; - estimated_usd?: string; - borrowed?: string; - neg_balance?: string; -} -⋮---- -export interface UnifiedQuickRepayAvailableItem { - currency?: string; - available?: string; - estimated_usd?: string; -} -⋮---- -export interface QuickEstimatedRepayment { - debt_currencies?: UnifiedQuickRepayDebtItem[]; - available_currencies?: UnifiedQuickRepayAvailableItem[]; -} -⋮---- -export interface QuickRepayRepaidInfo { - currency: string; - repaid: string; - left: string; -} -⋮---- -export interface QuickRepayUsedInfo { - currency: string; - used: string; -} -⋮---- -export interface QuickRepaymentResp { - order_id: string; - repaid_infos: QuickRepayRepaidInfo[]; - used_infos: QuickRepayUsedInfo[]; -} -⋮---- -/** GET/POST /unified/delta_neutral — v4.106.97 */ -export interface DeltaNeutralEnabled { - enabled: boolean; -} -⋮---- -/** POST /unified/leverage/user_setting failed currency entry */ -export interface LeverageFailedCurrency { - currency: string; - reason: string; -} - -================ -File: src/lib/BaseRestClient.ts -================ -import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; -// NOTE: https.Agent is Node.js-only and not available in browser environments -// Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings -import https from 'https'; -⋮---- -import { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; -⋮---- -/** - * Used to switch how authentication/requests work under the hood - */ -⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; -⋮---- -interface SignedRequest { - originalParams: T; - paramsWithSign?: T & { sign: string }; - serializedParams: string; - sign: string; - queryParamsWithSign: string; - timestamp: number; - recvWindow: number; -} -⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; -} -⋮---- -type SignMethod = 'gateV4'; -⋮---- -/** - * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. - * This type anticipates these are possible in any combination. - * - * The request builder will automatically handle where parameters should go. - */ -type ParamsInQueryBodyOrHeader = { - query?: object; - body?: object; - headers?: object; - /** multipart/form-data body; mutually exclusive with `body` */ - multipart?: FormData; -}; -⋮---- -/** multipart/form-data body; mutually exclusive with `body` */ -⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses - */ -⋮---- -// request: { -// url: response.config.url, -// method: response.config.method, -// data: response.config.data, -// headers: response.config.headers, -// }, -⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. - */ -function deleteUndefinedValues(params?: any): void -⋮---- -export abstract class BaseRestClient -⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; -⋮---- -/** - * Create an instance of the REST client. Pass API credentials in the object in the first parameter. - * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity - * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios - */ -constructor( - restClientOptions: RestClientOptions = {}, - networkOptions: AxiosRequestConfig = {}, -) -⋮---- -/** Throw errors if any request params are empty */ -⋮---- -/** in ms == 5 minutes by default */ -⋮---- -/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ -⋮---- -// If enabled, configure a https agent with keepAlive enabled -// NOTE: This is Node.js-only functionality. In browser environments, this code is skipped -// as the 'https' module is excluded via webpack fallback configuration. -// Browser connection pooling is handled automatically by the browser itself. -⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely -⋮---- -// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" -// parameter to define a custom httpsAgent with the desired properties -⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used -⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set -⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number -⋮---- -protected get(endpoint: string, params?: object) -⋮---- -// GET only supports params in the query string -⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) -⋮---- -protected getPrivate(endpoint: string, params?: object) -⋮---- -// GET only supports params in the query string -⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) -⋮---- -/** POST private endpoint with multipart/form-data (empty body hash for signing) */ -protected postPrivateMultipart( - endpoint: string, - formData: FormData, - query?: object, -) -⋮---- -protected deletePrivate( - endpoint: string, - params?: ParamsInQueryBodyOrHeader, -) -⋮---- -protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) -⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) -⋮---- -/** - * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. - */ -private async _call( - method: Method, - endpoint: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, -): Promise -⋮---- -// Sanity check to make sure it's only ever prefixed by one forward slash -⋮---- -// Build a request and handle signature process -⋮---- -// Dispatch request -⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format -⋮---- -// Throw API rejections by parsing the response code from the body -⋮---- -/** - * @private generic handler to parse request exceptions - */ -parseException(e: any, request: AxiosRequestConfig): unknown -⋮---- -// Something happened in setting up the request that triggered an error -⋮---- -// request made but no response received -⋮---- -// The request was made and the server responded with a status code -// that falls out of the range of 2xx -⋮---- -// console.error('err: ', response?.data); -⋮---- -// Prevent credentials from leaking into error messages -⋮---- -/** - * @private sign request and set recv window - */ -private async signRequest< - T extends ParamsInQueryBodyOrHeader | undefined = {}, - >( - data: T, - endpoint: string, - method: Method, - signMethod: SignMethod, -): Promise> -⋮---- -const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds -⋮---- -// recvWindow: this.options.recvWindow, -⋮---- -// It's possible to override the recv window on a per rquest level -⋮---- -// console.log('sign params: ', { -// requestBodyToHash, -// paramsStr: toSign, -// url: this.baseUrl, -// urlPath: this.baseUrlPath, -// }); -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise -⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: true, - ): Promise>; -⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: false | undefined, - ): Promise>; -⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: boolean, -) -⋮---- -/** Returns an axios request object. Handles signing process automatically if this is a private API call */ -private async buildRequest( - method: Method, - endpoint: string, - url: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, -): Promise - -================ -File: src/types/response/futures.ts -================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ -⋮---- -export interface FuturesOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} -⋮---- -export interface FuturesTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated -} -⋮---- -is_internal?: boolean; // Deprecated -⋮---- -export interface FuturesCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} -⋮---- -export interface PremiumIndexKLine { - t: number; - c: string; - h: string; - l: string; - o: string; -} -⋮---- -export interface FuturesTicker { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; // Deprecated - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; - lowest_size: string; - highest_size: string; -} -⋮---- -quanto_base_rate?: string; // Deprecated -⋮---- -export interface BatchFundingRatesResponse { - contract?: string; - data?: { t: number; r: string }[]; -} -⋮---- -export interface FuturesStats { - time: number; - lsr_taker: number; - lsr_account: number; - long_liq_size: number; - long_liq_amount: number; - long_liq_usd: number; - long_liq_usd_new?: number; - short_liq_size: number; - short_liq_amount: number; - short_liq_usd: number; - short_liq_usd_new?: number; - open_interest: number; - open_interest_usd: number; - top_lsr_account: number; - top_lsr_size: number; - top_long_size?: number; - top_short_size?: number; - long_taker_size?: number; - short_taker_size?: number; - top_long_account?: number; - top_short_account?: number; - long_users?: number; - short_users?: number; -} -⋮---- -export interface IndexConstituents { - index: string; - constituents: { - exchange: string; - symbols: string[]; - }[]; -} -⋮---- -export interface LiquidationHistoryRecord { - time: number; - contract: string; - size: number; - order_size: number; - order_price: string; - fill_price: string; - left: number; -} -⋮---- -export interface RiskLimitTier { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; // First-tier maintenance margin rate requirement - leverage_max: string; - contract: string; -} -⋮---- -maintenance_rate: string; // First-tier maintenance margin rate requirement -⋮---- -export interface FuturesAccount { - total: string; // Balance, only applicable to classic contract account - unrealised_pnl: string; - position_margin?: string; // Deprecated - order_margin: string; // Initial margin for all pending orders - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic?: boolean; // Deprecated - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - cross_margin_balance: string; - cross_mmr: string; - cross_imr: string; - isolated_position_margin: string; - enable_new_dual_mode?: boolean; // Deprecated - margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - enable_tiered_mm: boolean; - funding_balance?: string; -} -⋮---- -total: string; // Balance, only applicable to classic contract account -⋮---- -position_margin?: string; // Deprecated -order_margin: string; // Initial margin for all pending orders -⋮---- -position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) -⋮---- -enable_evolved_classic?: boolean; // Deprecated -⋮---- -enable_new_dual_mode?: boolean; // Deprecated -margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode -⋮---- -export interface FuturesAccountBookRecord { - time: number; - change: string; - balance: string; - type: string; - text: string; - contract?: string; - trade_id: string; - id: string; -} -⋮---- -export interface FuturesOrder { - id?: number; - user?: number; - create_time?: number; - finish_time?: number; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as?: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'poc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed' - | 'stp'; - status?: 'open' | 'finished'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - is_close?: boolean; - reduce_only?: boolean; - is_reduce_only?: boolean; - is_liq?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - left?: number; - fill_price?: string; - text?: string; - tkfr?: string; - mkfr?: string; - refu?: number; - auto_size?: 'close_long' | 'close_short'; - stp_id?: number; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - amend_text?: string; - biz_info?: string; - /** Read-only; order notional in settle currency (API response only; omit from order requests). */ - order_value?: string; - /** Read-only; traded value (API response only; omit from order requests). */ - trade_value?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - tpsl_tp_trigger_price?: string; - tpsl_sl_trigger_price?: string; - tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg - tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg - pos_margin_mode?: string; -} -⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ -⋮---- -/** Read-only; order notional in settle currency (API response only; omit from order requests). */ -⋮---- -/** Read-only; traded value (API response only; omit from order requests). */ -⋮---- -tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg -tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg -⋮---- -/** Item shape for `GET /futures/{settle}/orders_timerange` (differs from {@link FuturesOrder} in field types). */ -export interface FuturesOrderTimerange { - id?: number; - user?: number; - create_time?: number; - update_time?: string; - finish_time?: string; - contract: string; - size: string; - iceberg?: string; - is_close?: boolean; - is_reduce_only?: boolean; - is_liq?: boolean; - left?: string; - fill_price?: string; - tkfr?: string; - mkfr?: string; - refu?: number; - amend_text?: string; - pid?: number; - market_order_slip_ratio?: string; - pos_margin_mode?: string; -} -⋮---- -export interface FuturesPosition { - user?: number; - contract?: string; - size?: number; - leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode - risk_limit?: string; - leverage_max?: string; // Max leverage based on current position size - maintenance_rate?: string; // Tiered maintenance margin rate calculation - value?: string; - margin?: string; - entry_price?: string; - liq_price?: string; // Estimated liquidation price for reference only - liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management - mark_price?: string; - initial_margin?: string; // Expanded scope description - maintenance_margin?: string; // Expanded scope description - unrealised_pnl?: string; - realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees - pnl_pnl?: string; // Settlement P&L - pnl_fund?: string; // Funding fee P&L - pnl_fee?: string; // Total trading fees - history_pnl?: string; // All historical settlement P&L - last_close_pnl?: string; - realised_point?: string; - history_point?: string; - adl_ranking?: number; - pending_orders?: number; - close_order?: { - id?: number; - price?: string; - is_liq?: boolean; - } | null; - mode?: 'single' | 'dual_long' | 'dual_short'; - cross_leverage_limit?: string; // Simplified description - update_time?: number; - update_id?: number; - open_time?: number; - settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support - isolated_margin?: string; // v4.104.6: Add isolated_margin field - pid?: number; // v4.106.0: Sub-position ID - hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status - hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy - unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy -} -⋮---- -leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode -⋮---- -leverage_max?: string; // Max leverage based on current position size -maintenance_rate?: string; // Tiered maintenance margin rate calculation -⋮---- -liq_price?: string; // Estimated liquidation price for reference only -liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management -⋮---- -initial_margin?: string; // Expanded scope description -maintenance_margin?: string; // Expanded scope description -⋮---- -realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees -pnl_pnl?: string; // Settlement P&L -pnl_fund?: string; // Funding fee P&L -pnl_fee?: string; // Total trading fees -history_pnl?: string; // All historical settlement P&L -⋮---- -cross_leverage_limit?: string; // Simplified description -⋮---- -settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support -isolated_margin?: string; // v4.104.6: Add isolated_margin field -pid?: number; // v4.106.0: Sub-position ID -hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status -hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy -unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy -⋮---- -export interface FuturesTradingHistoryRecord { - id: number; - create_time: number; - contract: string; - order_id: string; - size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; - close_size: number; -} -⋮---- -export interface FuturesPositionHistoryRecord { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; - text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; - accum_size: string; -} -⋮---- -export interface FuturesLiquidationHistoryRecord { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - liq_price: string; - mark_price: string; - order_id: number; - order_price: string; - fill_price: string; - left: number; -} -export interface FuturesAutoDeleveragingHistoryRecord { - time: number; - user: number; - order_id: number; - contract: string; - leverage: string; // Clarified for better understanding of margin modes - cross_leverage_limit: string; // Clarified for better understanding of margin modes - entry_price: string; - fill_price: string; - trade_size: number; - position_size: number; -} -⋮---- -leverage: string; // Clarified for better understanding of margin modes -cross_leverage_limit: string; // Clarified for better understanding of margin modes -⋮---- -export interface DeleteFuturesBatchOrdersResp { - user_id: number; - id: string; - succeeded: boolean; - message: string; -} -⋮---- -export interface FuturesContract { - name?: string; - /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ - contract_type?: string; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; // First-tier maintenance margin rate requirement - mark_type?: 'internal' | 'index'; // Deprecated - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; // Minimum unit of mark price - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - funding_rate?: string; - funding_rate_indicative?: string; - funding_interval?: number; - funding_next_apply?: number; - funding_offset?: number; - /** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ - interest_rate?: string; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: string | number; // API returns string e.g. "1" - order_size_max?: string | number; // API returns string e.g. "1000000" - orderbook_id?: number; - trade_id?: number; - trade_size?: string | number; // API returns string - position_size?: string | number; // API returns string - short_users?: number; - long_users?: number; - funding_impact_value?: string; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; - enable_bonus?: boolean; - enable_credit?: boolean; - /** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ - enable_decimal?: boolean; - /** Whether the newly listed contract uses the mark price circuit breaker */ - enable_circuit_breaker?: boolean; - create_time?: number; - launch_time?: number; - delisting_time?: number; - delisted_time?: number; - status?: string; // e.g. "trading" - funding_cap_ratio?: string; // Deprecated - funding_rate_limit?: string; // v4.106.4: Funding rate cap value - market_order_slip_ratio?: string; - market_order_size_max?: string; + +================ +File: docs/GATE_SDK_QUICKSTART_GUIDE.md +================ + + +# Gate API JavaScript Tutorial for Node.js + + + +> [!TIP] +> Read this guide in tutorial format on the Siebly website: [Gate JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/gate/javascript/tutorial) + + + +This tutorial uses [`gateio-api`](https://www.npmjs.com/package/gateio-api), Siebly's Node.js, JavaScript, and TypeScript SDK for Gate.com. It covers public and private REST API calls, Spot and Futures TestNet orders, live WebSocket streams, WebSocket API commands, API hosts, and proxies. + +The SDK handles REST API request signing, private WebSocket authentication, product-specific WebSocket routing, heartbeats, reconnects, resubscriptions, and WebSocket API response matching. Request and response types are included for TypeScript users. + +**Key links** + +- Gate JavaScript SDK by Siebly: [`gateio-api`](https://siebly.io/sdk/gate/javascript) +- npm package: [`gateio-api`](https://www.npmjs.com/package/gateio-api) +- GitHub repository: [`sieblyio/gateio-api`](https://github.com/sieblyio/gateio-api) +- SDK examples: [Gate SDK examples](https://siebly.io/examples/Gate) +- SDK endpoint map: [Gate JavaScript endpoint reference](./endpointFunctionList.md) +- Gate REST API documentation: [Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) +- Gate Spot WebSocket documentation: [Spot WebSocket API](https://www.gate.com/docs/developers/apiv4/ws/) +- Gate Futures WebSocket documentation: [Futures WebSocket API](https://www.gate.com/docs/developers/futures/ws/) +- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) +- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) + +## Why use `gateio-api`? + +The JavaScript SDK handles all the complexities of integrating with Gate's REST APIs & WebSockets, so you can focus on your system without wasting excessive time on plumbing. + +Private Gate REST API requests require a timestamp and HMAC-SHA512 signature. Private WebSocket subscriptions require authentication, and each product family has its own WebSocket connection. A Spot subscription cannot be sent through a USDT perpetual Futures connection. + +`gateio-api` handles those mechanics and gives each job a focused client: + +| Client | Use it for | +| -------------------- | ------------------------------------------------------------ | +| `RestClient` | Public and private REST API calls across Gate product groups | +| `WebsocketClient` | Public and private WebSocket subscriptions | +| `WebsocketAPIClient` | Promise-based Spot and Futures order commands over WebSocket | + +`WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. + +## Install the SDK + +```bash +npm install gateio-api +``` + +The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. + +## Create Gate API keys + +Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. + +Create and manage keys from the [Gate API key page](https://www.gate.com/myaccount/api_key_manage). Start with the least access your application needs: + +- Use a read-only key while building account views and recovery code. +- Enable Spot read-write access only for Spot order workflows. +- Enable perpetual-contract read-write access only for Futures order workflows. +- Add an IP whitelist when your outbound IP is stable. +- Keep live and TestNet credentials separate. +- Allow a few minutes for API key and permission changes to take effect. +- Do not enable withdrawal permission for anything in this tutorial. + +Set these live credential names in your shell, secret manager, or deployment environment: + +- `GATE_API_KEY` +- `GATE_API_SECRET` + +Use separate names for TestNet: + +- `GATE_TESTNET_API_KEY` +- `GATE_TESTNET_API_SECRET` +- `GATE_PLACE_TESTNET_ORDER=true` + +The order examples check `GATE_PLACE_TESTNET_ORDER` before sending an order. Do not log API keys or secrets, and never put them in browser code. + +## Gate products and request vocabulary + +Several short fields determine where a request goes and what its values mean: + +| Field | Example | Meaning | +| --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- | +| `currency_pair` | `BTC_USDT` | A Spot or margin market | +| `account` | `spot` | The account used by a Spot order or query | +| `settle` | `usdt` | The settlement currency for a Futures or Delivery REST API request | +| `contract` | `BTC_USDT` | The exact Futures, Delivery, or Options contract | +| `size` | `1` or `-1` | Futures contract count, not a BTC or USDT amount | +| `text` | `t-my-order-123` | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id) | +| `wsKey` | `WS_KEY_MAP.perpFuturesUSDTV4` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) that selects a product connection | + +For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. + +For USDT perpetual Futures, use `settle: 'usdt'` and a contract such as `BTC_USDT`. The `size` is a number of contracts. In one-way mode, a positive size buys and a negative size sells. The contract's `quanto_multiplier` tells you how much underlying currency one contract represents. + +Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. + + + +## Start building: first calls and streams + +Run each example on its own. Start with public data, then add authenticated account state and live streams. + +### 1. Make public REST API calls + +Public calls need no API key. Gate response bodies are endpoint-specific: server time and order books are objects, tickers are arrays, and candles are tuple arrays. + + + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient(); + +async function main() { + try { + const time = await client.getServerTime(); + console.log('Server time:', time.server_time); + } catch (error) { + console.error('Server time request failed:', error); + } + + try { + const pair = await client.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + console.log('BTC_USDT metadata:', pair); + } catch (error) { + console.error('Currency pair request failed:', error); + } + + try { + const tickers = await client.getSpotTicker({ + currency_pair: 'BTC_USDT', + }); + console.log('BTC_USDT ticker:', tickers[0]); + } catch (error) { + console.error('Ticker request failed:', error); + } + + try { + const orderBook = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + console.log('Best bid:', orderBook.bids[0]); + console.log('Best ask:', orderBook.asks[0]); + } catch (error) { + console.error('Order book request failed:', error); + } + + try { + const candles = await client.getSpotCandles({ + currency_pair: 'BTC_USDT', + interval: '1h', + limit: 10, + }); + console.log('Latest candle:', candles[0]); + } catch (error) { + console.error('Candles request failed:', error); + } } -⋮---- -/** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ -⋮---- -quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" -⋮---- -maintenance_rate?: string; // First-tier maintenance margin rate requirement -mark_type?: 'internal' | 'index'; // Deprecated -⋮---- -mark_price_round?: string; // Minimum unit of mark price -⋮---- -/** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ -⋮---- -order_size_min?: string | number; // API returns string e.g. "1" -order_size_max?: string | number; // API returns string e.g. "1000000" -⋮---- -trade_size?: string | number; // API returns string -position_size?: string | number; // API returns string -⋮---- -/** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ -⋮---- -/** Whether the newly listed contract uses the mark price circuit breaker */ -⋮---- -status?: string; // e.g. "trading" -funding_cap_ratio?: string; // Deprecated -funding_rate_limit?: string; // v4.106.4: Funding rate cap value -⋮---- -/** GET /futures/{settle}/adl_risk_states */ -export interface FuturesADLRiskState { - state: 'normal' | 'warning' | 'adl_risk'; - calculated_at_ms: number; + +main(); +``` + +The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. + +Each Spot candle is a tuple: + +```text +[ + timestamp, + quoteVolume, + close, + high, + low, + open, + baseVolume, + closed +] +``` + +Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. + +### 2. Make private REST API calls + +Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. + + + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +async function main() { + try { + const balances = await client.getSpotAccounts(); + console.log('Spot balances:', balances); + } catch (error) { + console.error('Balance request failed:', error); + } + + try { + const openOrders = await client.getSpotOpenOrders({ + account: 'spot', + }); + console.log('Open Spot orders grouped by pair:', openOrders); + } catch (error) { + console.error('Open-order request failed:', error); + } + + try { + const recentOrders = await client.getSpotOrders({ + currency_pair: 'BTC_USDT', + status: 'finished', + account: 'spot', + limit: 20, + }); + console.log('Recent BTC_USDT orders:', recentOrders); + } catch (error) { + console.error('Order-history request failed:', error); + } + + try { + const trades = await client.getSpotTradingHistory({ + currency_pair: 'BTC_USDT', + account: 'spot', + limit: 20, + }); + console.log('Recent BTC_USDT trades:', trades); + } catch (error) { + console.error('Trade-history request failed:', error); + } } -⋮---- -export interface FuturesADLRiskStates { - settle: string; - states: Record; + +main(); +``` + +`getSpotAccounts()`, `getSpotOrders()`, and `getSpotTradingHistory()` return arrays. `getSpotOpenOrders()` returns an array whose entries group open orders by currency pair. Other private endpoints return objects or different array shapes, so check the [SDK endpoint map](./endpointFunctionList.md) instead of assuming a common format. + +### 3. Subscribe to public WebSocket streams + +Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. + + + +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +const ws = new WebsocketClient(); + +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); + +ws.on('update', (update) => { + console.log('WebSocket update:', update); +}); + +ws.on('reconnect', ({ wsKey }) => { + console.log('Reconnecting:', wsKey); +}); + +ws.on('reconnected', (event) => { + console.log('Reconnected:', event.wsKey); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Spot subscription failed:', error); } -⋮---- -/** GET /futures/{settle}/get_leverage/{contract} — API field name is `Lever` */ -export interface FuturesContractLeverageInfo { - Lever: string; + +try { + ws.subscribe( + { + topic: 'futures.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.perpFuturesUSDTV4, + ); +} catch (error) { + console.error('Futures subscription failed:', error); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` + +Gate sends Spot ticker data as an object in `result`, while a Futures ticker update can contain an array. The SDK adds `wsKey` to each update so one event handler can identify the source connection. + +The main WebSocket events are: + +| Event | Meaning | +| --------------- | ------------------------------------------------------------- | +| `open` | A connection opened for the reported `wsKey` | +| `response` | Subscription, unsubscription, or request response | +| `update` | Market or account data | +| `authenticated` | A private connection authenticated successfully | +| `reconnect` | The connection dropped and a reconnect is starting | +| `reconnected` | The connection is open and cached subscriptions were restored | +| `close` | A connection closed for the reported `wsKey` | +| `exception` | The client or connection reported an error | + +A successful `response` event confirms the [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). It does not mean that a market update has arrived yet. + +### 4. Subscribe to private Spot streams + +Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. + + + +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); + +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); + +ws.on('update', (update) => { + console.log('Private Spot update:', update); +}); + +ws.on('reconnected', (event) => { + console.log('Reconnected:', event.wsKey); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +try { + ws.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Balance subscription failed:', error); } -⋮---- -/** Create/amend response for futures price-trigger orders (`/futures/{settle}/price_orders`). */ -export interface TriggerOrderResponse { - id?: number; - /** - * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. - */ - id_string?: string; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -/** - * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. - */ -⋮---- -export interface FuturesPriceTriggeredOrder { - initial: { - contract: string; - size?: number; - price?: string; - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - is_reduce_only?: boolean; - is_close?: boolean; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price?: string; - rule?: 1 | 2; - expiration?: number; - }; - id?: number; // int64 price-triggered order id - /** - * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. - */ - id_string?: string; - user?: number; - create_time?: number; - finish_time?: number; - trade_id?: number; - status?: 'open' | 'finished' | 'inactive' | 'invalid'; - finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; - reason?: string; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - me_order_id?: number; // int64 + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -id?: number; // int64 price-triggered order id -/** - * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. - */ -⋮---- -me_order_id?: number; // int64 -⋮---- -export interface FuturesDeliveryContract { - name?: string; - /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ - contract_type?: string; - underlying?: string; - cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; // First-tier maintenance margin rate requirement - mark_type?: 'internal' | 'index'; // Deprecated - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; // Minimum unit of mark price - basis_rate?: string; - basis_value?: string; - basis_impact_value?: string; - settle_price?: string; - settle_price_interval?: number; - settle_price_duration?: number; - expire_time?: number; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - orderbook_id?: number; - trade_id?: number; - trade_size?: number; - position_size?: number; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; + +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` + +Use the `authenticated` event as a connection-level signal. Use private updates as [private stream confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) of account and order changes. + +Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. + +### 5. Subscribe to private Futures streams + +Futures private channels use your Gate user ID. Contract-specific channels also include the contract. Retrieve the user ID once from the REST API, then use the payload required by each channel. + +```javascript +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); + +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); + +ws.on('update', (update) => { + console.log('Private Futures update:', update); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +async function main() { + let account; + + try { + account = await rest.getAccountDetail(); + console.log('Gate user ID:', account.user_id); + } catch (error) { + console.error('Account detail request failed:', error); + return; + } + + const userId = String(account.user_id); + const payload = [userId, 'BTC_USDT']; + const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; + + try { + ws.subscribe( + { + topic: 'futures.orders', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Order subscription failed:', error); + } + + try { + ws.subscribe( + { + topic: 'futures.usertrades', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Trade subscription failed:', error); + } + + try { + ws.subscribe( + { + topic: 'futures.balances', + payload: [userId], + }, + wsKey, + ); + } catch (error) { + console.error('Balance subscription failed:', error); + } + + try { + ws.subscribe( + { + topic: 'futures.positions', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Position subscription failed:', error); + } } -⋮---- -/** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ -⋮---- -quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" -⋮---- -maintenance_rate?: string; // First-tier maintenance margin rate requirement -mark_type?: 'internal' | 'index'; // Deprecated -⋮---- -mark_price_round?: string; // Minimum unit of mark price -⋮---- -export interface BatchAmendOrderResp { - succeeded: boolean; - label?: string; - detail?: string; - id: number; - user: number; - create_time: number; - finish_time?: number; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as?: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'poc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed' - | 'reduce_out' - | 'stp'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc' | 'fok'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - stp_act: 'co' | 'cn' | 'cb' | '-'; - stp_id: number; + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main(); +``` + +Keep the `wsKey` aligned with the settlement currency and product. USDT perpetual Futures use `WS_KEY_MAP.perpFuturesUSDTV4`; BTC perpetual Futures use `WS_KEY_MAP.perpFuturesBTCV4`. + +Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. + +### 6. Place and cancel a Spot order in TestNet + +Gate TestNet uses separate credentials and API hosts. This example: + +1. Checks the explicit order opt-in. +2. Loads current `BTC_USDT` trading rules and the order book. +3. Calculates an amount that meets the pair's base and quote minimums. +4. Places a post-only limit buy at the current best bid. +5. Queries the order and cancels it if it remains open. + +The order uses `time_in_force: 'poc'`, Gate's post-only setting. A fast market can move before the request arrives, in which case Gate can reject or finish the order instead of leaving it on the book. + + + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let pair; + + try { + pair = await client.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + } catch (error) { + console.error('Currency pair request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { + console.error('BTC_USDT is not currently buyable.'); + return; + } + + const price = orderBook.bids[0]?.[0]; + const amountPrecision = pair.amount_precision; + const minBase = Number(pair.min_base_amount); + const minQuote = Number(pair.min_quote_amount); + const priceNumber = Number(price); + + if ( + !price || + amountPrecision === undefined || + !Number.isFinite(minBase) || + !Number.isFinite(minQuote) || + !Number.isFinite(priceNumber) || + priceNumber <= 0 + ) { + console.error('Required market metadata is unavailable.'); + return; + } + + const amountStep = 10 ** -amountPrecision; + const minimumAmount = Math.max(minBase, minQuote / priceNumber); + const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; + const amount = amountNumber.toFixed(amountPrecision); + + if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { + console.error('Could not derive a valid TestNet order.'); + return; + } + + const maxBase = Number(pair.max_base_amount); + const maxQuote = Number(pair.max_quote_amount); + + if ( + (Number.isFinite(maxBase) && amountNumber > maxBase) || + (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) + ) { + console.error('Derived amount exceeds the pair limits.'); + return; + } + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + let placedOrder; + + try { + placedOrder = await client.submitSpotOrder({ + currency_pair: 'BTC_USDT', + account: 'spot', + side: 'buy', + type: 'limit', + amount, + price, + time_in_force: 'poc', + text, + }); + console.log('Placed Spot order:', placedOrder); + } catch (error) { + console.error('Spot order placement failed:', error); + return; + } + + if (!placedOrder.id) { + console.error('Gate did not return an order ID.'); + return; + } + + let currentOrder; + + try { + currentOrder = await client.getSpotOrder({ + order_id: placedOrder.id, + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Current Spot order:', currentOrder); + } catch (error) { + console.error('Spot order query failed:', error); + } + + if (currentOrder && currentOrder.status !== 'open') { + console.log('Order is no longer open:', currentOrder.status); + return; + } + + try { + const cancelledOrder = await client.cancelSpotOrder({ + order_id: placedOrder.id, + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Cancelled Spot order:', cancelledOrder); + } catch (error) { + console.error('Spot order cancellation failed:', error); + } +} + +main(); +``` + +The extra amount increment avoids falling just below the quote minimum after decimal rounding. Before using another pair, read its `amount_precision`, `precision`, minimums, maximums, and `trade_status`. + +### 7. Place and cancel a USDT perpetual order in TestNet + +A Futures `size` is a contract count. It is not an amount of BTC or USDT. This example reads the contract's minimum size and current price, and it only runs when the account is in one-way mode. It does not change account or position settings. + + + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let contract; + + try { + contract = await client.getFuturesContract({ + settle: 'usdt', + contract: 'BTC_USDT', + }); + } catch (error) { + console.error('Contract request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await client.getFuturesOrderBook({ + settle: 'usdt', + contract: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + let account; + + try { + account = await client.getFuturesAccount({ + settle: 'usdt', + }); + } catch (error) { + console.error('Futures account request failed:', error); + return; + } + + const oneWayMode = account.position_mode + ? account.position_mode === 'single' + : !account.in_dual_mode; + + if (!oneWayMode) { + console.error('This example requires one-way Futures position mode.'); + return; + } + + if (contract.status && contract.status !== 'trading') { + console.error('BTC_USDT Futures is not currently trading.'); + return; + } + + const price = orderBook.bids[0]?.p; + const size = Number(contract.order_size_min); + + if ( + !price || + !Number.isFinite(Number(price)) || + Number(price) <= 0 || + !Number.isFinite(size) || + size <= 0 || + (contract.enable_decimal === false && !Number.isInteger(size)) + ) { + console.error('Required contract metadata is unavailable.'); + return; + } + + console.log('One contract represents:', contract.quanto_multiplier, 'BTC'); + console.log('Price increment:', contract.order_price_round); + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + let placedOrder; + + try { + placedOrder = await client.submitFuturesOrder({ + settle: 'usdt', + contract: 'BTC_USDT', + size, + price, + tif: 'poc', + text, + }); + console.log('Placed Futures order:', placedOrder); + } catch (error) { + console.error('Futures order placement failed:', error); + return; + } + + if (placedOrder.id === undefined) { + console.error('Gate did not return an order ID.'); + return; + } + + const orderId = String(placedOrder.id); + let currentOrder; + + try { + currentOrder = await client.getFuturesOrder({ + settle: 'usdt', + order_id: orderId, + }); + console.log('Current Futures order:', currentOrder); + } catch (error) { + console.error('Futures order query failed:', error); + } + + if (currentOrder && currentOrder.status !== 'open') { + console.log('Order is no longer open:', currentOrder.status); + return; + } + + try { + const cancelledOrder = await client.cancelFuturesOrder({ + settle: 'usdt', + order_id: orderId, + }); + console.log('Cancelled Futures order:', cancelledOrder); + } catch (error) { + console.error('Futures order cancellation failed:', error); + } } -⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ -⋮---- -/** - * @deprecated - Use FuturesAccount instead - */ -export interface UpdateFuturesDualModeResp { - total: string; - unrealised_pnl: string; - position_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic: boolean; - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; + +main(); +``` + +In one-way mode, a positive `size` buys and a negative `size` sells. Dual-side mode uses different position semantics, so handle it in account-specific code after reading the [official Gate API v4 documentation](https://www.gate.com/docs/developers/apiv4/en/). + +The contract metadata supplies the size and price rules: + +- `order_size_min`: minimum contract count +- `order_price_round`: permitted price increment +- `quanto_multiplier`: underlying amount represented by one contract +- `enable_decimal`: whether fractional contract sizes are supported + +Do not derive a Futures order size from Spot precision rules. + +### 8. Send a Spot order through the WebSocket API + +`WebsocketAPIClient` turns Gate WebSocket API commands into promises. It connects and authenticates automatically on the first private command, adds a request ID, matches the response, and resolves the promise. + +This TestNet example uses the REST API only to read current market rules and the order book. The order, query, and cancellation use the WebSocket API. + + + +```javascript +import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let pair; + + try { + pair = await rest.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + } catch (error) { + console.error('Currency pair request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await rest.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { + console.error('BTC_USDT is not currently buyable.'); + return; + } + + const price = orderBook.bids[0]?.[0]; + const amountPrecision = pair.amount_precision; + const minBase = Number(pair.min_base_amount); + const minQuote = Number(pair.min_quote_amount); + const priceNumber = Number(price); + + if ( + !price || + amountPrecision === undefined || + !Number.isFinite(minBase) || + !Number.isFinite(minQuote) || + !Number.isFinite(priceNumber) || + priceNumber <= 0 + ) { + console.error('Required market metadata is unavailable.'); + return; + } + + const amountStep = 10 ** -amountPrecision; + const minimumAmount = Math.max(minBase, minQuote / priceNumber); + const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; + const amount = amountNumber.toFixed(amountPrecision); + + if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { + console.error('Could not derive a valid TestNet order.'); + return; + } + + const maxBase = Number(pair.max_base_amount); + const maxQuote = Number(pair.max_quote_amount); + + if ( + (Number.isFinite(maxBase) && amountNumber > maxBase) || + (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) + ) { + console.error('Derived amount exceeds the pair limits.'); + return; + } + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + const wsKey = WS_KEY_MAP.spotV4; + + try { + let placedResponse; + + try { + placedResponse = await wsApi.submitNewSpotOrder( + { + currency_pair: 'BTC_USDT', + account: 'spot', + side: 'buy', + type: 'limit', + amount, + price, + time_in_force: 'poc', + text, + }, + wsKey, + ); + console.log('Command status:', placedResponse.header.status); + console.log('Placed Spot order:', placedResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API placement failed:', error); + return; + } + + const orderId = placedResponse.data.result.id; + let statusResponse; + + try { + statusResponse = await wsApi.getSpotOrderStatus( + { + order_id: orderId, + currency_pair: 'BTC_USDT', + account: 'spot', + }, + wsKey, + ); + console.log('Current Spot order:', statusResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API query failed:', error); + } + + if (statusResponse && statusResponse.data.result.status !== 'open') { + console.log( + 'Order is no longer open:', + statusResponse.data.result.status, + ); + return; + } + + try { + const cancelledResponse = await wsApi.cancelSpotOrder( + { + order_id: orderId, + currency_pair: 'BTC_USDT', + account: 'spot', + }, + wsKey, + ); + console.log('Cancelled Spot order:', cancelledResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API cancellation failed:', error); + } + } finally { + wsApi.getWSClient().closeAll(); + } } -⋮---- -export interface RiskLimitTableTier { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; // First-tier maintenance margin rate requirement - leverage_max: string; - deduction: string; + +main(); +``` + +### 9. Send a USDT perpetual order through the WebSocket API + +Futures WebSocket API commands use a product-specific WebSocket key. Pass it explicitly so the contract and connection remain clear. + + + +```javascript +import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + wsUrl: 'wss://ws-testnet.gate.com/v4/ws/futures/usdt', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let contract; + + try { + contract = await rest.getFuturesContract({ + settle: 'usdt', + contract: 'BTC_USDT', + }); + } catch (error) { + console.error('Contract request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await rest.getFuturesOrderBook({ + settle: 'usdt', + contract: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + let account; + + try { + account = await rest.getFuturesAccount({ + settle: 'usdt', + }); + } catch (error) { + console.error('Futures account request failed:', error); + return; + } + + const oneWayMode = account.position_mode + ? account.position_mode === 'single' + : !account.in_dual_mode; + + if (!oneWayMode) { + console.error('This example requires one-way Futures position mode.'); + return; + } + + if (contract.status && contract.status !== 'trading') { + console.error('BTC_USDT Futures is not currently trading.'); + return; + } + + const price = orderBook.bids[0]?.p; + const size = Number(contract.order_size_min); + + if ( + !price || + !Number.isFinite(Number(price)) || + Number(price) <= 0 || + !Number.isFinite(size) || + size <= 0 || + (contract.enable_decimal === false && !Number.isInteger(size)) + ) { + console.error('Required contract metadata is unavailable.'); + return; + } + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; + + try { + let placedResponse; + + try { + placedResponse = await wsApi.submitNewFuturesOrder( + { + contract: 'BTC_USDT', + size, + price, + tif: 'poc', + text, + }, + wsKey, + ); + console.log('Command status:', placedResponse.header.status); + console.log('Placed Futures order:', placedResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API placement failed:', error); + return; + } + + const orderId = String(placedResponse.data.result.id); + let statusResponse; + + try { + statusResponse = await wsApi.getFuturesOrderStatus( + { + order_id: orderId, + }, + wsKey, + ); + console.log('Current Futures order:', statusResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API query failed:', error); + } + + if (statusResponse && statusResponse.data.result.status !== 'open') { + console.log( + 'Order is no longer open:', + statusResponse.data.result.status, + ); + return; + } + + try { + const cancelledResponse = await wsApi.cancelFuturesOrder( + { + order_id: orderId, + }, + wsKey, + ); + console.log('Cancelled Futures order:', cancelledResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API cancellation failed:', error); + } + } finally { + wsApi.getWSClient().closeAll(); + } } -⋮---- -maintenance_rate: string; // First-tier maintenance margin rate requirement -⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint types -export interface FuturesInsuranceHistory { - t: number; - b: string; + +main(); +``` + +Successful commands have `header.status === '200'`, and the endpoint result is in `data.result`. The SDK rejects a command promise when Gate returns a non-success status. + +An accepted command is not proof that an order later filled, remained open, or was cancelled. Treat the response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then confirm the final state through the private order stream or a REST API query. + + + +## Work with the Gate REST API + +`RestClient` covers Gate's product groups through named methods. Public methods work without credentials. Private methods use the API key and secret passed to the client. + +### Understand response shapes + +The client resolves to the endpoint's response body: + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient(); + +async function main() { + try { + const result = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + }); + console.log(result); + } catch (error) { + console.error('Order book request failed:', error); + } } -⋮---- -/** Trail order (autoorder/v1/trail) response types */ -export interface TrailOrder { - id?: number | string; - user_id?: number | string; - user?: number | string; - contract?: string; - settle?: string; - amount?: string; - is_gte?: boolean; - activation_price?: string; - price_type?: number; - price_offset?: string; - text?: string; - reduce_only?: boolean; - position_related?: boolean; - created_at?: number | string; - activated_at?: number | string; - finished_at?: number | string; - create_time?: number | string; - active_time?: number | string; - finish_time?: number | string; - reason?: string; - suborder_text?: string; - is_dual_mode?: boolean; - trigger_price?: string; - suborder_id?: number | string; - side_label?: string; - original_status?: number; - status?: string; - position_side_output?: string; - updated_at?: number | string; - extremum_price?: string; - status_code?: string; - created_at_precise?: string; - finished_at_precise?: string; - activated_at_precise?: string; - status_label?: string; - pos_margin_mode?: string; - position_mode?: string; - error_label?: string; - leverage?: string; - [key: string]: unknown; + +main(); +``` + +There is no shared response envelope. Check the [SDK endpoint map](./endpointFunctionList.md) before deciding how to handle `result`. + +| Method | Response shape | +| ----------------------- | ------------------------------------------ | +| `getServerTime()` | Object with `server_time` | +| `getSpotCurrencyPair()` | Currency-pair object | +| `getSpotTicker()` | Array of ticker objects | +| `getSpotOrderBook()` | Object with tuple-array `bids` and `asks` | +| `getSpotCandles()` | Array of candle tuples | +| `getFuturesContract()` | Contract object | +| `getFuturesTickers()` | Array of ticker objects | +| `getFuturesOrderBook()` | Object with `{ p, s }` bid and ask entries | +| `getFuturesAccount()` | Account object | +| `getFuturesPositions()` | Array of position objects | + +Prices and quantities are commonly returned as strings. Keep them as strings while passing them between Gate API methods. Convert them deliberately when doing calculations, and round the result back to the product's required precision. + +### Read account state + +An authenticated integration usually needs these views: + +| State | Spot method | USDT perpetual method | +| ------------------- | ------------------------- | ---------------------------------------------------------- | +| Balances or account | `getSpotAccounts()` | `getFuturesAccount({ settle: 'usdt' })` | +| Positions | Not applicable | `getFuturesPositions({ settle: 'usdt' })` | +| Open orders | `getSpotOpenOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'open' })` | +| Recent orders | `getSpotOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'finished' })` | +| Trades | `getSpotTradingHistory()` | `getFuturesTradingHistory({ settle: 'usdt' })` | + +These REST API views form a reliable [account state](https://siebly.io/reference/glossary#accountstate) baseline before stream updates are applied. + +### Explore other Gate product groups + +The same `RestClient` also covers the following APIs. Start with read methods and check account eligibility, permissions, and product-specific rules before using any write method. + +| Product group | Representative SDK methods | +| ----------------------- | --------------------------------------------------------------------------- | +| Margin and cross margin | `getMarginAccounts()`, `getCrossMarginAccount()`, `getMarginUserAccounts()` | +| Universal margin loans | `getMarginUNILoans()`, `getMarginUNIMaxBorrow()` | +| Unified Account | `getUnifiedAccountInfo()`, `getUnifiedAccountMode()`, `getUnifiedLoans()` | +| Delivery | `getAllDeliveryContracts()`, `getDeliveryAccount()`, `getDeliveryOrders()` | +| Options | `getOptionsContracts()`, `getOptionsAccount()`, `getOptionsOrders()` | +| Wallet and transfers | `getBalances()`, `submitTransfer()`, `getTransferStatus()` | +| Multi-collateral loans | `getMultiLoanOrders()`, `getMultiLoanSupportedCurrencies()` | +| Flash Swap | `getFlashSwapCurrencyPairs()`, `getFlashSwapOrders()` | +| Earn and lending | `getEarnFixedTermProducts()`, `getEarnFixedTermLends()` | +| Auto Invest | `getAutoInvestCoins()`, `getAutoInvestPlans()`, `getAutoInvestOrders()` | +| Subaccounts | `getSubAccounts()`, `getSubBalance()`, `getSubFuturesBalances()` | +| Rebates and partners | `getPartnerTransactionHistory()`, `getPartnerCommissionHistory()` | +| OTC | `getOTCBankList()`, `getOTCFiatOrderList()` | +| P2P Merchant | `getP2PMerchantUserInfo()`, `getP2PMerchantPendingTransactionList()` | +| CrossEx | `getCrossExSymbols()`, `getCrossExAccounts()`, `getCrossExPositions()` | +| Alpha | `getAlphaCurrencies()`, `getAlphaTickers()`, `getAlphaOrders()` | +| TradFi | `getTradFiSymbols()`, `getTradFiAssets()`, `getTradFiOrders()` | + +See the [complete SDK endpoint map](./endpointFunctionList.md) for every supported method, its authentication requirement, HTTP method, and Gate path. + + + +## Build with WebSocket streams + +Use `WebsocketClient` for ongoing market and account updates. A subscription request has two independent parts: + +- `topic` and `payload` select the Gate channel and its data. +- `wsKey` selects the product connection that carries the subscription. + +One `subscribe()` call can contain several topics when they share the same `wsKey`. Use separate calls for topics on different product connections. + +### Choose the correct WebSocket key + +| Product connection | SDK key | +| ---------------------- | ---------------------------------- | +| Spot | `WS_KEY_MAP.spotV4` | +| USDT perpetual Futures | `WS_KEY_MAP.perpFuturesUSDTV4` | +| BTC perpetual Futures | `WS_KEY_MAP.perpFuturesBTCV4` | +| USDT Delivery | `WS_KEY_MAP.deliveryFuturesUSDTV4` | +| BTC Delivery | `WS_KEY_MAP.deliveryFuturesBTCV4` | +| Options | `WS_KEY_MAP.optionsV4` | +| Announcements | `WS_KEY_MAP.announcementsV4` | + +Do not infer the connection from a symbol alone. `BTC_USDT` can appear in more than one product family. + +Useful public topics include: + +| Product | Starting topics | +| ------- | -------------------------------------------------------------------------------------------------------------- | +| Spot | `spot.tickers`, `spot.trades`, `spot.order_book`, `spot.order_book_update`, `spot.candlesticks` | +| Futures | `futures.tickers`, `futures.trades`, `futures.order_book`, `futures.order_book_update`, `futures.candlesticks` | +| Options | `options.tickers`, `options.trades`, `options.order_book`, `options.ul_tickers` | + +### Treat responses and updates differently + +The `response` event tells you whether Gate accepted a subscribe, unsubscribe, or request message. Check its `error` and `result`. + +The `update` event carries channel data. Inspect `channel`, `event`, `result`, and the SDK-added `wsKey` before updating local state. A subscription response and a data update can have different result shapes. + +### Recover after a reconnect + +The SDK reconnects and restores cached subscriptions. A stream gap can still hide balance, order, trade, or position changes. Reload the affected state from the REST API after `reconnected`. + +This Spot example reloads balances, open orders, and recent trades in sequence: + +```javascript +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +let recoveryRunning = false; +let spotState; + +async function recoverSpotState() { + if (recoveryRunning) { + return; + } + + recoveryRunning = true; + + try { + let balances; + + try { + balances = await rest.getSpotAccounts(); + } catch (error) { + console.error('Balance recovery failed:', error); + return; + } + + let openOrders; + + try { + openOrders = await rest.getSpotOpenOrders({ + account: 'spot', + }); + } catch (error) { + console.error('Open-order recovery failed:', error); + return; + } + + let trades; + + try { + trades = await rest.getSpotTradingHistory({ + currency_pair: 'BTC_USDT', + account: 'spot', + limit: 100, + }); + } catch (error) { + console.error('Trade recovery failed:', error); + return; + } + + spotState = { + balances, + openOrders, + trades, + recoveredAt: Date.now(), + }; + + console.log('Recovered Spot state:', spotState); + } finally { + recoveryRunning = false; + } } -⋮---- -export interface TrailChangeLog { - updated_at?: number; - amount?: string; - is_gte?: boolean; - activation_price?: string; - price_type?: number; - price_offset?: string; - is_create?: boolean; + +ws.on('reconnected', async ({ wsKey }) => { + if (wsKey !== WS_KEY_MAP.spotV4) { + return; + } + + await recoverSpotState(); +}); + +ws.on('update', (update) => { + console.log('Private Spot update:', update); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +try { + ws.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Balance subscription failed:', error); } -⋮---- -export interface ChaseOrder { - id?: string; - user?: string; - contract?: string; - settle?: string; - amount?: string; - price_limit?: string; - reduce_only?: boolean; - text?: string; - create_time?: number; - finish_time?: number; - original_status?: number; - status?: string; - reason?: string; - fill_amount?: string; - average_fill_price?: string; - suborder_id?: string; - is_dual_mode?: boolean; - side_label?: string; - position_side_output?: string; - chase_price?: string; - interval_sec?: number; - updated_at?: number; - suborder_price?: string; - suborder_ongoing?: boolean; - suborder_finish_as?: string; - price_type?: number; - price_gap_type?: string; - price_gap_value?: string; - status_code?: string; - create_time_precise?: string; - finish_time_precise?: string; - pos_margin_mode?: string; - position_mode?: string; - leverage?: string; - error_label?: string; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -export interface CreateChaseOrderResp { - id?: string; + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -export interface StopChaseOrderResp { - order?: ChaseOrder; + +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` + +This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration) applied as [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery). The example replaces `spotState` only after all three reads succeed. Reload only the state that may have changed on the affected connection, then reconcile it before trusting new updates. + +For a wider recovery design, see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows). + + + +## Use the Gate WebSocket API + +`WebsocketAPIClient` is for request and response commands over WebSocket. It is not the same as a subscription stream. + +The client: + +1. Opens the selected WebSocket connection. +2. Authenticates automatically. +3. Adds a unique request ID. +4. Sends the command. +5. Matches Gate's response to the pending promise. +6. Resolves with `header`, `data.result`, `request_id`, and `wsKey`. + +Authentication happens automatically on the first command. `connectWSAPI(wsKey)` is available when an application wants to open and authenticate the connection early. Automatic WebSocket API reauthentication after a reconnect is enabled by default. + +Spot methods include: + +- `submitNewSpotOrder()` +- `getSpotOrderStatus()` +- `getSpotOrders()` +- `updateSpotOrder()` +- `cancelSpotOrder()` +- `cancelSpotOrderById()` +- `cancelSpotOrderForSymbol()` + +Futures methods include: + +- `submitNewFuturesOrder()` +- `submitNewFuturesBatchOrder()` +- `getFuturesOrderStatus()` +- `getFuturesOrders()` +- `updateFuturesOrder()` +- `cancelFuturesOrder()` + +Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: + +```javascript +import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +async function main() { + try { + const response = await wsApi.getFuturesOrders( + { + contract: 'BTC_USDT', + status: 'open', + limit: 20, + }, + WS_KEY_MAP.perpFuturesUSDTV4, + ); + + console.log(response.header.status); + console.log(response.data.result); + } catch (error) { + console.error('WebSocket API order request failed:', error); + } finally { + wsApi.getWSClient().closeAll(); + } } -⋮---- -export interface StopAllChaseOrdersResp { - orders?: ChaseOrder[]; + +main(); +``` + +The response confirms the command outcome. Use private order streams or a REST API query to confirm the resulting exchange state. + + + +## Use Gate TestNet + +Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. + +| Interface | Current TestNet host | +| ------------------------ | ---------------------------------------------- | +| REST API | `https://api-testnet.gateapi.io/api/v4` | +| Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | +| USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | + +For WebSocket TestNet, set `useTestnet: true`. + +```javascript +import { RestClient, WebsocketClient } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const spotWs = new WebsocketClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + useTestnet: true, +}); +``` + +Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. + +Fund the required Spot or Futures TestNet account with test assets before running an order example. + + + +## Connect to Global and regional REST API hosts + +Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. + +| Environment or account | REST API base URL | Official reference | +| ------------------------ | --------------------------------------- | -------------------------------------------------------------------- | +| Global live | `https://api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Global TestNet | `https://api-testnet.gateapi.io/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Futures live alternative | `https://fx-api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Gate US live | `https://api.gate.us/api/v4` | [Gate US API v4](https://us.gate.com/en-us/docs/developers/apiv4/) | +| Gate EU live | `https://api.gateeu.com/api/v4` | [Gate EU API v4](https://eu.gate.com/docs/developers/apiv4/en/) | + +Global live is the SDK default. Set `baseUrl` for another supported account host: + +```javascript +import { RestClient } from 'gateio-api'; + +const gateUs = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + baseUrl: 'https://api.gate.us/api/v4', +}); + +const gateEu = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + baseUrl: 'https://api.gateeu.com/api/v4', +}); +``` + +Use only the client that matches the account. Regional APIs can expose different products and endpoint sets. Check the regional documentation before calling a method, and use the region's own credentials. + +This guide does not assign regional WebSocket URLs. Use a regional WebSocket host only when the official documentation for that account region provides it. + + + +## Use a proxy with the REST API and WebSockets + +`gateio-api` accepts standard Node.js agents. Configure the agent in both places when all Gate traffic must use the proxy: + +- Pass `httpsAgent` in the second `RestClient` argument and set `proxy: false`. +- Pass the same agent as `wsOptions.agent` to `WebsocketClient` or `WebsocketAPIClient`. + +See [Using proxies with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. + +### HTTP and HTTPS proxy + +Install the proxy agent: + +```bash +npm install https-proxy-agent +``` + +Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. + +```javascript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_PROXY_URL.'); + return; + } + + const agent = new HttpsProxyAgent(proxyUrl); + + const rest = new RestClient( + {}, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const ws = new WebsocketClient({ + wsOptions: { + agent, + }, + }); + + ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through proxy:', wsKey); + }); + + ws.on('response', (response) => { + console.log('Subscription response:', response); + }); + + ws.on('update', (update) => { + console.log('Ticker update through proxy:', update); + ws.closeAll(); + }); + + ws.on('exception', () => { + console.error('WebSocket proxy connection failed.'); + }); + + try { + const time = await rest.getServerTime(); + console.log('Server time through proxy:', time.server_time); + } catch { + console.error('REST API proxy request failed.'); + } + + try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('WebSocket proxy subscription failed.'); + } + + process.once('SIGINT', () => { + ws.closeAll(); + }); } -⋮---- -export interface GetChaseOrdersResp { - orders?: ChaseOrder[]; + +main(); +``` + +For an authenticated HTTP or HTTPS proxy, include the username and password in `GATE_PROXY_URL`. Percent-encode reserved characters in each credential component. + +### SOCKS5 proxy + +Install the SOCKS agent: + +```bash +npm install socks-proxy-agent +``` + +Set `GATE_SOCKS_PROXY_URL` to a `socks5://` URL: + +```javascript +import { SocksProxyAgent } from 'socks-proxy-agent'; +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_SOCKS_PROXY_URL.'); + return; + } + + const agent = new SocksProxyAgent(proxyUrl); + + const rest = new RestClient( + {}, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const ws = new WebsocketClient({ + wsOptions: { + agent, + }, + }); + + ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through SOCKS5:', wsKey); + }); + + ws.on('response', (response) => { + console.log('Subscription response:', response); + }); + + ws.on('update', (update) => { + console.log('Ticker update through SOCKS5:', update); + ws.closeAll(); + }); + + ws.on('exception', () => { + console.error('SOCKS5 WebSocket connection failed.'); + }); + + try { + const time = await rest.getServerTime(); + console.log('Server time through SOCKS5:', time.server_time); + } catch { + console.error('SOCKS5 REST API request failed.'); + } + + try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('SOCKS5 WebSocket subscription failed.'); + } + + process.once('SIGINT', () => { + ws.closeAll(); + }); } -⋮---- -export interface GetChaseOrderDetailResp { - order?: ChaseOrder; + +main(); +``` + +### Private REST API, stream, and WebSocket API traffic + +Use the same agent and credentials for private REST API calls, private subscriptions, and WebSocket API connections: + +```javascript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { + RestClient, + WebsocketAPIClient, + WebsocketClient, + WS_KEY_MAP, +} from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_PROXY_URL.'); + return; + } + + const agent = new HttpsProxyAgent(proxyUrl); + + const rest = new RestClient( + { + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + }, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const streams = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + wsOptions: { + agent, + }, + }); + + const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + wsOptions: { + agent, + }, + }); + + streams.on('authenticated', ({ wsKey }) => { + console.log('Private stream authenticated:', wsKey); + }); + + streams.on('update', (update) => { + console.log('Private update through proxy:', update); + }); + + streams.on('exception', () => { + console.error('Private stream proxy connection failed.'); + }); + + try { + const balances = await rest.getSpotAccounts(); + console.log('Spot balances through proxy:', balances); + } catch { + console.error('Private REST API proxy request failed.'); + } + + try { + streams.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('Private stream subscription failed.'); + } + + try { + await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); + console.log('WebSocket API authenticated through proxy.'); + } catch { + console.error('WebSocket API proxy connection failed.'); + } + + process.once('SIGINT', () => { + streams.closeAll(); + wsApi.getWSClient().closeAll(); + }); } -================ -File: README.md -================ -# Node.js & JavaScript SDK for Gate.com (Gate.io) REST APIs, WebSockets & WebSocket API +main(); +``` -

- - - - SDK Logo - - -

+To combine a proxy with TestNet or a regional API, keep `baseUrl` or `wsUrl` in the first client argument and the agent in the same positions shown above. -[![npm version](https://img.shields.io/npm/v/gateio-api)][1] -[![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] -[![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] -[![Build & Test](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml) -[![last commit](https://img.shields.io/github/last-commit/sieblyio/gateio-api)][1] -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) -[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/gateio-api) +The proxy's egress IP is the address Gate sees. Add that address to the API key whitelist when whitelisting is enabled. Use a stable proxy endpoint, monitor its latency, and never use a proxy to bypass account or regional restrictions. -[1]: https://www.npmjs.com/package/gateio-api +A proxy changes the network path, not request signing, account eligibility, or regional product access. Test public REST API and WebSocket traffic first. Treat HTTP 407 responses, TLS failures, and repeated reconnects as network faults. The SDK does not rotate proxy endpoints. -Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets: + -- Professional, robust & performant Gate.com SDK with extensive production use in live trading environments. -- Extensive integration with Gate.com (Gate.io) REST APIs and WebSockets. -- Complete TypeScript support (with type declarations for most API requests & responses). - - Strongly typed requests and responses. - - Automated end-to-end tests ensuring reliability. -- Actively maintained with a modern, promise-driven interface. -- Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC Trading APIs. - - Unified RestClient for all Gate.com trading products. - - Strongly typed on most requests and responses. - - Support for Cross-Exchange (CrossEx) trading across multiple exchanges - - Support for Alpha account trading (meme tokens and new listings) - - Support for OTC (fiat and stablecoin) trading -- Support for seamless API authentication for private Gate.com REST API and WebSocket calls. -- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - - Event driven messaging. - - Smart websocket persistence with automatic reconnection handling. - - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - - Automatically handle listenKey persistence and expiration/refresh. - - Emit `reconnected` event when dropped connection is restored. - - Support for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC. -- WebSocket API for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & CrossEx. - - Automatic connectivity via existing WebsocketClient, just call sendWSAPIRequest to trigger a request. - - Automatic authentication, just call sendWSAPIRequest with channel & parameters. - - Choose between two interfaces for WS API communication: - - Event-driven interface, fire & forget via sendWSAPIRequest and receive async replies via wsClient's event emitter. - - Promise-driven interface, simply use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. -- Heavy automated end-to-end testing with real API calls. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- QuickStart Guide: https://siebly.io/sdk/gate/javascript -- Gate JavaScript Tutorial: https://siebly.io/sdk/gate/javascript/tutorial +## Production checklist -## Table of Contents +### Keep request time accurate -- [Installation](#installation) -- [Examples](#examples) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation](#documentation) -- [Structure](#structure) -- [Usage](#usage) - - [REST API Client](#rest-api) - - [WebSocket Client](#websockets) - - [WebSocket Data Streams](#websocket-data-streams) - - [WebSocket API](#websocket-api) - - [Event Driven API](#event-driven-api) - - [REST-like API](#rest-like-api) -- [Customise Logging](#customise-logging) -- [Browser/Frontend Usage](#browserfrontend-usage) - - [Webpack](#webpack) -- [LLMs & AI](#use-with-llms--ai) -- [Used By](#used-by) -- [Contributions & Thanks](#contributions--thanks) +Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. -## Installation +Synchronize the host clock with NTP. Use `getServerTime()` for diagnosis, but fix the system clock rather than adding a permanent application offset for a drifting machine. -`npm install --save gateio-api` +### Respect rate limits -## Examples +Rate limits vary by product and endpoint. Read the current [Gate API rate-limit documentation](https://www.gate.com/docs/developers/apiv4/en/#frequency-limit-rule) and monitor rejection labels. -Refer to the [examples](./examples) folder for implementation demos, including: +Retry temporary network failures and rate-limit responses with bounded exponential backoff and jitter. Do not blindly retry an order command after an ambiguous timeout. First reconcile by the order's `text` value or query current order state. -- **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 +### Use custom order IDs -## Issues & Discussion +Set a unique `text` value beginning with `t-` on each application-owned order. Store it with your local request record. This gives retries, restarts, stream updates, and REST API recovery a common identifier. -- Issues? Check the [issues tab](https://github.com/sieblyio/gateio-api/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) +### Apply product metadata - +Before placing an order: -## Related Projects +- Check that the pair or contract is tradable. +- Apply minimum and maximum amounts. +- Round prices and quantities to the permitted increments. +- Treat Futures `size` as a contract count. +- Read `quanto_multiplier` before translating contract size into underlying exposure. +- Keep one-way, dual-side, and split position modes explicit. -Check out our JavaScript/TypeScript/Node.js SDKs & Projects: +Refresh metadata regularly and when Gate rejects an order for a precision or size rule. -- Visit our website: [https://Siebly.io](https://siebly.io/) -- Try our REST API & WebSocket SDKs published on npmjs: - - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) - - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) - - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) - - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) - - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) - - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) - - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) - - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) -- Try my misc utilities: - - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) - +### Confirm final state -## Documentation +A REST API response or WebSocket API response can arrive before later fills, cancellations, or amendments. Record the command response, then confirm final state through private streams or a REST API query. -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. +After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. -### API Documentation Links +### Scope credentials and network access -- [Gate.com/gate.io API Documentation](https://www.gate.com/docs/developers/apiv4/en/) - - [Spot Trading API](https://www.gate.com/docs/developers/apiv4/en/#spot-new) - - [Margin Trading API](https://www.gate.com/docs/developers/apiv4/en/#margin-new) - - [Futures Trading API](https://www.gate.com/docs/developers/apiv4/en/#futures-new) - - [Options Trading API](https://www.gate.com/docs/developers/apiv4/en/#options-new) - - [CrossEx Trading API](https://www.gate.com/docs/developers/apiv4/en/#crossex) - - [Alpha Trading API](https://www.gate.com/docs/developers/apiv4/en/#alpha) - - [OTC Trading API](https://www.gate.com/docs/developers/apiv4/en/#otc) - - [WebSocket API](https://www.gate.com/docs/developers/apiv4/en/#websocket-api) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/gateio-api) +- Use separate keys for live and TestNet. +- Grant only the product permissions the process needs. +- Use read-only keys for monitoring services. +- Do not grant withdrawal permission. +- Add IP whitelists when egress addresses are stable. +- Keep secrets in a server-side secret manager or deployment environment. +- Monitor proxy availability and egress IP changes. -## Structure +### Shut down connections -This project uses typescript. Resources are stored in 2 key structures: +Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. -- [src](./src) - the whole connector written in typescript -- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! +## FAQ ---- +### Does `gateio-api` work with plain JavaScript? -# Usage +Yes. Every example in this guide is plain JavaScript. The examples use ESM imports, so save them as `.mjs` files or set `"type": "module"` in `package.json`. The package also includes a CommonJS build and TypeScript declarations. -Create API credentials on Gate.com's website: +### Which client should I use? -- [Gate.com API Key Management](https://www.gate.com/myaccount/api_key_manage) +Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. -## REST API +### Do public Gate API calls need credentials? -The SDK provides a unified `RestClient` for all Gate.com trading products including Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha, and OTC Trading. This single client handles all REST API operations across all trading markets. +No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. -To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`: +### Why did a REST API call return an object when another returned an array? -```javascript -const { RestClient } = require('gateio-api'); +Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. -const API_KEY = 'xxx'; -const PRIVATE_KEY = 'yyy'; +### Why does `getSpotTicker()` return an array for one pair? -const client = new RestClient({ - apiKey: API_KEY, - apiSecret: PRIVATE_KEY, -}); +That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. -// Spot Trading Example -client - .getSpotTicker() - .then((result) => { - console.log('all spot tickers result: ', result); - }) - .catch((err) => { - console.error('spot ticker error: ', err); - }); +### How are Spot candles structured? -client - .getSpotOrders({ - currency_pair: 'BTC_USDT', - status: 'open', - }) - .then((result) => { - console.log('getSpotOrders result: ', result); - }) - .catch((err) => { - console.error('getSpotOrders error: ', err); - }); +Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. -// CrossEx Trading Example - Trade across multiple exchanges -client - .getCrossExSymbols() - .then((result) => { - console.log('CrossEx symbols: ', result); - }) - .catch((err) => { - console.error('CrossEx error: ', err); - }); +### Why does Gate use `BTC_USDT`? + +Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. + +### What do `account` and `settle` change? + +`account` selects the account used by a Spot order or query. `settle` selects the settlement currency and REST API path for Futures or Delivery requests. + +### What is the `text` order field? + +`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. + +### Why am I not receiving WebSocket updates? + +Check the topic payload, `wsKey`, API host, credentials, and permissions. Then inspect `response`, `authenticated`, and `exception` events. A successful subscription response confirms registration, but an update only arrives when the subscribed data changes. + +### Which `WS_KEY_MAP` value should I use? + +Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. + +### Why do private Futures topics use my Gate user ID? + +It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. + +### What is the difference between a stream and the WebSocket API? + +Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. -// 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); - }); +### Does a successful WebSocket API response mean the order filled? -// 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); - }); -``` +No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. -See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. +### Why was a post-only order rejected or immediately finished? -## WebSockets +The best bid or ask can move between the order-book request and order placement. Gate will not let a post-only order take liquidity. Read the returned status and `finish_as`, then decide whether to refresh the book and submit a new order with a new `text`. -All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles all Gate.com WebSocket streams with automatic connection management and reconnection. +### Why does a Futures order size look too small? -Key WebSocket features: +Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. -- 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 +### Can live credentials be used in TestNet? -### WebSocket Data Streams +No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. -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). +### Can I use Gate US or Gate EU with the SDK? -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. +Yes, for endpoints available to that account region. Set the documented regional `baseUrl`, use credentials from the same region, and check its official API documentation for product coverage. -Data events are emitted from the WebsocketClient via the `update` event, see example below: +### Can REST API and WebSocket traffic use the same proxy? -```javascript -const { WebsocketClient } = require('gateio-api'); +Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. -const API_KEY = 'xxx'; -const PRIVATE_KEY = 'yyy'; +### Does a proxy change signing or account eligibility? -const wsConfig = { - apiKey: API_KEY, - apiSecret: PRIVATE_KEY, +No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. - /* - The following parameters are optional: - */ +### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? - // Livenet is used by default, use this to enable testnet: - // useTestnet: true +Common causes are a drifting system clock, the wrong API secret, credentials from another environment, or an API request reaching the wrong host. Verify the clock, credential source, and API host without logging the secret. + +## Next steps + +- Browse the [Gate SDK examples](https://siebly.io/examples/Gate). +- Find methods in the [complete endpoint map](./endpointFunctionList.md). +- Review the [Gate SDK page](https://siebly.io/sdk/gate/javascript). +- Install or update [`gateio-api` from npm](https://www.npmjs.com/package/gateio-api). +- Browse the [`gateio-api` source repository](https://github.com/sieblyio/gateio-api). +- Read the official [Gate REST API documentation](https://www.gate.com/docs/developers/apiv4/en/). +- Read the official [Gate Spot WebSocket documentation](https://www.gate.com/docs/developers/apiv4/ws/). +- Read the official [Gate Futures WebSocket documentation](https://www.gate.com/docs/developers/futures/ws/). +- Review [Exchange State](https://siebly.io/reference/exchange-state) before building private state management. +- Use [Runtime Workflows](https://siebly.io/reference/runtime-workflows) when designing startup, reconnect, and reconciliation behavior. +- Open the [Siebly glossary](https://siebly.io/reference/glossary) for order, stream, and recovery terms. +- Report SDK issues in the [`gateio-api` GitHub repository](https://github.com/sieblyio/gateio-api/issues). + +================ +File: src/types/request/crossex.ts +================ +/**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ +⋮---- +export interface GetCrossExSymbolsReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} +⋮---- +symbols?: string; // Trading Pair List, multiple separated by commas +⋮---- +export interface GetCrossExRiskLimitsReq { + symbols: string; // Trading Pair List, multiple separated by commas +} +⋮---- +symbols: string; // Trading Pair List, multiple separated by commas +⋮---- +export interface GetCrossExTransferCoinsReq { + coin?: string; // Currency +} +⋮---- +coin?: string; // Currency +⋮---- +export interface CreateCrossExTransferReq { + coin: string; // Currency + amount: string; // Transfer amount + from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. + to: string; + text?: string; // User-defined ID +} +⋮---- +coin: string; // Currency +amount: string; // Transfer amount +from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. +⋮---- +text?: string; // User-defined ID +⋮---- +export interface GetCrossExTransferHistoryReq { + coin?: string; // Query by specified currency name + order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) + from?: number; // Start timestamp for the query + to?: number; // End timestamp for the query, defaults to current time if not specified + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 +} +⋮---- +coin?: string; // Query by specified currency name +order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) +from?: number; // Start timestamp for the query +to?: number; // End timestamp for the query, defaults to current time if not specified +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +export interface CreateCrossExOrderReq { + text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only + symbol: string; // Unique identifier Exchange_Business_Base_Counter + side: 'BUY' | 'SELL'; + type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) + time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement + qty?: string; // Order quantity (required unless spot market buy) + price?: string; // Limit Order Price (Required for Limit Orders) + quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders + reduce_only?: 'true' | 'false'; // Reduce-only + position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified +} +⋮---- +text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only +symbol: string; // Unique identifier Exchange_Business_Base_Counter +⋮---- +type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) +time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement +qty?: string; // Order quantity (required unless spot market buy) +price?: string; // Limit Order Price (Required for Limit Orders) +quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders +reduce_only?: 'true' | 'false'; // Reduce-only +position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified +⋮---- +export interface GetCrossExMarketTickersReq { + symbols?: string; +} +⋮---- +export interface GetCrossExMarketFundingInfoReq { + symbols?: string; +} +⋮---- +/** Either order_id or text required; order_id wins if both set */ +export interface CancelBatchCrossExOrdersReq { + order_id?: string; + text?: string; +} +⋮---- +export interface ModifyCrossExOrderReq { + qty?: string; // modify amount + price?: string; // modify price +} +⋮---- +qty?: string; // modify amount +price?: string; // modify price +⋮---- +export interface CreateCrossExConvertQuoteReq { + exchange_type: string; // Exchange Type + from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) + to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) + from_amount: string; // Amount to sell +} +⋮---- +exchange_type: string; // Exchange Type +from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) +to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) +from_amount: string; // Amount to sell +⋮---- +export interface CreateCrossExConvertOrderReq { + quote_id: string; // Inquiry ID +} +⋮---- +quote_id: string; // Inquiry ID +⋮---- +export interface UpdateCrossExAccountReq { + position_mode?: string; // Futures position mode (SINGLE/DUAL) + account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) + exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) +} +⋮---- +position_mode?: string; // Futures position mode (SINGLE/DUAL) +account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) +exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) +⋮---- +export interface GetCrossExAccountsReq { + exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) +} +⋮---- +exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) +⋮---- +export interface SetCrossExPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} +⋮---- +symbol: string; // Currency pair +leverage: string; // leverage +⋮---- +export interface GetCrossExPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} +⋮---- +symbols?: string; // Trading Pair List, multiple separated by commas +⋮---- +export interface SetCrossExMarginPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} +⋮---- +symbol: string; // Currency pair +leverage: string; // leverage +⋮---- +export interface GetCrossExMarginPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} +⋮---- +symbols?: string; // Trading Pair List, multiple separated by commas +⋮---- +export interface CloseCrossExPositionReq { + symbol: string; // Trading Pair + position_side?: string; // Position Direction +} +⋮---- +symbol: string; // Trading Pair +position_side?: string; // Position Direction +⋮---- +export interface GetCrossExInterestRateReq { + coin?: string; // Currency + exchange_type?: string; // Exchange +} +⋮---- +coin?: string; // Currency +exchange_type?: string; // Exchange +⋮---- +export interface GetCrossExPositionsReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange +} +⋮---- +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange +⋮---- +export interface GetCrossExMarginPositionsReq { + symbol?: string; // Currency pair + exchange_type?: string; // Exchange +} +⋮---- +symbol?: string; // Currency pair +exchange_type?: string; // Exchange +⋮---- +export interface GetCrossExAdlRankReq { + symbol: string; // Trading Pair +} +⋮---- +symbol: string; // Trading Pair +⋮---- +export interface GetCrossExOpenOrdersReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange + business_type?: string; // Business Type +} +⋮---- +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange +business_type?: string; // Business Type +⋮---- +export interface GetCrossExHistoryOrdersReq { + page?: number; // Page number + limit?: number; // Maximum number of records returned in a single list + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp + /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ + attributes?: string; +} +⋮---- +page?: number; // Page number +limit?: number; // Maximum number of records returned in a single list +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +/** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ +⋮---- +export interface GetCrossExHistoryPositionsReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp +} +⋮---- +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExHistoryMarginPositionsReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp +} +⋮---- +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExHistoryMarginInterestsReq { + symbol?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + exchange_type?: string; +} +⋮---- +export interface GetCrossExHistoryTradesReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp +} +⋮---- +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExAccountBookReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + coin?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp +} +⋮---- +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExCoinDiscountRateReq { + coin?: string; + exchange_type?: string; // OKX/GATE/BINANCE/BYBIT +} +⋮---- +exchange_type?: string; // OKX/GATE/BINANCE/BYBIT +⋮---- +export interface UpdateCrossExPositionsMarginReq { + symbol: string; + margin: string; + position_side?: 'NONE' | 'LONG' | 'SHORT'; +} - // how long to wait (in ms) before deciding the connection should be terminated & reconnected - // pongTimeout: 1000, +================ +File: src/types/response/crossex.ts +================ +/**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ +⋮---- +export interface CrossExSymbol { + symbol: string; + exchange_type: string; + business_type: string; + state: string; + min_size: string; + min_notional: string; + lot_size: string; + tick_size: string; + max_num_orders: string; + max_market_size: string; + max_limit_size: string; + contract_size: string; + liquidation_fee: string; + delist_time: string; + support_rpi?: string; // true/false whether RPI orders are supported + support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders +} +⋮---- +support_rpi?: string; // true/false whether RPI orders are supported +support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders +⋮---- +export interface CrossExRiskLimitTier { + min_risk_limit_value: string; // Minimum risk limit value + max_risk_limit_value: string; // Maximum risk limit value + leverage_max: string; // Maximum leverage + maintenance_rate: string; // Maintenance margin rate + tier: string; // Tier + quick_cal_amount: string; // Quick-calculation amount for this risk tier +} +⋮---- +min_risk_limit_value: string; // Minimum risk limit value +max_risk_limit_value: string; // Maximum risk limit value +leverage_max: string; // Maximum leverage +maintenance_rate: string; // Maintenance margin rate +tier: string; // Tier +quick_cal_amount: string; // Quick-calculation amount for this risk tier +⋮---- +export interface CrossExRiskLimit { + symbol: string; + tiers: CrossExRiskLimitTier[]; +} +⋮---- +export interface CrossExTransferCoin { + coin: string; // Currency + min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) + est_fee: number; // Estimated Fee + precision: number; // Precision + is_disabled: number; // If it is disabled. 0 means NOT being disabled +} +⋮---- +coin: string; // Currency +min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) +est_fee: number; // Estimated Fee +precision: number; // Precision +is_disabled: number; // If it is disabled. 0 means NOT being disabled +⋮---- +export interface CreateCrossExTransferResp { + tx_id: string; // Order ID + text: string; // User-defined Order ID +} +⋮---- +tx_id: string; // Order ID +text: string; // User-defined Order ID +⋮---- +export interface CrossExTransferHistory { + id: string; // Order ID + text: string; // Client Custom ID + from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) + to_account_type: string; + coin: string; // Currency + amount: string; // Transfer amount, the amount requested for the transfer + actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) + status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress + fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) + create_time: number; // Creation time of order + update_time: number; // Order Update Time +} +⋮---- +id: string; // Order ID +text: string; // Client Custom ID +from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) +⋮---- +coin: string; // Currency +amount: string; // Transfer amount, the amount requested for the transfer +actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) +status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress +fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) +create_time: number; // Creation time of order +update_time: number; // Order Update Time +⋮---- +export interface CreateCrossExOrderResp { + order_id: number | string; + text: string; // User-defined Order ID +} +⋮---- +text: string; // User-defined Order ID +⋮---- +export interface CancelCrossExOrderResp { + order_id: number; + text: string; +} +⋮---- +export interface ModifyCrossExOrderResp { + order_id: number; + text: string; +} +⋮---- +export interface CrossExOrder { + user_id: string; // User ID + order_id: string; // Order ID + text: string; // Client Order ID + state: string; // Order Status + symbol: string; // Currency pair + side: string; // direction + type: string; // type + attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT + exchange_type: string; // Exchange + business_type: string; // Business Type + qty: string; // Base Currency Quantity + quote_qty: string; // Quote Currency Quantity + price: string; // Price + time_in_force: string; // Time in Force Strategy + executed_qty: string; // Filled Quantity + executed_amount: string; // Filled Amount + executed_avg_price: string; // Average Filled Price + fee_coin: string; // Fee currency + fee: string; // fee + reduce_only: string; // Reduce Position Only + leverage: string; // leverage + reason: string; // Reason + last_executed_qty: string; // Latest Filled Quantity + last_executed_price: string; // Latest Filled Price + last_executed_amount: string; // Latest Filled Amount + position_side: string; // Position Direction + create_time: string; // Created time + update_time: string; // Update time +} +⋮---- +user_id: string; // User ID +order_id: string; // Order ID +text: string; // Client Order ID +state: string; // Order Status +symbol: string; // Currency pair +side: string; // direction +type: string; // type +attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT +exchange_type: string; // Exchange +business_type: string; // Business Type +qty: string; // Base Currency Quantity +quote_qty: string; // Quote Currency Quantity +price: string; // Price +time_in_force: string; // Time in Force Strategy +executed_qty: string; // Filled Quantity +executed_amount: string; // Filled Amount +executed_avg_price: string; // Average Filled Price +fee_coin: string; // Fee currency +fee: string; // fee +reduce_only: string; // Reduce Position Only +leverage: string; // leverage +reason: string; // Reason +last_executed_qty: string; // Latest Filled Quantity +last_executed_price: string; // Latest Filled Price +last_executed_amount: string; // Latest Filled Amount +position_side: string; // Position Direction +create_time: string; // Created time +update_time: string; // Update time +⋮---- +export interface CreateCrossExConvertQuoteResp { + quote_id: string; // Quote ID + valid_ms: string; // Valid time (milliseconds timestamp) + from_coin: string; // Asset Sold + to_coin: string; // Asset Bought + from_amount: string; // Amount to sell + to_amount: string; // Amount to buy + price: string; // Price +} +⋮---- +quote_id: string; // Quote ID +valid_ms: string; // Valid time (milliseconds timestamp) +from_coin: string; // Asset Sold +to_coin: string; // Asset Bought +from_amount: string; // Amount to sell +to_amount: string; // Amount to buy +price: string; // Price +⋮---- +export interface CreateCrossExConvertOrderResp { + order_id: string; // Order ID + text: string; // User-defined order ID text +} +⋮---- +order_id: string; // Order ID +text: string; // User-defined order ID text +⋮---- +export interface UpdateCrossExAccountResp { + position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) + account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) + exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) +} +⋮---- +position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) +account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) +exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) +⋮---- +export interface CrossExAccountAsset { + user_id: string; // User ID + coin: string; // Currency + exchange_type: string; // Exchange + balance: string; // Balance + upnl: string; // Unrealized P&L + equity: string; // Equity (only USDT has a value; other assets are 0) + futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) + futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) + borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) + borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) + available_balance: string; // Available Balance + liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) +} +⋮---- +user_id: string; // User ID +coin: string; // Currency +exchange_type: string; // Exchange +balance: string; // Balance +upnl: string; // Unrealized P&L +equity: string; // Equity (only USDT has a value; other assets are 0) +futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) +futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) +borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) +borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) +available_balance: string; // Available Balance +liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) +⋮---- +export interface CrossExAccount { + user_id: string; // User ID + available_margin: string; // Available Margin + margin_balance: string; // margin balance + initial_margin: string; // Initial Margin + maintenance_margin: string; // Maintenance margin + initial_margin_rate: string; // Initial margin rate + maintenance_margin_rate: string; // Maintenance margin rate + position_mode: string; // Contract Position Mode + account_limit: string; // Account limit + create_time: string; // Created time + update_time: string; // Update time + account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode + exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange + assets: CrossExAccountAsset[]; +} +⋮---- +user_id: string; // User ID +available_margin: string; // Available Margin +margin_balance: string; // margin balance +initial_margin: string; // Initial Margin +maintenance_margin: string; // Maintenance margin +initial_margin_rate: string; // Initial margin rate +maintenance_margin_rate: string; // Maintenance margin rate +position_mode: string; // Contract Position Mode +account_limit: string; // Account limit +create_time: string; // Created time +update_time: string; // Update time +account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode +exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange +⋮---- +export interface SetCrossExPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage +} +⋮---- +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage +⋮---- +export interface CrossExPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; +} +⋮---- +symbol: string; // Currency pair +⋮---- +export interface SetCrossExMarginPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage +} +⋮---- +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage +⋮---- +export interface CrossExMarginPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; +} +⋮---- +symbol: string; // Currency pair +⋮---- +export interface CloseCrossExPositionResp { + order_id: string; // Order ID + text: string; // User-defined Order ID +} +⋮---- +order_id: string; // Order ID +text: string; // User-defined Order ID +⋮---- +export interface CrossExInterestRate { + coin: string; // Currency + exchange_type: string; // Exchange + hour_interest_rate: string; // Hourly Interest Rate + time: string; // Millisecond Timestamp +} +⋮---- +coin: string; // Currency +exchange_type: string; // Exchange +hour_interest_rate: string; // Hourly Interest Rate +time: string; // Millisecond Timestamp +⋮---- +export interface CrossExSpecialFee { + symbol: string; // Currency pair + taker_fee_rate: string; // Taker fee rate + maker_fee_rate: string; // Maker fee rate + rpi_fee_rate?: string; // RPI order maker fee rate +} +⋮---- +symbol: string; // Currency pair +taker_fee_rate: string; // Taker fee rate +maker_fee_rate: string; // Maker fee rate +rpi_fee_rate?: string; // RPI order maker fee rate +⋮---- +export interface CrossExFeeRate { + exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) + spot_maker_fee: string; // spot Maker fee rate + spot_taker_fee: string; // spot Taker fee rate + spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate + future_maker_fee: string; // contract Maker fee rate + future_taker_fee: string; // contract Taker fee rate + future_rpi_maker_fee?: string; // Futures RPI order maker fee rate + special_fee_list: CrossExSpecialFee[]; +} +⋮---- +exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) +spot_maker_fee: string; // spot Maker fee rate +spot_taker_fee: string; // spot Taker fee rate +spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate +future_maker_fee: string; // contract Maker fee rate +future_taker_fee: string; // contract Taker fee rate +future_rpi_maker_fee?: string; // Futures RPI order maker fee rate +⋮---- +export interface CrossExMarketTicker { + symbol: string; + last_price: string; + open_24h: string; + low_24h: string; + high_24h: string; + volume_24h_base: string; + volume_24h_quote: string; + mark_price: string; + index_price: string; + open_interest: string; + open_interest_quote: string; + timestamp: string; +} +⋮---- +export interface CrossExMarketFundingInfo { + symbol: string; + funding_rate: string; + funding_interval: string; + funding_time: string; // Next funding time +} +⋮---- +funding_time: string; // Next funding time +⋮---- +export interface CancelBatchCrossExOrdersResp { + order_id: string; + text: string; + accepted: string; // "true" | "false" + label: string; + message: string; +} +⋮---- +accepted: string; // "true" | "false" +⋮---- +export interface CrossExPosition { + user_id: string; // User ID + position_id: string; // Position ID + symbol: string; // Currency pair + position_side: string; // Position Direction + initial_margin: string; // Initial Margin + maintenance_margin: string; // Maintenance margin + position_qty: string; // Position Quantity + position_value: string; // Position Value + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + entry_price: string; // Position Average Entry Price + mark_price: string; // Mark price + leverage: string; // Position Leverage + max_leverage: string; // Maximum leverage + risk_limit: string; // Position risk limit + fee: string; // Position Fee + funding_fee: string; // Position Funding Fee + funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) + create_time: string; // Position Creation Time + update_time: string; // Position Update Time + closed_pnl: string; // Realized PnL +} +⋮---- +user_id: string; // User ID +position_id: string; // Position ID +symbol: string; // Currency pair +position_side: string; // Position Direction +initial_margin: string; // Initial Margin +maintenance_margin: string; // Maintenance margin +position_qty: string; // Position Quantity +position_value: string; // Position Value +upnl: string; // Unrealized P&L +upnl_rate: string; // Unrealized P&L Ratio +entry_price: string; // Position Average Entry Price +mark_price: string; // Mark price +leverage: string; // Position Leverage +max_leverage: string; // Maximum leverage +risk_limit: string; // Position risk limit +fee: string; // Position Fee +funding_fee: string; // Position Funding Fee +funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) +create_time: string; // Position Creation Time +update_time: string; // Position Update Time +closed_pnl: string; // Realized PnL +⋮---- +export interface CrossExMarginPosition { + user_id: string; // User ID + position_id: string; // Leveraged Position ID + symbol: string; // Trading Pair + position_side: string; // Position Direction + initial_margin: string; // Initial position margin + maintenance_margin: string; // Position maintenance margin + asset_qty: string; // Position Asset Quantity + asset_coin: string; // Position Asset Currency + position_value: string; // Position Value + liability: string; // Debt Quantity + liability_coin: string; // Debt Currency + interest: string; // Deducted Interest + max_position_qty: string; // Max Trade Size + entry_price: string; // Position Cost Price (Average Opening Price) + index_price: string; // Index price + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + leverage: string; // Opening Leverage + max_leverage: string; // Maximum leverage + create_time: string; // Created time + update_time: string; // Update time +} +⋮---- +user_id: string; // User ID +position_id: string; // Leveraged Position ID +symbol: string; // Trading Pair +position_side: string; // Position Direction +initial_margin: string; // Initial position margin +maintenance_margin: string; // Position maintenance margin +asset_qty: string; // Position Asset Quantity +asset_coin: string; // Position Asset Currency +position_value: string; // Position Value +liability: string; // Debt Quantity +liability_coin: string; // Debt Currency +interest: string; // Deducted Interest +max_position_qty: string; // Max Trade Size +entry_price: string; // Position Cost Price (Average Opening Price) +index_price: string; // Index price +upnl: string; // Unrealized P&L +upnl_rate: string; // Unrealized P&L Ratio +leverage: string; // Opening Leverage +max_leverage: string; // Maximum leverage +create_time: string; // Created time +update_time: string; // Update time +⋮---- +export interface CrossExAdlRank { + user_id: string; // User ID + symbol: string; // Currency pair + crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) + exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) +} +⋮---- +user_id: string; // User ID +symbol: string; // Currency pair +crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) +exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) +⋮---- +export interface CrossExHistoryPosition { + position_id: string; // Position ID + user_id: string; // User ID + symbol: string; // Currency pair + closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) + closed_pnl: string; // Close Position P&L + closed_pnl_rate: string; // Close Position P&L Ratio + open_avg_price: string; // Average Opening Price + closed_avg_price: string; // Average Close Price + max_position_qty: string; // Max Trade Size + closed_qty: string; // Close Position Quantity + closed_value: string; // Close Position Value + fee: string; // Position Accumulated Fees + liq_fee: string; // Liquidation Fee + funding_fee: string; // Funding Fee + position_side: string; // Position Direction Before Close + position_mode: string; // Position Mode at Close + leverage: string; // Leverage at Close + margin_mode?: 'CROSS' | 'ISOLATED'; + business_type: string; // Business Type + create_time: string; // Created time + update_time: string; // Update time +} +⋮---- +position_id: string; // Position ID +user_id: string; // User ID +symbol: string; // Currency pair +closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) +closed_pnl: string; // Close Position P&L +closed_pnl_rate: string; // Close Position P&L Ratio +open_avg_price: string; // Average Opening Price +closed_avg_price: string; // Average Close Price +max_position_qty: string; // Max Trade Size +closed_qty: string; // Close Position Quantity +closed_value: string; // Close Position Value +fee: string; // Position Accumulated Fees +liq_fee: string; // Liquidation Fee +funding_fee: string; // Funding Fee +position_side: string; // Position Direction Before Close +position_mode: string; // Position Mode at Close +leverage: string; // Leverage at Close +⋮---- +business_type: string; // Business Type +create_time: string; // Created time +update_time: string; // Update time +⋮---- +export interface CrossExHistoryMarginPosition { + position_id: string; // Position ID + user_id: string; // User ID + symbol: string; // Currency pair + closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) + closed_pnl: string; // Close Position P&L + closed_pnl_rate: string; // Close Position P&L Ratio + open_avg_price: string; // Average Opening Price + closed_avg_price: string; // Average Close Price + max_position_qty: string; // Max Trade Size + closed_qty: string; // Close Position Quantity + closed_value: string; // Close Position Value + liq_fee: string; // Liquidation Fee + position_side: string; // Position Direction Before Close + leverage: string; // Leverage at Close + interest: string; // Total Deducted Interest + business_type: string; // Position Business Type + create_time: string; // Created time + update_time: string; // Update time +} +⋮---- +position_id: string; // Position ID +user_id: string; // User ID +symbol: string; // Currency pair +closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) +closed_pnl: string; // Close Position P&L +closed_pnl_rate: string; // Close Position P&L Ratio +open_avg_price: string; // Average Opening Price +closed_avg_price: string; // Average Close Price +max_position_qty: string; // Max Trade Size +closed_qty: string; // Close Position Quantity +closed_value: string; // Close Position Value +liq_fee: string; // Liquidation Fee +position_side: string; // Position Direction Before Close +leverage: string; // Leverage at Close +interest: string; // Total Deducted Interest +business_type: string; // Position Business Type +create_time: string; // Created time +update_time: string; // Update time +⋮---- +export interface CrossExHistoryMarginInterest { + userId: string; // User ID + symbol: string; // Trading Pair + interest_id: string; // Interest Deduction ID + liability_id: string; // Debt Source ID, can be Order ID or Position ID + liability: string; // Debt Quantity + liability_coin: string; // Debt Currency + interest: string; // Interest + interest_rate: string; // interest rate + interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) + create_time: string; // Created time + exchange_type: string; // Exchange +} +⋮---- +userId: string; // User ID +symbol: string; // Trading Pair +interest_id: string; // Interest Deduction ID +liability_id: string; // Debt Source ID, can be Order ID or Position ID +liability: string; // Debt Quantity +liability_coin: string; // Debt Currency +interest: string; // Interest +interest_rate: string; // interest rate +interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) +create_time: string; // Created time +exchange_type: string; // Exchange +⋮---- +export interface CrossExHistoryTrade { + user_id: string; // User ID + transaction_id: string; // filled records ID + order_id: string; // Order ID + text: string; // User Order ID + symbol: string; // Currency pair + exchange_type: string; // Exchange + business_type: string; // Business Type + side: string; // Buy/Sell Direction + qty: string; // Trading size + price: string; // Fill Price + fee: string; // fee + fee_coin: string; // Fee currency + fee_rate: string; // Fee Rate + match_role: string; // Filled Role + rpnl: string; // Realized P&L + position_mode: string; // Position Mode + position_side: string; // Position Direction + create_time: string; // Created time +} +⋮---- +user_id: string; // User ID +transaction_id: string; // filled records ID +order_id: string; // Order ID +text: string; // User Order ID +symbol: string; // Currency pair +exchange_type: string; // Exchange +business_type: string; // Business Type +side: string; // Buy/Sell Direction +qty: string; // Trading size +price: string; // Fill Price +fee: string; // fee +fee_coin: string; // Fee currency +fee_rate: string; // Fee Rate +match_role: string; // Filled Role +rpnl: string; // Realized P&L +position_mode: string; // Position Mode +position_side: string; // Position Direction +create_time: string; // Created time +⋮---- +export interface CrossExAccountBook { + id: string; // Account Change Record ID + user_id: string; // User ID + business_id: string; // Business ID + type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY + exchange_type: string; // Exchange + coin: string; // Currency + change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) + balance: string; // Balance after change + create_time: string; // Created time +} +⋮---- +id: string; // Account Change Record ID +user_id: string; // User ID +business_id: string; // Business ID +type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY +exchange_type: string; // Exchange +coin: string; // Currency +change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) +balance: string; // Balance after change +create_time: string; // Created time +⋮---- +export interface CrossExCoinDiscountRate { + coin: string; // Currency + exchange_type: string; // Exchange + tier: string; // Tier + min_value: string; // Minimum value + max_value: string; // Maximum value + discount_rate: string; // Discount rate +} +⋮---- +coin: string; // Currency +exchange_type: string; // Exchange +tier: string; // Tier +min_value: string; // Minimum value +max_value: string; // Maximum value +discount_rate: string; // Discount rate +⋮---- +export interface UpdateCrossExPositionsMarginResp { + symbol?: string; + margin?: string; + position_side?: 'NONE' | 'LONG' | 'SHORT'; +} - // how often to check (in ms) that WS connection is still alive - // pingInterval: 10000, +================ +File: src/types/response/spot.ts +================ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ +⋮---- +/** Limit-order take-profit / stop-loss on order responses (not re-exported; use request types for submits) */ +interface SpotOrderTPSL { + trigger_price: string; + order_price: string; +} +⋮---- +/** `{}` cancels TP/SL; `null` leaves unchanged */ +type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; +⋮---- +export interface SpotCurrencyChain { + name: string; + addr?: string; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; +} +⋮---- +export interface SpotCurrency { + currency: string; + name: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + chain: string; + chains: SpotCurrencyChain[]; + /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ + category?: string[]; +} +⋮---- +/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ +⋮---- +export interface SpotTicker { + currency_pair: string; + last: string; + lowest_ask: string; + lowest_size: string; + highest_bid: string; + highest_size: string; + change_percentage: string; + change_utc0: string; + change_utc8: string; + base_volume: string; + quote_volume: string; + high_24h: string; + low_24h: string; + etf_net_value: string; + etf_pre_net_value: string | null; + etf_pre_timestamp: number | null; + etf_leverage: string | null; +} +⋮---- +export interface SpotOrderBook { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; +} +⋮---- +export interface SpotTrade { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; + order_id: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; + trade_quote?: string; +} +⋮---- +export type SpotCandle = [ + string, // Unix timestamp with second precision + string, // Trading volume in quote currency + string, // Closing price + string, // Highest price + string, // Lowest price + string, // Opening price + string, // Trading volume in base currency + boolean, // Whether the window is closed +]; +⋮---- +string, // Unix timestamp with second precision +string, // Trading volume in quote currency +string, // Closing price +string, // Highest price +string, // Lowest price +string, // Opening price +string, // Trading volume in base currency +boolean, // Whether the window is closed +⋮---- +export interface SpotFeeRates { + user_id: number; + taker_fee: string; // For spot trading + maker_fee: string; // For spot trading + gt_discount: boolean; + gt_taker_fee: string; + gt_maker_fee: string; + loan_fee: string; + point_type: string; + currency_pair: string; + debit_fee: number; +} +⋮---- +taker_fee: string; // For spot trading +maker_fee: string; // For spot trading +⋮---- +export interface SpotAccount { + currency: string; + available: string; + locked: string; + update_id: number; + refresh_time: number; + last_update_time?: number; + trading_fee_rate?: string; +} +⋮---- +export interface SpotAccountBook { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + code: string; + text: string; +} +⋮---- +export interface SubmitSpotBatchOrdersResp { + order_id: string; + amend_text: string; + text: string; + succeeded: boolean; + label: string; + message: string; + id: string; + create_time: string; + update_time: string; + create_time_ms: number; + update_time_ms: number; + status: 'open' | 'closed' | 'cancelled'; + currency_pair: string; + type: 'limit' | 'market'; + account: 'spot' | 'margin' | 'cross_margin' | 'unified'; + side: 'buy' | 'sell'; + amount: string; + price: string; + time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg: string; + auto_repay: boolean; + left: string; + filled_amount: string; + fill_price: string; + filled_total: string; + avg_deal_price: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + gt_discount: boolean; + rebated_fee: string; + rebated_fee_currency: string; + stp_id: number; + stp_act: 'cn' | 'co' | 'cb' | '-'; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; +} +⋮---- +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- +export interface SpotOrder { + id?: string; + text?: string; + amend_text?: string; + create_time?: string; + update_time?: string; + create_time_ms?: number; + update_time_ms?: number; + status?: 'open' | 'closed' | 'cancelled'; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + side: 'buy' | 'sell'; + amount: string; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + left?: string; + filled_amount?: string; + fill_price?: string; + filled_total?: string; + avg_deal_price?: string; + fee?: string; + fee_currency?: string; + point_fee?: string; + gt_fee?: string; + gt_maker_fee?: string; + gt_taker_fee?: string; + gt_discount?: boolean; + rebated_fee?: string; + rebated_fee_currency?: string; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; + trade_quote?: string; +} +⋮---- +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- +export interface SpotInsuranceHistory { + currency: string; + balance: string; + time: number; +} +⋮---- +export interface SpotPriceTriggeredOrder { + trigger: { + price: string; + rule: '>=' | '<='; + expiration?: number; + }; + put: { + type?: 'limit' | 'market'; + side: 'buy' | 'sell'; + price: string; + amount: string; + account: 'normal' | 'margin' | 'cross_margin'; + time_in_force: 'gtc' | 'ioc'; + text?: string; + }; + id?: number; + user?: number; + market: string; + ctime?: number; + ftime?: number; + fired_order_id?: number; + status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; + reason?: string; +} +⋮---- +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: SpotOrder[]; +} +⋮---- +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; + text: string; +} +⋮---- +export interface SpotHistoricTradeRecord { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; + order_id: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; + deal?: string; // v4.105.29: Total Executed Value + trade_quote?: string; +} +⋮---- +deal?: string; // v4.105.29: Total Executed Value +⋮---- +export type SpotPovOrderStatus = + | 'CREATED' + | 'CANCELING' + | 'RUNNING' + | 'COMPLETED' + | 'EXPIRED' + | 'TERMINATED'; +⋮---- +export interface SpotPovOrder { + id?: string; + currency_pair?: string; + side?: string; + amount?: string; + participation_rate?: number; + ttl?: string; + limit_price?: string; + trigger_price?: string; + status?: SpotPovOrderStatus | string; + terminated_as?: string; + start_time_ms?: number; + end_time_ms?: number; + expire_time_ms?: number; + create_time_ms?: number; + update_time_ms?: number; + text?: string; +} - // how long to wait before attempting to reconnect (in ms) after connection is closed - // reconnectTimeout: 500, +================ +File: src/types/response/tradfi.ts +================ +/** TradFi API response types */ +⋮---- +export interface TradFiApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: string; +} +⋮---- +export interface TradFiListData { + list?: T[]; + total?: number; + total_page?: number; +} +⋮---- +export interface TradFiMT5Account { + mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility + leverage?: number; + stop_out_level?: string; + status?: number; +} +⋮---- +mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility +⋮---- +export interface TradFiCategoryItem { + category_id?: number; + is_favorite?: boolean; + category_name?: string; +} +⋮---- +export interface TradFiSymbolItem { + symbol?: string; + symbol_desc?: string; + category_id?: number; + status?: string; + trade_mode?: string; + icon_link?: string; + close_time?: number; + open_time?: number; + next_open_time?: number; + settlement_currency?: string; + settlement_currency_symbol?: string; + price_precision?: number; +} +⋮---- +export interface TradFiSymbolDetailItem { + symbol?: string; + symbol_desc?: string; + category_name?: string; + contract_volume?: string; + settlement_currency?: string; + max_order_volume?: string; + min_order_volume?: string; + leverage?: string; + price_precision?: number; + price_sl_level?: string; + swap_cost_type?: string; + buy_swap_cost_rate?: string; + sell_swap_cost_rate?: string; + swap_cost_3day?: string; + trade_timezone?: string; + trade_mode?: string; + icon_link?: string; + [key: string]: unknown; +} +⋮---- +export interface TradFiKlineItem { + o?: string; + c?: string; + h?: string; + l?: string; + t?: number; +} +⋮---- +export interface TradFiTicker { + highest_price?: string; + lowest_price?: string; + price_change?: string; + price_change_amount?: string; + today_open_price?: string; + last_today_close_price?: string; + last_price?: string; + bid_price?: string; + ask_price?: string; + favorite?: boolean; + status?: string; + close_time?: number; + open_time?: number; + next_open_time?: number; + trade_mode?: string; + category_name?: string; +} +⋮---- +export interface TradFiCreateUserResult { + status?: number; + leverage?: number; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +} +⋮---- +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +⋮---- +export interface TradFiAssets { + equity?: string; + margin_level?: string; + balance?: string; + margin?: string; + margin_free?: string; + unrealized_pnl?: string; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +} +⋮---- +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +⋮---- +export interface TradFiTransactionRecord { + asset?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + time?: number; +} +⋮---- +export interface TradFiTransactionListData { + total?: number; + total_page?: number; + list?: TradFiTransactionRecord[]; +} +⋮---- +export interface TradFiCreateOrderResult { + id?: string; +} +⋮---- +export interface TradFiOrderItem { + order_id?: number; + symbol?: string; + symbol_desc?: string; + price_type?: string; + state?: number; + state_desc?: string; + finished?: number; + side?: number; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; + time_setup?: number; +} +⋮---- +export interface TradFiOrderListData { + list?: TradFiOrderItem[]; + timestamp?: number; +} +⋮---- +export interface TradFiModifyOrderResult { + order_id?: number; + symbol?: string; + state?: string; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; +} +⋮---- +export interface TradFiOrderHistoryItem { + order_id?: number; + symbol?: string; + symbol_desc?: string; + price_type?: string; + order_opt_type?: number; + state?: number; + state_desc?: string; + side?: number; + volume?: string; + fill_volume?: string; + close_pnl?: string; + price?: string; + trigger_price?: string; + price_tp?: string; + price_sl?: string; + time_setup?: number; + time_done?: number; +} +⋮---- +export interface TradFiPositionItem { + position_id?: number; + symbol?: string; + symbol_desc?: string; + margin?: string; + unrealized_pnl?: string; + unrealized_pnl_rate?: string; + volume?: string; + price_open?: string; + position_dir?: string; + price_tp?: string; + price_sl?: string; + counterparty_price?: string; + time_create?: number; +} +⋮---- +export interface TradFiPositionListData { + list?: TradFiPositionItem[]; + timestamp?: number; +} +⋮---- +export interface TradFiPositionHistoryItem { + position_id?: number; + symbol?: string; + realized_pnl?: string; + realized_pnl_rate?: string; + volume?: string; + volume_closed?: string; + price_open?: string; + position_dir?: string; + price_tp?: string; + price_sl?: string; + counterparty_price?: string; + close_price?: string; + time_create?: string; + time_close?: string; + position_status?: string; + close_detail?: Record | null; + realized_pnl_detail?: { + closed_pnl?: string; + swap?: string; + fee?: string; + }; +} +⋮---- +/** GET /tradfi/orders/log/{log_id} — v4.106.94 */ +export interface TradFiOrderLog { + order_id?: number; + log_id?: number; + symbol?: string; + price_type?: 'market' | 'trigger'; + state?: number; + side?: number; + volume?: string; + price?: string; + [key: string]: unknown; +} +⋮---- +export interface TradFiSymbolCommissionItem { + category_code?: string; + symbol?: string; + fee_per_lot?: string; +} - // config options sent to RestClient (used for time sync). See RestClient docs. - // restOptions: { }, +================ +File: src/index.ts +================ +// Request Types +⋮---- +// Response Types +⋮---- +// Websockets Types +⋮---- +// Shared Types - // config for axios used for HTTP requests. E.g for proxy support - // requestOptions: { } -}; +================ +File: src/types/response/otc.ts +================ +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ +⋮---- +export interface OTCActionResp { + code: number; + message: string; + timestamp: number; +} +⋮---- +export interface CreateOTCQuoteResp { + code: number; + message: string; + data: { + type: string; // BUY (on-ramp) or SELL (off-ramp) + pay_coin: string; + get_coin: string; + pay_amount: string; + get_amount: string; + rate: string; + rate_reci: string; // Reciprocal of the exchange rate + promotion_code: string; + side: string; + order_type: string; // FIAT or STABLE + quote_token: string; // Quote token required when placing an order + url?: string; + memo?: string; + has_signature?: string; + validity_period?: string; + ex_rate?: string; + usdc_rate?: string; + is_need_file?: string; + gate_bank_id?: string; + gate_bank_name?: string; + refresh_limit?: number; + refresh_limit_msg?: string; + }; + timestamp: number; +} +⋮---- +type: string; // BUY (on-ramp) or SELL (off-ramp) +⋮---- +rate_reci: string; // Reciprocal of the exchange rate +⋮---- +order_type: string; // FIAT or STABLE +quote_token: string; // Quote token required when placing an order +⋮---- +export type CreateOTCFiatOrderResp = OTCActionResp; +⋮---- +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; + timestamp: number; +} +⋮---- +export interface OTCBankListItem { + id: string; // Bank ID (required for order placement) + bank_account_name: string; + bank_name: string; + bank_country?: string; + bank_address?: string; + bank_code?: string; + branch_code?: string; + iban?: string; + swift?: string; + remittance_line_number?: string; + agent_bank_name?: string; + agent_bank_swift?: string; + submit_time?: string; + update_time?: string; + status?: string; + documentation_file_type?: string; + memo?: string; + /** 1 = default bank card, 0 = not default */ + is_default?: 0 | 1; + bank_id?: string; + documentation_file_key_url?: string; +} +⋮---- +id: string; // Bank ID (required for order placement) +⋮---- +/** 1 = default bank card, 0 = not default */ +⋮---- +export interface GetOTCBankListResp { + code: number; + message: string; + data: { + lists: OTCBankListItem[]; + }; + timestamp: number; +} +⋮---- +export interface CreateOTCBankResp { + code: number; + message: string; + data: { + bank_id: number; + status: number; + }; + timestamp?: number; +} +⋮---- +export interface OTCBankSupplementChecklistItem { + description: string; + code?: string; + zh?: string; + en?: string; + required?: boolean; +} +⋮---- +export interface GetOTCBankSupplementChecklistResp { + code: number; + message: string; + data: { + user_type: 'personal' | 'enterprise'; + items: OTCBankSupplementChecklistItem[]; + }; + timestamp?: number; +} +⋮---- +export type MarkOTCOrderAsPaidResp = OTCActionResp; +⋮---- +export type CancelOTCOrderResp = OTCActionResp; +⋮---- +export interface OTCFiatOrderListItem { + time: string; // Current time + timestamp: number; // Current timestamp + order_id: string; + trade_no: string; // Trade number + type: string; // Quote direction buy/sell/all + status: string; // Order Status (includes DISBURSED) + db_status: string; + fiat_currency: string; // Fiat type + fiat_currency_info: { + name: string; + icon: string; + }; + fiat_amount: string; // Fiat amount + crypto_currency: string; // Stablecoin + crypto_currency_info: { + name: string; + icon: string; + }; + crypto_amount: string; // Stablecoin amount + rate: string; // Exchange rate + transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) + reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders + gate_bank_account_iban: string; // Bank account + promotion_code: string; // Promotion code +} +⋮---- +time: string; // Current time +timestamp: number; // Current timestamp +⋮---- +trade_no: string; // Trade number +type: string; // Quote direction buy/sell/all +status: string; // Order Status (includes DISBURSED) +⋮---- +fiat_currency: string; // Fiat type +⋮---- +fiat_amount: string; // Fiat amount +crypto_currency: string; // Stablecoin +⋮---- +crypto_amount: string; // Stablecoin amount +rate: string; // Exchange rate +transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) +reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders +gate_bank_account_iban: string; // Bank account +promotion_code: string; // Promotion code +⋮---- +export interface GetOTCFiatOrderListResp { + code: number; + message: string; + data: { + pn: number; + ps: number; + total_pn: number; + count: number; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; + }; +} +⋮---- +/** v4.106.158: was `list` */ +⋮---- +export interface OTCStablecoinOrderListItem { + id: number; // Order ID + trade_no: string; // Transaction reference number + pay_coin: string; // Payment currency + pay_amount: string; // Payment amount + get_coin: string; // Received currency + get_amount: string; // Received amount + rate: string; // Exchange rate + rate_reci: string; // Reciprocal of the exchange rate + status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed + create_timest: number; // Timestamp + create_time: string; // Created time + pay_icon?: string; + get_icon?: string; +} +⋮---- +id: number; // Order ID +trade_no: string; // Transaction reference number +pay_coin: string; // Payment currency +pay_amount: string; // Payment amount +get_coin: string; // Received currency +get_amount: string; // Received amount +rate: string; // Exchange rate +rate_reci: string; // Reciprocal of the exchange rate +status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed +create_timest: number; // Timestamp +create_time: string; // Created time +⋮---- +export interface GetOTCStablecoinOrderListResp { + code: number; + message: string; + data: { + total: number; + page_size: number; + page_number: number; + total_page: number; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; + }; +} +⋮---- +/** v4.106.158: was `list` */ +⋮---- +export interface OTCFiatOrderDetail { + order_id: string; // Order ID + uid: string; // User ID + type: string; // Order Type + fiat_currency: string; // Fiat type + fiat_amount: string; // Fiat amount + crypto_currency: string; // Stablecoin + crypto_amount: string; // Stablecoin amount + rate: string; // Exchange rate + transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) + reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders + status: string; // Status + db_status: string; + create_time: string; // Created time + memo: string; // Cancellation or rejection reason + side: string; // Quote direction + promotion_code: string; // Promotion code + trade_no: string; // Trade number +} +⋮---- +order_id: string; // Order ID +uid: string; // User ID +type: string; // Order Type +fiat_currency: string; // Fiat type +fiat_amount: string; // Fiat amount +crypto_currency: string; // Stablecoin +crypto_amount: string; // Stablecoin amount +rate: string; // Exchange rate +transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) +reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders +status: string; // Status +⋮---- +create_time: string; // Created time +memo: string; // Cancellation or rejection reason +side: string; // Quote direction +promotion_code: string; // Promotion code +trade_no: string; // Trade number +⋮---- +export interface GetOTCFiatOrderDetailResp { + message: string; + code: number; + data: OTCFiatOrderDetail; +} +⋮---- +export interface CreateOTCUploadPreUploadFields { + key?: string; + content_type?: string; + x_amz_credential?: string; + x_amz_algorithm?: string; + x_amz_date?: string; + policy?: string; + x_amz_signature?: string; +} +⋮---- +export interface CreateOTCUploadPreUploadData { + file_key?: string; + url?: string; + fields?: CreateOTCUploadPreUploadFields; + expires_in?: number; +} +⋮---- +export interface CreateOTCUploadPreUploadResp { + code?: number; + message?: string; + timestamp?: number; + data?: CreateOTCUploadPreUploadData; +} -const ws = new WebsocketClient(wsConfig); +================ +File: src/types/request/futures.ts +================ +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ +⋮---- +export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; +⋮---- +export interface GetFuturesOrderBookReq { + settle: FuturesSettle; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; +} +⋮---- +export interface GetFuturesTradesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; +} +⋮---- +export interface GetFuturesCandlesReq { + settle: FuturesSettle; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; +} +⋮---- +export interface GetFuturesStatsReq { + settle: FuturesSettle; + contract: string; + from?: number; + interval?: string; + limit?: number; +} +⋮---- +export interface GetFundingRatesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + from?: number; + to?: number; +} +⋮---- +export interface BatchFundingRatesReq { + settle: 'btc' | 'usdt' | 'usd1'; + contracts: string[]; +} +⋮---- +export interface GetLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; +} +⋮---- +export interface GetRiskLimitTiersReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; +} +⋮---- +export interface GetRiskLimitTableReq { + settle: FuturesSettle; + table_id: string; +} +⋮---- +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout +⋮---- +| 'dividend'; // v4.106.147: dividend payout +⋮---- +export interface GetFuturesAccountBookReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: FuturesAccountBookType; +} +⋮---- +export interface GetFuturesADLRiskStatesReq { + settle: 'btc' | 'usdt' | 'usd1'; +} +⋮---- +export interface GetFuturesPositionsReq { + settle: FuturesSettle; + holding?: boolean; + limit?: number; // deprecated, use positions_limit instead + positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 + offset?: number; + position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support + hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +} +⋮---- +limit?: number; // deprecated, use positions_limit instead +positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 +⋮---- +position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support +hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +⋮---- +export interface UpdateDualModePositionMarginReq { + settle: FuturesSettle; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} +⋮---- +export interface UpdateDualModePositionLeverageReq { + settle: FuturesSettle; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} +⋮---- +export interface SubmitFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + tpsl_tp_trigger_price?: string; + tpsl_sl_trigger_price?: string; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; + pos_margin_mode?: 'isolated' | 'cross'; +} +⋮---- +/** BBO price type for the take-profit leg */ +⋮---- +/** BBO price type for the stop-loss leg */ +⋮---- +export interface GetFuturesOrdersReq { + settle: FuturesSettle; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} +⋮---- +export interface DeleteAllFuturesOrdersReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + side?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} +⋮---- +export interface GetFuturesOrdersByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} +⋮---- +export interface UpdateFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + order_id: string; + size?: number; + price?: string; + amend_text?: string; +} +⋮---- +export interface GetFuturesTradingHistoryReq { + settle: FuturesSettle; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} +⋮---- +export interface GetFuturesTradingHistoryByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + role?: 'maker' | 'taker'; +} +⋮---- +export interface GetFuturesPositionHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} +⋮---- +export interface GetFuturesLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + at?: number; +} +⋮---- +export interface SubmitFuturesTriggeredOrderReq { + initial: { + contract: string; + size?: number; + /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ + amount?: string; + price: string; // Required: Order price. Set to 0 to use market price + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price: string; // Required: Price value for price trigger + rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) + expiration?: number; + }; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + settle: FuturesSettle; +} +⋮---- +/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ +⋮---- +price: string; // Required: Order price. Set to 0 to use market price +⋮---- +price: string; // Required: Price value for price trigger +rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +⋮---- +export interface GetFuturesAutoOrdersReq { + settle: FuturesSettle; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} +⋮---- +/** + * Modify contract order parameters + */ +export interface BatchAmendOrderReq { + order_id?: number; // Order id, order_id and text must contain at least one + text?: string; // User-defined order text, at least one of order_id and text must be passed + size?: number; // The new order size, including the executed order size + price?: string; // New order price + amend_text?: string; // Custom info during amending order +} +⋮---- +order_id?: number; // Order id, order_id and text must contain at least one +text?: string; // User-defined order text, at least one of order_id and text must be passed +size?: number; // The new order size, including the executed order size +price?: string; // New order price +amend_text?: string; // Custom info during amending order +⋮---- +// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request +export interface GetFuturesPositionCloseHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} +⋮---- +// v4.104.6: New GET /futures/{settle}/insurance endpoint request +export interface GetFuturesInsuranceReq { + settle: FuturesSettle; + limit?: number; +} +⋮---- +export interface UpdateFuturesPriceTriggeredOrderReq { + settle: FuturesSettle; + order_id: number | string; + contract?: string; + size?: number; + /** Same semantics as `size` (decimal contract size) */ + amount?: string; + price?: string; + /** When fully closing in single-position mode, set true */ + close?: boolean; + trigger_price?: string; + price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price + auto_size?: string; // Not required in single position mode +} +⋮---- +/** Same semantics as `size` (decimal contract size) */ +⋮---- +/** When fully closing in single-position mode, set true */ +⋮---- +price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price +auto_size?: string; // Not required in single position mode +⋮---- +/** GET /futures/{settle}/get_leverage/{contract} — v4.106.43: pos_margin_mode and dual_side required */ +export interface GetFuturesContractLeverageReq { + settle: FuturesSettle; + contract: string; + pos_margin_mode: 'isolated' | 'cross'; + dual_side: 'dual_long' | 'dual_short'; +} +⋮---- +/** Trail order (autoorder/v1/trail) request types */ +export interface CreateTrailOrderReq { + settle: 'btc' | 'usdt'; + contract: string; + amount: string; + activation_price?: string; + is_gte?: boolean; + price_type?: 1 | 2 | 3; + price_offset?: string; + reduce_only?: boolean; + position_related?: boolean; + text?: string; + pos_margin_mode?: string; + position_mode?: string; +} +⋮---- +export interface TerminateTrailOrderReq { + settle: 'btc' | 'usdt'; + id?: number; + text?: string; +} +⋮---- +export interface BatchTerminateTrailOrdersReq { + settle: 'btc' | 'usdt'; + contract?: string; + related_position?: 1 | 2; +} +⋮---- +export interface GetTrailOrderListReq { + settle: 'btc' | 'usdt'; + contract?: string; + is_finished?: boolean; + start_at?: number; + end_at?: number; + page_num?: number; + page_size?: number; + sort_by?: 1 | 2; + hide_cancel?: boolean; + related_position?: 1 | 2; + sort_by_trigger?: boolean; + reduce_only?: 1 | 2; + side?: 1 | 2; +} +⋮---- +export interface GetTrailOrderDetailReq { + settle: 'btc' | 'usdt'; + id: number; +} +⋮---- +export interface UpdateTrailOrderReq { + settle: 'btc' | 'usdt'; + id: number; + amount?: string; + activation_price?: string; + is_gte_str?: string; + price_type?: 0 | 1 | 2 | 3; + price_offset?: string; +} +⋮---- +export interface GetTrailOrderChangeLogReq { + settle: 'btc' | 'usdt'; + id: number; + page_num?: number; + page_size?: number; +} +⋮---- +/** Chase limit order (autoorder/v1/chase) request types */ +export interface CreateChaseOrderReq { + settle: FuturesSettle; + contract: string; + amount: string; + price_limit: string; + offset_limit?: string; + reduce_only?: boolean; + text?: string; + is_dual_mode?: boolean; + price_type?: number; + price_gap_type?: number; + price_gap_value?: string; + pos_margin_mode?: 'isolated' | 'cross' | string; + position_mode?: string; +} +⋮---- +export interface StopChaseOrderReq { + settle: FuturesSettle; + id?: string; + text?: string; +} +⋮---- +export interface StopAllChaseOrdersReq { + settle: FuturesSettle; + contract?: string; + pos_margin_mode?: 'isolated' | 'cross' | string; +} +⋮---- +export interface GetChaseOrdersReq { + settle: FuturesSettle; + contract?: string; + is_finished?: boolean; + start_at?: number; + end_at?: number; + page_num?: number; + page_size?: number; + /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ + sort_by: 1 | 2; + hide_cancel?: boolean; + reduce_only?: 0 | 1 | 2; + side?: 0 | 1 | 2; +} +⋮---- +/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ +⋮---- +export interface GetChaseOrderDetailReq { + settle: FuturesSettle; + id: string; +} +================ +File: src/types/response/futures.ts +================ +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ +⋮---- +export interface FuturesOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} +⋮---- +export interface FuturesTrade { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; // Deprecated +} +⋮---- +is_internal?: boolean; // Deprecated +⋮---- +export interface FuturesCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; +} +⋮---- +export interface PremiumIndexKLine { + t: number; + c: string; + h: string; + l: string; + o: string; +} +⋮---- +export interface FuturesTicker { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; // Deprecated + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; + lowest_size: string; + highest_size: string; +} +⋮---- +quanto_base_rate?: string; // Deprecated +⋮---- +export interface BatchFundingRatesResponse { + contract?: string; + data?: { t: number; r: string }[]; +} +⋮---- +export interface FuturesStats { + time: number; + lsr_taker: number; + lsr_account: number; + long_liq_size: number; + long_liq_amount: number; + long_liq_usd: number; + long_liq_usd_new?: number; + short_liq_size: number; + short_liq_amount: number; + short_liq_usd: number; + short_liq_usd_new?: number; + open_interest: number; + open_interest_usd: number; + top_lsr_account: number; + top_lsr_size: number; + top_long_size?: number; + top_short_size?: number; + long_taker_size?: number; + short_taker_size?: number; + top_long_account?: number; + top_short_account?: number; + long_users?: number; + short_users?: number; +} +⋮---- +export interface IndexConstituents { + index: string; + constituents: { + exchange: string; + symbols: string[]; + }[]; +} +⋮---- +export interface LiquidationHistoryRecord { + time: number; + contract: string; + size: number; + order_size: number; + order_price: string; + fill_price: string; + left: number; +} +⋮---- +export interface RiskLimitTier { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; // First-tier maintenance margin rate requirement + leverage_max: string; + contract: string; +} +⋮---- +maintenance_rate: string; // First-tier maintenance margin rate requirement +⋮---- +export interface FuturesAccount { + total: string; // Balance, only applicable to classic contract account + unrealised_pnl: string; + position_margin?: string; // Deprecated + order_margin: string; // Initial margin for all pending orders + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic?: boolean; // Deprecated + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + cross_margin_balance: string; + cross_mmr: string; + cross_imr: string; + isolated_position_margin: string; + enable_new_dual_mode?: boolean; // Deprecated + margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + enable_tiered_mm: boolean; + funding_balance?: string; +} +⋮---- +total: string; // Balance, only applicable to classic contract account +⋮---- +position_margin?: string; // Deprecated +order_margin: string; // Initial margin for all pending orders +⋮---- +position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) +⋮---- +enable_evolved_classic?: boolean; // Deprecated +⋮---- +enable_new_dual_mode?: boolean; // Deprecated +margin_mode: number; // 0: classic future account or Classic Spot Margin Mode of unified account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +export type FuturesAccountBookRecordType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; +⋮---- +export interface FuturesAccountBookRecord { + time: number; + change: string; + balance: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookRecordType; + text: string; + contract?: string; + trade_id: string; + id: string; +} +⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +⋮---- +export interface FuturesOrder { + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'poc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'stp'; + status?: 'open' | 'finished'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + is_close?: boolean; + reduce_only?: boolean; + is_reduce_only?: boolean; + is_liq?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + left?: number; + fill_price?: string; + text?: string; + tkfr?: string; + mkfr?: string; + refu?: number; + auto_size?: 'close_long' | 'close_short'; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + amend_text?: string; + biz_info?: string; + /** Read-only; order notional in settle currency (API response only; omit from order requests). */ + order_value?: string; + /** Read-only; traded value (API response only; omit from order requests). */ + trade_value?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + tpsl_tp_trigger_price?: string; + tpsl_sl_trigger_price?: string; + tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg + tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg + pos_margin_mode?: string; +} +⋮---- +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- +/** Read-only; order notional in settle currency (API response only; omit from order requests). */ +⋮---- +/** Read-only; traded value (API response only; omit from order requests). */ +⋮---- +tpsl_tp_bbo_type?: string; // v4.106.93: BBO price type for take-profit leg +tpsl_sl_bbo_type?: string; // v4.106.93: BBO price type for stop-loss leg +⋮---- +/** Item shape for `GET /futures/{settle}/orders_timerange` (differs from {@link FuturesOrder} in field types). */ +export interface FuturesOrderTimerange { + id?: number; + user?: number; + create_time?: number; + update_time?: string; + finish_time?: string; + contract: string; + size: string; + iceberg?: string; + is_close?: boolean; + is_reduce_only?: boolean; + is_liq?: boolean; + left?: string; + fill_price?: string; + tkfr?: string; + mkfr?: string; + refu?: number; + amend_text?: string; + pid?: number; + market_order_slip_ratio?: string; + pos_margin_mode?: string; +} +⋮---- +export interface FuturesPosition { + user?: number; + contract?: string; + size?: number; + leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode + risk_limit?: string; + leverage_max?: string; // Max leverage based on current position size + maintenance_rate?: string; // Tiered maintenance margin rate calculation + value?: string; + margin?: string; + entry_price?: string; + liq_price?: string; // Estimated liquidation price for reference only + liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management + mark_price?: string; + initial_margin?: string; // Expanded scope description + maintenance_margin?: string; // Expanded scope description + unrealised_pnl?: string; + realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees + pnl_pnl?: string; // Settlement P&L + pnl_fund?: string; // Funding fee P&L + pnl_fee?: string; // Total trading fees + history_pnl?: string; // All historical settlement P&L + last_close_pnl?: string; + realised_point?: string; + history_point?: string; + adl_ranking?: number; + pending_orders?: number; + close_order?: { + id?: number; + price?: string; + is_liq?: boolean; + } | null; + mode?: 'single' | 'dual_long' | 'dual_short'; + cross_leverage_limit?: string; // Simplified description + update_time?: number; + update_id?: number; + open_time?: number; + settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support + isolated_margin?: string; // v4.104.6: Add isolated_margin field + pid?: number; // v4.106.0: Sub-position ID + hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status + hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy + unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy +} +⋮---- +leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode +⋮---- +leverage_max?: string; // Max leverage based on current position size +maintenance_rate?: string; // Tiered maintenance margin rate calculation +⋮---- +liq_price?: string; // Estimated liquidation price for reference only +liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management +⋮---- +initial_margin?: string; // Expanded scope description +maintenance_margin?: string; // Expanded scope description +⋮---- +realised_pnl?: string; // Detailed breakdown including settlement, funding fees, and trading fees +pnl_pnl?: string; // Settlement P&L +pnl_fund?: string; // Funding fee P&L +pnl_fee?: string; // Total trading fees +history_pnl?: string; // All historical settlement P&L +⋮---- +cross_leverage_limit?: string; // Simplified description +⋮---- +settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support +isolated_margin?: string; // v4.104.6: Add isolated_margin field +pid?: number; // v4.106.0: Sub-position ID +hedge_status?: 'partial_hedged' | 'full_hedged'; // v4.106.97: Delta-neutral hedging status +hedged_size?: string; // v4.106.97: Hedged size under Delta-neutral strategy +unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy +⋮---- +export interface FuturesTradingHistoryRecord { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; + close_size: number; +} +⋮---- +export interface FuturesPositionHistoryRecord { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; + accum_size: string; +} +⋮---- +export interface FuturesLiquidationHistoryRecord { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + liq_price: string; + mark_price: string; + order_id: number; + order_price: string; + fill_price: string; + left: number; +} +export interface FuturesAutoDeleveragingHistoryRecord { + time: number; + user: number; + order_id: number; + contract: string; + leverage: string; // Clarified for better understanding of margin modes + cross_leverage_limit: string; // Clarified for better understanding of margin modes + entry_price: string; + fill_price: string; + trade_size: number; + position_size: number; +} +⋮---- +leverage: string; // Clarified for better understanding of margin modes +cross_leverage_limit: string; // Clarified for better understanding of margin modes +⋮---- +export interface DeleteFuturesBatchOrdersResp { + user_id: number; + id: string; + succeeded: boolean; + message: string; +} +⋮---- +export interface FuturesContract { + name?: string; + /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ + contract_type?: string; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; // First-tier maintenance margin rate requirement + mark_type?: 'internal' | 'index'; // Deprecated + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; // Minimum unit of mark price + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + funding_rate?: string; + funding_rate_indicative?: string; + funding_interval?: number; + funding_next_apply?: number; + funding_offset?: number; + /** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ + interest_rate?: string; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: string | number; // API returns string e.g. "1" + order_size_max?: string | number; // API returns string e.g. "1000000" + orderbook_id?: number; + trade_id?: number; + trade_size?: string | number; // API returns string + position_size?: string | number; // API returns string + short_users?: number; + long_users?: number; + funding_impact_value?: string; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; + enable_bonus?: boolean; + enable_credit?: boolean; + /** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ + enable_decimal?: boolean; + /** Whether the newly listed contract uses the mark price circuit breaker */ + enable_circuit_breaker?: boolean; + create_time?: number; + launch_time?: number; + delisting_time?: number; + delisted_time?: number; + status?: string; // e.g. "trading" + funding_cap_ratio?: string; // Deprecated + funding_rate_limit?: string; // v4.106.4: Funding rate cap value + market_order_slip_ratio?: string; + market_order_size_max?: string; +} +⋮---- +/** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ +⋮---- +quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" +⋮---- +maintenance_rate?: string; // First-tier maintenance margin rate requirement +mark_type?: 'internal' | 'index'; // Deprecated +⋮---- +mark_price_round?: string; // Minimum unit of mark price +⋮---- +/** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ +⋮---- +order_size_min?: string | number; // API returns string e.g. "1" +order_size_max?: string | number; // API returns string e.g. "1000000" +⋮---- +trade_size?: string | number; // API returns string +position_size?: string | number; // API returns string +⋮---- +/** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ +⋮---- +/** Whether the newly listed contract uses the mark price circuit breaker */ +⋮---- +status?: string; // e.g. "trading" +funding_cap_ratio?: string; // Deprecated +funding_rate_limit?: string; // v4.106.4: Funding rate cap value +⋮---- +/** GET /futures/{settle}/adl_risk_states */ +export interface FuturesADLRiskState { + state: 'normal' | 'warning' | 'adl_risk'; + calculated_at_ms: number; +} +⋮---- +export interface FuturesADLRiskStates { + settle: string; + states: Record; +} +⋮---- +/** GET /futures/{settle}/get_leverage/{contract} — API field name is `Lever` */ +export interface FuturesContractLeverageInfo { + Lever: string; +} +⋮---- +/** Create/amend response for futures price-trigger orders (`/futures/{settle}/price_orders`). */ +export interface TriggerOrderResponse { + id?: number; + /** + * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. + */ + id_string?: string; +} +⋮---- +/** + * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. + */ +⋮---- +export interface FuturesPriceTriggeredOrder { + initial: { + contract: string; + size?: number; + price?: string; + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + is_reduce_only?: boolean; + is_close?: boolean; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price?: string; + rule?: 1 | 2; + expiration?: number; + }; + id?: number; // int64 price-triggered order id + /** + * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. + */ + id_string?: string; + user?: number; + create_time?: number; + finish_time?: number; + trade_id?: number; + status?: 'open' | 'finished' | 'inactive' | 'invalid'; + finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; + reason?: string; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + me_order_id?: number; // int64 +} +⋮---- +id?: number; // int64 price-triggered order id +/** + * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. + */ +⋮---- +me_order_id?: number; // int64 +⋮---- +export interface FuturesDeliveryContract { + name?: string; + /** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ + contract_type?: string; + underlying?: string; + cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; // First-tier maintenance margin rate requirement + mark_type?: 'internal' | 'index'; // Deprecated + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; // Minimum unit of mark price + basis_rate?: string; + basis_value?: string; + basis_impact_value?: string; + settle_price?: string; + settle_price_interval?: number; + settle_price_duration?: number; + expire_time?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; +} +⋮---- +/** Contract classification (e.g. stocks, metals, indices, forex, commodities). */ +⋮---- +quanto_multiplier?: string; // Conceptually renamed to "contract multiplier" +⋮---- +maintenance_rate?: string; // First-tier maintenance margin rate requirement +mark_type?: 'internal' | 'index'; // Deprecated +⋮---- +mark_price_round?: string; // Minimum unit of mark price +⋮---- +export interface BatchAmendOrderResp { + succeeded: boolean; + label?: string; + detail?: string; + id: number; + user: number; + create_time: number; + finish_time?: number; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'poc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'reduce_out' + | 'stp'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc' | 'fok'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + stp_act: 'co' | 'cn' | 'cb' | '-'; + stp_id: number; +} +⋮---- /** - * Subscribing to data: - **/ - -const userOrders = { - topic: 'spot.orders', - payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], -}; - -const userTrades = { - topic: 'spot.usertrades', - payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], -}; - -const userPriceOrders = { - topic: 'spot.priceorders', - payload: ['!all'], -}; - -// subscribe to multiple topics at once -ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4'); - -// and/or subscribe to individual topics on demand -ws.subscribe( - { - topic: 'spot.priceorders', - payload: ['!all'], - }, - 'spotV4', -); - -// Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above) -ws.subscribe('spot.balances', 'spotV4'); - + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- /** - * Handling events: - **/ - -// Listen to events coming from websockets. This is the primary data source -ws.on('update', (data) => { - console.log('data', data); -}); - -// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) -ws.on('open', ({ wsKey, event }) => { - console.log('connection open for websocket with ID: ' + wsKey); -}); - -// Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic) -ws.on('response', (response) => { - console.log('response', response); -}); - -// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. -ws.on('close', () => { - console.log('connection closed'); -}); - -// Optional: listen to internal exceptions. Useful for debugging if something weird happens -ws.on('exception', (data) => { - console.error('exception: ', data); -}); - -// Optional: Listen to raw error events. -ws.on('error', (err) => { - console.error('ERR', err); -}); -``` - -See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail. - -### Websocket API - -Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. - -The WebSocket API is available through two approaches, depending on individual preference: - -#### Event Driven API - -The WebSocket API is available in the [WebsocketClient](./src/WebsocketClient.ts) via the `sendWSAPIRequest(wsKey, channel, params)` method. - -Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. - -- event-driven: - - send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))`, fire and forget, don't use await - - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` -- promise-driven: - - send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise - - await each call - - use try/catch blocks to handle promise rejections - -#### REST-like API - -The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the RestClient). - -It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. - -Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. - -```javascript -const { WebsocketAPIClient } = require('gateio-api'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -async function start() { - // Make an instance of the WS API Client - const wsClient = new WebsocketAPIClient({ - apiKey: API_KEY, - apiSecret: API_SECRET, - // Automatically re-auth WS API, if we were auth'd before and get reconnected - reauthWSAPIOnReconnect: true, - }); - - try { - // Connection will authenticate automatically before first request - // Make WebSocket API calls, very similar to a REST API: - - /* ============ SPOT TRADING EXAMPLES ============ */ - - // Submit a new spot order - const newOrder = await wsClient.submitNewSpotOrder({ - text: 't-my-custom-id', - currency_pair: 'BTC_USDT', - type: 'limit', - account: 'spot', - side: 'buy', - amount: '1', - price: '10000', - }); - console.log('Order result:', newOrder.data); - - // Cancel a spot order - const cancelOrder = await wsClient.cancelSpotOrder({ - order_id: '1700664330', - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Cancel result:', cancelOrder.data); - - // Get spot order status - const orderStatus = await wsClient.getSpotOrderStatus({ - order_id: '1700664330', - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Order status:', orderStatus.data); - - /* ============ FUTURES TRADING EXAMPLES ============ */ - - // Submit a new futures order - const newFuturesOrder = await wsClient.submitNewFuturesOrder({ - contract: 'BTC_USDT', - size: 10, - price: '31503.28', - tif: 'gtc', - text: 't-my-custom-id', - }); - console.log('Futures order result:', newFuturesOrder.data); - - // Cancel a futures order - const cancelFuturesOrder = await wsClient.cancelFuturesOrder({ - order_id: '74046514', - }); - console.log('Cancel futures order result:', cancelFuturesOrder.data); - - // Get futures order status - const futuresOrderStatus = await wsClient.getFuturesOrderStatus({ - order_id: '74046543', - }); - console.log('Futures order status:', futuresOrderStatus.data); - } catch (e) { - console.error('WS API Error:', e); - } + * @deprecated - Use FuturesAccount instead + */ +export interface UpdateFuturesDualModeResp { + total: string; + unrealised_pnl: string; + position_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic: boolean; + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; +} +⋮---- +export interface RiskLimitTableTier { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; // First-tier maintenance margin rate requirement + leverage_max: string; + deduction: string; +} +⋮---- +maintenance_rate: string; // First-tier maintenance margin rate requirement +⋮---- +// v4.104.6: New GET /futures/{settle}/insurance endpoint types +export interface FuturesInsuranceHistory { + t: number; + b: string; +} +⋮---- +/** Trail order (autoorder/v1/trail) response types */ +export interface TrailOrder { + id?: number | string; + user_id?: number | string; + user?: number | string; + contract?: string; + settle?: string; + amount?: string; + is_gte?: boolean; + activation_price?: string; + price_type?: number; + price_offset?: string; + text?: string; + reduce_only?: boolean; + position_related?: boolean; + created_at?: number | string; + activated_at?: number | string; + finished_at?: number | string; + create_time?: number | string; + active_time?: number | string; + finish_time?: number | string; + reason?: string; + suborder_text?: string; + is_dual_mode?: boolean; + trigger_price?: string; + suborder_id?: number | string; + side_label?: string; + original_status?: number; + status?: string; + position_side_output?: string; + updated_at?: number | string; + extremum_price?: string; + status_code?: string; + created_at_precise?: string; + finished_at_precise?: string; + activated_at_precise?: string; + status_label?: string; + pos_margin_mode?: string; + position_mode?: string; + error_label?: string; + leverage?: string; + [key: string]: unknown; +} +⋮---- +export interface TrailChangeLog { + updated_at?: number; + amount?: string; + is_gte?: boolean; + activation_price?: string; + price_type?: number; + price_offset?: string; + is_create?: boolean; +} +⋮---- +export interface ChaseOrder { + id?: string; + user?: string; + contract?: string; + settle?: string; + amount?: string; + price_limit?: string; + reduce_only?: boolean; + text?: string; + create_time?: number; + finish_time?: number; + original_status?: number; + status?: string; + reason?: string; + fill_amount?: string; + average_fill_price?: string; + suborder_id?: string; + is_dual_mode?: boolean; + side_label?: string; + position_side_output?: string; + chase_price?: string; + interval_sec?: number; + updated_at?: number; + suborder_price?: string; + suborder_ongoing?: boolean; + suborder_finish_as?: string; + price_type?: number; + price_gap_type?: string; + price_gap_value?: string; + status_code?: string; + create_time_precise?: string; + finish_time_precise?: string; + pos_margin_mode?: string; + position_mode?: string; + leverage?: string; + error_label?: string; +} +⋮---- +export interface CreateChaseOrderResp { + id?: string; +} +⋮---- +export interface StopChaseOrderResp { + order?: ChaseOrder; +} +⋮---- +export interface StopAllChaseOrdersResp { + orders?: ChaseOrder[]; +} +⋮---- +export interface GetChaseOrdersResp { + orders?: ChaseOrder[]; +} +⋮---- +export interface GetChaseOrderDetailResp { + order?: ChaseOrder; } - -start(); -``` - -For more detailed examples using any approach, refer to the [examples](./examples/) folder (e.g. [ws-api-client.ts](./examples/ws-api-client.ts)). - ---- - -## Customise Logging - -Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired. - -```javascript -const { WebsocketClient, DefaultLogger } = require('gateio-api'); - -// Disable all logging on the silly level -DefaultLogger.silly = () => {}; - -const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger); -``` - -## Browser/Frontend Usage - -### Webpack - -Build a bundle using webpack: - -- `npm install` -- `npm run build` -- `npm run pack` - -The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. - -## Use with LLMs & AI - -This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. - -This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. - ---- - -## Used By - -[![Repository Users Preview Image](https://dependents.info/sieblyio/gateio-api/image)](https://github.com/sieblyio/gateio-api/network/dependents) - ---- - - - -### Contributions & Thanks - -Have my projects helped you? Share the love, there are many ways you can show your thanks: - -- Star & share my projects. -- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler -- Have an interesting project? Get in touch & invite me to it. -- Or buy me all the coffee: - - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` -- Sign up with my referral links: - - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 - - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ - - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY - - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 - - - - -### Contributions & Pull Requests - -Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. - - - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) - - ================ File: src/RestClient.ts @@ -14968,6 +14469,7 @@ import { CreateChaseOrderReq, CreateTrailOrderReq, DeleteAllFuturesOrdersReq, + FuturesSettle, GetChaseOrderDetailReq, GetChaseOrdersReq, GetFundingRatesReq, @@ -17098,7 +16600,7 @@ submitFlashSwapOrderPreview( * @returns Promise */ getFuturesContracts(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; offset?: number; }): Promise @@ -17110,7 +16612,7 @@ getFuturesContracts(params: { * @returns Promise */ getFuturesContract(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17169,7 +16671,7 @@ getPremiumIndexKLines( * @returns Promise */ getFuturesTickers(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17211,7 +16713,7 @@ getBatchFundingRates( * }[]> */ getFuturesInsuranceBalanceHistory(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; }): Promise< { @@ -17237,7 +16739,7 @@ getFuturesStats(params: GetFuturesStatsReq): Promise * @returns Promise */ getIndexConstituents(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; index: string; }): Promise ⋮---- @@ -17274,7 +16776,7 @@ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise * @returns Promise */ getFuturesAccount(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; }): Promise ⋮---- /** @@ -17308,7 +16810,7 @@ getFuturesPositions( * @returns Promise */ getFuturesPosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17321,7 +16823,7 @@ getFuturesPosition(params: { * @returns Promise */ updateFuturesMargin(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; change: string; }): Promise @@ -17344,7 +16846,7 @@ updateFuturesMargin(params: { * @returns Promise */ updateFuturesLeverage(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; leverage: string; cross_leverage_limit?: string; @@ -17382,7 +16884,7 @@ updateFuturesPositionMode(params: { * @returns Promise */ updatePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17396,7 +16898,7 @@ updatePositionRiskLimit(params: { * @returns Promise */ updateFuturesDualMode(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; dual_mode: boolean; }): Promise ⋮---- @@ -17407,7 +16909,7 @@ updateFuturesDualMode(params: { * @returns Promise */ getDualModePosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17446,7 +16948,7 @@ updateDualModePositionLeverage( * @returns Promise */ updateDualModePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17521,7 +17023,7 @@ getFuturesOrdersByTimeRange( */ submitFuturesBatchOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- @@ -17535,7 +17037,7 @@ submitFuturesBatchOrders(params: { * @returns Promise */ getFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; }): Promise ⋮---- @@ -17549,7 +17051,7 @@ getFuturesOrder(params: { */ cancelFuturesOrder(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise @@ -17629,7 +17131,7 @@ getFuturesAutoDeleveragingHistory( * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; timeout: number; contract?: string; }): Promise< @@ -17641,7 +17143,7 @@ setFuturesOrderCancelCountdown(params: { * @returns Promise */ getFuturesUserTradingFees(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17657,7 +17159,7 @@ getFuturesUserTradingFees(params: { */ batchCancelFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orderIds: string[]; }): Promise ⋮---- @@ -17674,7 +17176,7 @@ batchCancelFuturesOrders(params: { */ batchUpdateFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: BatchAmendOrderReq[]; }): Promise ⋮---- @@ -17715,7 +17217,7 @@ getFuturesAutoOrders( * @returns Promise */ cancelAllOpenFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17726,7 +17228,7 @@ cancelAllOpenFuturesOrders(params: { * @returns Promise */ getFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- @@ -17737,13 +17239,16 @@ getFuturesPriceTriggeredOrder(params: { * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ @@ -20118,27 +19623,582 @@ createStockTransaction( ): Promise>> ⋮---- /** - * Query supported stock exchanges - * - * @returns Promise with exchange list - */ -getStockExchanges(): Promise>> -⋮---- + * Query supported stock exchanges + * + * @returns Promise with exchange list + */ +getStockExchanges(): Promise>> +⋮---- +/** + * Query stock fee rates + * + * Maker/taker fee fields apply to Japanese and Korean stocks. + * + * @returns Promise with fee rate list by VIP level + */ +getStockFeeRate(): Promise>> + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Gate.com (Gate.io) REST APIs, WebSockets & WebSocket API + +

+ + + + SDK Logo + + +

+ +[![npm version](https://img.shields.io/npm/v/gateio-api)][1] +[![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] +[![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] +[![Build & Test](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/sieblyio/gateio-api/actions/workflows/e2etest.yml) +[![last commit](https://img.shields.io/github/last-commit/sieblyio/gateio-api)][1] +[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/gateio-api) + +[1]: https://www.npmjs.com/package/gateio-api + +Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST APIs and WebSockets: + +- Professional, robust & performant Gate.com SDK with extensive production use in live trading environments. +- Extensive integration with Gate.com (Gate.io) REST APIs and WebSockets. +- Complete TypeScript support (with type declarations for most API requests & responses). + - Strongly typed requests and responses. + - Automated end-to-end tests ensuring reliability. +- Actively maintained with a modern, promise-driven interface. +- Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC Trading APIs. + - Unified RestClient for all Gate.com trading products. + - Strongly typed on most requests and responses. + - Support for Cross-Exchange (CrossEx) trading across multiple exchanges + - Support for Alpha account trading (meme tokens and new listings) + - Support for OTC (fiat and stablecoin) trading +- Support for seamless API authentication for private Gate.com REST API and WebSocket calls. +- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. + - Event driven messaging. + - Smart websocket persistence with automatic reconnection handling. + - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. + - Automatically handle listenKey persistence and expiration/refresh. + - Emit `reconnected` event when dropped connection is restored. + - Support for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha & OTC. +- WebSocket API for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & CrossEx. + - Automatic connectivity via existing WebsocketClient, just call sendWSAPIRequest to trigger a request. + - Automatic authentication, just call sendWSAPIRequest with channel & parameters. + - Choose between two interfaces for WS API communication: + - Event-driven interface, fire & forget via sendWSAPIRequest and receive async replies via wsClient's event emitter. + - Promise-driven interface, simply use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. +- Heavy automated end-to-end testing with real API calls. +- Proxy support via axios integration. +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +- QuickStart Guide: https://siebly.io/sdk/gate/javascript +- Gate JavaScript Tutorial: https://siebly.io/sdk/gate/javascript/tutorial + +## Table of Contents + +- [Installation](#installation) +- [Examples](#examples) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation](#documentation) +- [Structure](#structure) +- [Usage](#usage) + - [REST API Client](#rest-api) + - [WebSocket Client](#websockets) + - [WebSocket Data Streams](#websocket-data-streams) + - [WebSocket API](#websocket-api) + - [Event Driven API](#event-driven-api) + - [REST-like API](#rest-like-api) +- [Customise Logging](#customise-logging) +- [Browser/Frontend Usage](#browserfrontend-usage) + - [Webpack](#webpack) +- [LLMs & AI](#use-with-llms--ai) +- [Used By](#used-by) +- [Contributions & Thanks](#contributions--thanks) + +## Installation + +`npm install --save gateio-api` + +## Examples + +Refer to the [examples](./examples) folder for implementation demos, including: + +- **REST API Examples**: spot trading, futures trading, account management +- **WebSocket Examples**: public market data streams, private account data, WebSocket API usage +- **Spot Trading**: comprehensive spot market examples +- **Futures Trading**: perpetual and delivery futures examples +- **WebSocket API**: both event-driven and promise-driven approaches + +## Issues & Discussion + +- Issues? Check the [issues tab](https://github.com/sieblyio/gateio-api/issues). +- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. +- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) + + + +## Related Projects + +Check out our JavaScript/TypeScript/Node.js SDKs & Projects: + +- Visit our website: [https://Siebly.io](https://siebly.io/) +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) + - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) +- Try my misc utilities: + - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) + - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) +- Check out my examples: + - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Gate.com's API documentation, or check the type definition in each class within this repository. + +### API Documentation Links + +- [Gate.com/gate.io API Documentation](https://www.gate.com/docs/developers/apiv4/en/) + - [Spot Trading API](https://www.gate.com/docs/developers/apiv4/en/#spot-new) + - [Margin Trading API](https://www.gate.com/docs/developers/apiv4/en/#margin-new) + - [Futures Trading API](https://www.gate.com/docs/developers/apiv4/en/#futures-new) + - [Options Trading API](https://www.gate.com/docs/developers/apiv4/en/#options-new) + - [CrossEx Trading API](https://www.gate.com/docs/developers/apiv4/en/#crossex) + - [Alpha Trading API](https://www.gate.com/docs/developers/apiv4/en/#alpha) + - [OTC Trading API](https://www.gate.com/docs/developers/apiv4/en/#otc) + - [WebSocket API](https://www.gate.com/docs/developers/apiv4/en/#websocket-api) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/gateio-api) + +## Structure + +This project uses typescript. Resources are stored in 2 key structures: + +- [src](./src) - the whole connector written in typescript +- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! + +--- + +# Usage + +Create API credentials on Gate.com's website: + +- [Gate.com API Key Management](https://www.gate.com/myaccount/api_key_manage) + +## REST API + +The SDK provides a unified `RestClient` for all Gate.com trading products including Spot, Margin, Perpetual Futures, Delivery Futures, Options, CrossEx, Alpha, and OTC Trading. This single client handles all REST API operations across all trading markets. + +To use any of Gate.com's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the `RestClient`: + +```javascript +const { RestClient } = require('gateio-api'); + +const API_KEY = 'xxx'; +const PRIVATE_KEY = 'yyy'; + +const client = new RestClient({ + apiKey: API_KEY, + apiSecret: PRIVATE_KEY, +}); + +// Spot Trading Example +client + .getSpotTicker() + .then((result) => { + console.log('all spot tickers result: ', result); + }) + .catch((err) => { + console.error('spot ticker error: ', err); + }); + +client + .getSpotOrders({ + currency_pair: 'BTC_USDT', + status: 'open', + }) + .then((result) => { + console.log('getSpotOrders result: ', result); + }) + .catch((err) => { + console.error('getSpotOrders error: ', err); + }); + +// CrossEx Trading Example - Trade across multiple exchanges +client + .getCrossExSymbols() + .then((result) => { + console.log('CrossEx symbols: ', result); + }) + .catch((err) => { + console.error('CrossEx error: ', err); + }); + +// Alpha Trading Example - Trade meme tokens and new listings +client + .getAlphaCurrencies() + .then((result) => { + console.log('Alpha currencies: ', result); + }) + .catch((err) => { + console.error('Alpha error: ', err); + }); + +// OTC Trading Example - Fiat and stablecoin trading +client + .createOTCQuote({ + side: 'BUY', + pay_coin: 'USDT', + get_coin: 'USD', + pay_amount: '1000', + create_quote_token: '1', + }) + .then((result) => { + console.log('OTC quote: ', result); + }) + .catch((err) => { + console.error('OTC error: ', err); + }); +``` + +WebSocket TestNet: set `useTestnet: true` on `WebsocketClient`. + +See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. + +## WebSockets + +All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles all Gate.com WebSocket streams with automatic connection management and reconnection. + +Key WebSocket features: + +- Event driven messaging +- Smart WebSocket persistence with automatic reconnection +- Heartbeat mechanisms to detect disconnections +- Automatic resubscription after reconnection +- Support for all Gate.com trading products (Spot, Margin, Futures, Options) +- WebSocket API support for real-time trading operations + +### WebSocket Data Streams + +All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see [WS_KEY_MAP](src/lib/websocket/websocket-util.ts) for a list of supported values). + +Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub. + +Data events are emitted from the WebsocketClient via the `update` event, see example below: + +```javascript +const { WebsocketClient } = require('gateio-api'); + +const API_KEY = 'xxx'; +const PRIVATE_KEY = 'yyy'; + +const wsConfig = { + apiKey: API_KEY, + apiSecret: PRIVATE_KEY, + + /* + The following parameters are optional: + */ + + // Livenet is used by default, use this to enable testnet: + // useTestnet: true + + // how long to wait (in ms) before deciding the connection should be terminated & reconnected + // pongTimeout: 1000, + + // how often to check (in ms) that WS connection is still alive + // pingInterval: 10000, + + // how long to wait before attempting to reconnect (in ms) after connection is closed + // reconnectTimeout: 500, + + // config options sent to RestClient (used for time sync). See RestClient docs. + // restOptions: { }, + + // config for axios used for HTTP requests. E.g for proxy support + // requestOptions: { } +}; + +const ws = new WebsocketClient(wsConfig); + +/** + * Subscribing to data: + **/ + +const userOrders = { + topic: 'spot.orders', + payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], +}; + +const userTrades = { + topic: 'spot.usertrades', + payload: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], +}; + +const userPriceOrders = { + topic: 'spot.priceorders', + payload: ['!all'], +}; + +// subscribe to multiple topics at once +ws.subscribe([userOrders, userTrades, userPriceOrders], 'spotV4'); + +// and/or subscribe to individual topics on demand +ws.subscribe( + { + topic: 'spot.priceorders', + payload: ['!all'], + }, + 'spotV4', +); + +// Some topics don't need params, for those you can just subscribe with a string (or use a topic + payload object as above) +ws.subscribe('spot.balances', 'spotV4'); + /** - * Query stock fee rates - * - * Maker/taker fee fields apply to Japanese and Korean stocks. - * - * @returns Promise with fee rate list by VIP level - */ -getStockFeeRate(): Promise>> + * Handling events: + **/ + +// Listen to events coming from websockets. This is the primary data source +ws.on('update', (data) => { + console.log('data', data); +}); + +// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) +ws.on('open', ({ wsKey, event }) => { + console.log('connection open for websocket with ID: ' + wsKey); +}); + +// Optional: Listen to responses to websocket queries (e.g. the reply after subscribing to a topic) +ws.on('response', (response) => { + console.log('response', response); +}); + +// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. +ws.on('close', () => { + console.log('connection closed'); +}); + +// Optional: listen to internal exceptions. Useful for debugging if something weird happens +ws.on('exception', (data) => { + console.error('exception: ', data); +}); + +// Optional: Listen to raw error events. +ws.on('error', (err) => { + console.error('ERR', err); +}); +``` + +See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail. + +### Websocket API + +Gate.com supports sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. + +The WebSocket API is available through two approaches, depending on individual preference: + +#### Event Driven API + +The WebSocket API is available in the [WebsocketClient](./src/WebsocketClient.ts) via the `sendWSAPIRequest(wsKey, channel, params)` method. + +Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. + +- event-driven: + - send requests via `client.sendWSAPIRequest(wsKey, channel, params).catch(e => console.error('WS API exception for channel', channel, e))`, fire and forget, don't use await + - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` +- promise-driven: + - send requests via `const result = await client.sendWSAPIRequest(wsKey, channel, params)`, which returns a promise + - await each call + - use try/catch blocks to handle promise rejections + +#### REST-like API + +The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the RestClient). + +It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. + +Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. + +```javascript +const { WebsocketAPIClient } = require('gateio-api'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +async function start() { + // Make an instance of the WS API Client + const wsClient = new WebsocketAPIClient({ + apiKey: API_KEY, + apiSecret: API_SECRET, + // Automatically re-auth WS API, if we were auth'd before and get reconnected + reauthWSAPIOnReconnect: true, + }); + + try { + // Connection will authenticate automatically before first request + // Make WebSocket API calls, very similar to a REST API: + + /* ============ SPOT TRADING EXAMPLES ============ */ + + // Submit a new spot order + const newOrder = await wsClient.submitNewSpotOrder({ + text: 't-my-custom-id', + currency_pair: 'BTC_USDT', + type: 'limit', + account: 'spot', + side: 'buy', + amount: '1', + price: '10000', + }); + console.log('Order result:', newOrder.data); + + // Cancel a spot order + const cancelOrder = await wsClient.cancelSpotOrder({ + order_id: '1700664330', + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Cancel result:', cancelOrder.data); + + // Get spot order status + const orderStatus = await wsClient.getSpotOrderStatus({ + order_id: '1700664330', + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Order status:', orderStatus.data); + + /* ============ FUTURES TRADING EXAMPLES ============ */ + + // Submit a new futures order + const newFuturesOrder = await wsClient.submitNewFuturesOrder({ + contract: 'BTC_USDT', + size: 10, + price: '31503.28', + tif: 'gtc', + text: 't-my-custom-id', + }); + console.log('Futures order result:', newFuturesOrder.data); + + // Cancel a futures order + const cancelFuturesOrder = await wsClient.cancelFuturesOrder({ + order_id: '74046514', + }); + console.log('Cancel futures order result:', cancelFuturesOrder.data); + + // Get futures order status + const futuresOrderStatus = await wsClient.getFuturesOrderStatus({ + order_id: '74046543', + }); + console.log('Futures order status:', futuresOrderStatus.data); + } catch (e) { + console.error('WS API Error:', e); + } +} + +start(); +``` + +For more detailed examples using any approach, refer to the [examples](./examples/) folder (e.g. [ws-api-client.ts](./examples/ws-api-client.ts)). + +--- + +## Customise Logging + +Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired. + +```javascript +const { WebsocketClient, DefaultLogger } = require('gateio-api'); + +// Disable all logging on the silly level +DefaultLogger.silly = () => {}; + +const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger); +``` + +## Browser/Frontend Usage + +### Webpack + +Build a bundle using webpack: + +- `npm install` +- `npm run build` +- `npm run pack` + +The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO. + +## Use with LLMs & AI + +This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. + +This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. + +--- + +## Used By + +[![Repository Users Preview Image](https://dependents.info/sieblyio/gateio-api/image)](https://github.com/sieblyio/gateio-api/network/dependents) + +--- + + + +### Contributions & Thanks + +Have my projects helped you? Share the love, there are many ways you can show your thanks: + +- Star & share my projects. +- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler +- Have an interesting project? Get in touch & invite me to it. +- Or buy me all the coffee: + - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` +- Sign up with my referral links: + - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 + - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ + - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 + + + + +### Contributions & Pull Requests + +Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. + + + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) + + ================ File: package.json ================ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/package-lock.json b/package-lock.json index f876e20..78c0677 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 7df721f..e527c0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/src/RestClient.ts b/src/RestClient.ts index 66d6c04..aba932c 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -3548,16 +3548,22 @@ export class RestClient extends BaseRestClient { /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ updateFuturesPriceTriggeredOrder( params: UpdateFuturesPriceTriggeredOrderReq, ): Promise { - const { settle, ...body } = params; - return this.putPrivate(`/futures/${settle}/price_orders/amend`, { - body: body, - }); + const { settle, order_id, ...rest } = params; + return this.putPrivate( + `/futures/${settle}/price_orders/amend/${order_id}`, + { + body: { order_id, ...rest }, + }, + ); } /** diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index ae40631..f2a0cbb 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -79,10 +79,15 @@ export function serializeParams | undefined = {}>( return queryString ? prefixWith + queryString : queryString; } +/** Global TestNet REST host. Gate docs: spot and futures. */ +const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; + const GATE_BASE_URLS: Record = { live: 'https://api.gateio.ws/api/v4', futuresLiveAlternative: 'https://fx-api.gateio.ws/api/v4', - futuresTestnet: 'https://fx-api-testnet.gateio.ws/api/v4', + testnet: GATE_TESTNET_REST_URL, + // Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. + futuresTestnet: GATE_TESTNET_REST_URL, }; export function getRestBaseUrl(restClientOptions: RestClientOptions): string { diff --git a/src/lib/websocket/websocket-util.ts b/src/lib/websocket/websocket-util.ts index e6d1dab..3f938b4 100644 --- a/src/lib/websocket/websocket-util.ts +++ b/src/lib/websocket/websocket-util.ts @@ -101,7 +101,8 @@ export const WS_BASE_URL_MAP: Record< > = { spotV4: { livenet: 'wss://api.gateio.ws/ws/v4/', - testnet: 'NoTestnetForSpotWebsockets!', + // https://www.gate.com/docs/developers/apiv4/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/spot', }, perpFuturesUSDTV4: { livenet: 'wss://fx-ws.gateio.ws/v4/ws/usdt', @@ -121,7 +122,8 @@ export const WS_BASE_URL_MAP: Record< }, optionsV4: { livenet: 'wss://op-ws.gateio.live/v4/ws', - testnet: 'wss://op-ws-testnet.gateio.live/v4/ws', + // https://www.gate.com/docs/developers/options/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/options', }, announcementsV4: { livenet: 'wss://api.gateio.ws/ws/v4/ann', diff --git a/src/types/request/futures.ts b/src/types/request/futures.ts index 7753669..1007c36 100644 --- a/src/types/request/futures.ts +++ b/src/types/request/futures.ts @@ -73,6 +73,19 @@ export interface GetRiskLimitTableReq { table_id: string; } +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout + export interface GetFuturesAccountBookReq { settle: FuturesSettle; contract?: string; @@ -80,16 +93,7 @@ export interface GetFuturesAccountBookReq { offset?: number; from?: number; to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; + type?: FuturesAccountBookType; } export interface GetFuturesADLRiskStatesReq { @@ -136,6 +140,10 @@ export interface SubmitFuturesOrderReq { action_mode?: 'ACK' | 'RESULT' | 'FULL'; tpsl_tp_trigger_price?: string; tpsl_sl_trigger_price?: string; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; pos_margin_mode?: 'isolated' | 'cross'; } diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts index 4a936c8..46d330c 100644 --- a/src/types/response/futures.ts +++ b/src/types/response/futures.ts @@ -165,11 +165,25 @@ export interface FuturesAccount { funding_balance?: string; } +/** v4.106.147: includes `dividend` (dividend payout) */ +export type FuturesAccountBookRecordType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; + export interface FuturesAccountBookRecord { time: number; change: string; balance: string; - type: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookRecordType; text: string; contract?: string; trade_id: string; diff --git a/src/types/response/otc.ts b/src/types/response/otc.ts index ce6319f..c022716 100644 --- a/src/types/response/otc.ts +++ b/src/types/response/otc.ts @@ -147,7 +147,8 @@ export interface GetOTCFiatOrderListResp { ps: number; total_pn: number; count: number; - list: OTCFiatOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; }; } @@ -175,7 +176,8 @@ export interface GetOTCStablecoinOrderListResp { page_size: number; page_number: number; total_page: number; - list: OTCStablecoinOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; }; } diff --git a/src/types/response/stock.ts b/src/types/response/stock.ts index 3770646..4b8058a 100644 --- a/src/types/response/stock.ts +++ b/src/types/response/stock.ts @@ -11,6 +11,32 @@ export type StockCategory = export type StockAssetType = 'STOCK' | 'ETF'; +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; + +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; + export interface StockApiResp { timestamp?: number; data?: T; @@ -53,8 +79,8 @@ export interface StockSymbolItem { symbol_desc?: string; category?: StockCategory | string; asset_type?: StockAssetType; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; icon_link?: string; quote_currency_symbol?: string; @@ -91,8 +117,8 @@ export interface StockSymbolDetailItem { buy_price_protection?: string; slippage_rate?: string; commission_rate?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; symbol_descs?: StockSymbolDescI18n[]; [key: string]: unknown; @@ -118,11 +144,11 @@ export interface StockOrderItem { quote_currency?: string; fx_rate?: string; symbol_desc?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; price_type?: string; side?: number; - status?: number; + status?: StockOrderStatus; volume?: string; fill_volume?: string; price?: string; @@ -152,10 +178,10 @@ export interface StockOrderHistoryItem { fx_rate?: string; symbol_desc?: string; price_type?: string; - status?: number; + status?: StockOrderStatus; status_desc?: string; status_detail?: { title?: string; message?: string } | null; - finish_as?: number; + finish_as?: StockOrderFinishAs; side?: number; time_in_force?: string; volume?: string; @@ -178,7 +204,7 @@ export interface StockPositionItem { quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; - trade_status?: string; + trade_status?: StockTradeStatus; symbol_desc?: string; position_pnl?: string; today_pnl?: string; diff --git a/src/types/shared.ts b/src/types/shared.ts index d451367..0ce4210 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -1,6 +1,7 @@ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' + | 'testnet' | 'futuresTestnet'; // interfaces diff --git a/src/types/websockets/client.ts b/src/types/websockets/client.ts index 7485936..0175304 100644 --- a/src/types/websockets/client.ts +++ b/src/types/websockets/client.ts @@ -21,6 +21,7 @@ export interface WSClientConfigurableOptions { /** Your API secret */ apiSecret?: string; + /** Use the Gate TestNet WebSocket hosts. */ useTestnet?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */