diff --git a/README.md b/README.md index c8ab6e7..af882b9 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,12 @@ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST AP - Strongly typed requests and responses. - Automated end-to-end tests ensuring reliability. - Actively maintained with a modern, promise-driven interface. -- Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options & Announcements APIs. +- 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. @@ -36,8 +39,8 @@ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST AP - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - Automatically handle listenKey persistence and expiration/refresh. - Emit `reconnected` event when dropped connection is restored. - - Support for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & Options. -- WebSocket API for Gate.com Spot, Margin, Perpetual Futures & Delivery Futures. + - 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: @@ -124,6 +127,9 @@ Most methods accept JS objects. These can be populated using parameters specifie - [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) @@ -145,7 +151,7 @@ Create API credentials on Gate.com's website: ## REST API -The SDK provides a unified `RestClient` for all Gate.com trading products including Spot, Margin, Perpetual Futures, Delivery Futures, and Options. This single client handles all REST API operations across all trading markets. +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`: @@ -160,6 +166,7 @@ const client = new RestClient({ apiSecret: PRIVATE_KEY, }); +// Spot Trading Example client .getSpotTicker() .then((result) => { @@ -171,8 +178,8 @@ client client .getSpotOrders({ - currency_pair: 'BTC_USDT', // Specify the currency pair - status: 'open', // Specify the status of the orders to fetch + currency_pair: 'BTC_USDT', + status: 'open', }) .then((result) => { console.log('getSpotOrders result: ', result); @@ -180,6 +187,42 @@ client .catch((err) => { console.error('getSpotOrders error: ', err); }); + +// CrossEx Trading Example - Trade across multiple exchanges +client + .getCrossExSymbols() + .then((result) => { + console.log('CrossEx symbols: ', result); + }) + .catch((err) => { + console.error('CrossEx error: ', err); + }); + +// Alpha Trading Example - Trade meme tokens and new listings +client + .getAlphaCurrencies() + .then((result) => { + console.log('Alpha currencies: ', result); + }) + .catch((err) => { + console.error('Alpha error: ', err); + }); + +// OTC Trading Example - Fiat and stablecoin trading +client + .createOTCQuote({ + side: 'BUY', + pay_coin: 'USDT', + get_coin: 'USD', + pay_amount: '1000', + create_quote_token: '1', + }) + .then((result) => { + console.log('OTC quote: ', result); + }) + .catch((err) => { + console.error('OTC error: ', err); + }); ``` See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index c79255e..a2d1aef 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -49,303 +49,351 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getSystemMaintenanceStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L421) | | GET | `/v1/public/system_info` | -| [submitWithdrawal()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L438) | :closed_lock_with_key: | POST | `/withdrawals` | -| [submitSpotMainAccountTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L452) | :closed_lock_with_key: | POST | `/withdrawals/push` | -| [cancelWithdrawal()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L468) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | -| [getCurrencyChains()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L485) | | GET | `/wallet/currency_chains` | -| [createDepositAddress()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L495) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | -| [getWithdrawalRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L509) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | -| [getDepositRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L523) | :closed_lock_with_key: | GET | `/wallet/deposits` | -| [submitTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L542) | :closed_lock_with_key: | POST | `/wallet/transfers` | -| [submitMainSubTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L554) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | -| [getMainSubTransfers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L568) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | -| [submitSubToSubTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L582) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | -| [getTransferStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L597) | :closed_lock_with_key: | GET | `/wallet/order_status` | -| [getWithdrawalStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L613) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | -| [getSubBalance()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L628) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | -| [getSubMarginBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L643) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | -| [getSubFuturesBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L655) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | -| [getSubCrossMarginBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L668) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | -| [getSavedAddresses()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L680) | :closed_lock_with_key: | GET | `/wallet/saved_address` | -| [getTradingFees()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L690) | :closed_lock_with_key: | GET | `/wallet/fee` | -| [getBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L711) | :closed_lock_with_key: | GET | `/wallet/total_balance` | -| [getSmallBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L720) | :closed_lock_with_key: | GET | `/wallet/small_balance` | -| [convertSmallBalance()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L730) | :closed_lock_with_key: | POST | `/wallet/small_balance` | -| [getSmallBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L743) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | -| [getPushOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L755) | :closed_lock_with_key: | GET | `/wallet/push` | -| [getLowCapExchangeList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L764) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | -| [createSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L779) | :closed_lock_with_key: | POST | `/sub_accounts` | -| [getSubAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L790) | :closed_lock_with_key: | GET | `/sub_accounts` | -| [getSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L800) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | -| [createSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L810) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | -| [getSubAccountApiKeys()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L823) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | -| [updateSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L837) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | -| [deleteSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L848) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | -| [getSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L863) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | -| [lockSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L878) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | -| [unlockSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L888) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | -| [getSubAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L902) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | -| [getUnifiedAccountInfo()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L921) | :closed_lock_with_key: | GET | `/unified/accounts` | -| [getUnifiedMaxBorrow()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L937) | :closed_lock_with_key: | GET | `/unified/borrowable` | -| [getUnifiedMaxTransferable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L953) | :closed_lock_with_key: | GET | `/unified/transferable` | -| [getUnifiedMaxTransferables()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L968) | :closed_lock_with_key: | GET | `/unified/transferables` | -| [getUnifiedBatchMaxBorrowable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L977) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | -| [submitUnifiedBorrowOrRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L995) | :closed_lock_with_key: | POST | `/unified/loans` | -| [getUnifiedLoans()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1007) | :closed_lock_with_key: | GET | `/unified/loans` | -| [getUnifiedLoanRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1017) | :closed_lock_with_key: | GET | `/unified/loan_records` | -| [getUnifiedInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1029) | :closed_lock_with_key: | GET | `/unified/interest_records` | -| [getUnifiedRiskUnitDetails()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1040) | :closed_lock_with_key: | GET | `/unified/risk_units` | -| [setUnifiedAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1052) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | -| [getUnifiedAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1061) | :closed_lock_with_key: | GET | `/unified/unified_mode` | -| [getUnifiedEstimateRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1073) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | -| [getUnifiedCurrencyDiscountTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1084) | | GET | `/unified/currency_discount_tiers` | -| [getLoanMarginTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1096) | | GET | `/unified/loan_margin_tiers` | -| [portfolioMarginCalculate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1113) | | POST | `/unified/portfolio_calculator` | -| [getUserCurrencyLeverageConfig()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1127) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | -| [getUserCurrencyLeverageSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1141) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | -| [updateUserCurrencyLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1156) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | -| [getUnifiedLoanCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1171) | :closed_lock_with_key: | GET | `/unified/currencies` | -| [getHistoricalLendingRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1183) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | -| [submitUnifiedLoanRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1189) | :closed_lock_with_key: | POST | `/unified/loans/repay` | -| [getSpotCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1209) | | GET | `/spot/currencies` | -| [getSpotCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1219) | | GET | `/spot/currencies/{currency}` | -| [getSpotCurrencyPairs()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1228) | | GET | `/spot/currency_pairs` | -| [getSpotCurrencyPair()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1238) | | GET | `/spot/currency_pairs/{currency_pair}` | -| [getSpotTicker()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1252) | | GET | `/spot/tickers` | -| [getSpotOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1267) | | GET | `/spot/order_book` | -| [getSpotTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1280) | | GET | `/spot/trades` | -| [getSpotCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1292) | | GET | `/spot/candlesticks` | -| [getSpotFeeRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1304) | :closed_lock_with_key: | GET | `/spot/fee` | -| [getSpotBatchFeeRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1313) | :closed_lock_with_key: | GET | `/spot/batch_fee` | -| [getSpotAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1325) | :closed_lock_with_key: | GET | `/spot/accounts` | -| [getSpotAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1337) | :closed_lock_with_key: | GET | `/spot/account_book` | -| [submitSpotBatchOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1356) | :closed_lock_with_key: | POST | `/spot/batch_orders` | -| [getSpotOpenOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1383) | :closed_lock_with_key: | GET | `/spot/open_orders` | -| [submitSpotClosePosCrossDisabled()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1399) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | -| [submitSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1415) | :closed_lock_with_key: | POST | `/spot/orders` | -| [getSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1432) | :closed_lock_with_key: | GET | `/spot/orders` | -| [cancelSpotOpenOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1447) | :closed_lock_with_key: | DELETE | `/spot/orders` | -| [batchCancelSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1475) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | -| [getSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1500) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | -| [updateSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1517) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | -| [cancelSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1545) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | -| [getSpotTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1574) | :closed_lock_with_key: | GET | `/spot/my_trades` | -| [submitSpotCountdownOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1603) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | -| [batchUpdateSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1622) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | -| [getSpotInsuranceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1649) | :closed_lock_with_key: | GET | `/spot/insurance_history` | -| [submitSpotPriceTriggerOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1663) | :closed_lock_with_key: | POST | `/spot/price_orders` | -| [getSpotAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1675) | :closed_lock_with_key: | GET | `/spot/price_orders` | -| [cancelAllOpenSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1687) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | -| [getPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1700) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | -| [cancelSpotTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1712) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | -| [setCollateralCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1726) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | -| [getMarginAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1747) | :closed_lock_with_key: | GET | `/margin/accounts` | -| [getMarginBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1761) | :closed_lock_with_key: | GET | `/margin/account_book` | -| [getFundingAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1779) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | -| [updateAutoRepaymentSetting()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1797) | :closed_lock_with_key: | POST | `/margin/auto_repay` | -| [getAutoRepaymentSetting()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1808) | :closed_lock_with_key: | GET | `/margin/auto_repay` | -| [getMarginTransferableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1822) | :closed_lock_with_key: | GET | `/margin/transferable` | -| [getCrossMarginCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1839) | | GET | `/margin/cross/currencies` | -| [getCrossMarginCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1850) | | GET | `/margin/cross/currencies/{currency}` | -| [getCrossMarginAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1862) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | -| [getCrossMarginAccountHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1875) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | -| [submitCrossMarginBorrowLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1892) | :closed_lock_with_key: | POST | `/margin/cross/loans` | -| [getCrossMarginBorrowHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1907) | :closed_lock_with_key: | GET | `/margin/cross/loans` | -| [getCrossMarginBorrowLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1920) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | -| [submitCrossMarginRepayment()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1935) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | -| [getCrossMarginRepayments()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1951) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | -| [getCrossMarginInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1964) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | -| [getCrossMarginTransferableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1980) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | -| [getEstimatedInterestRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1996) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | -| [getCrossMarginBorrowableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2010) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | -| [getMarginUserLoanTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2023) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | -| [getMarginPublicLoanTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2039) | | GET | `/margin/loan_margin_tiers` | -| [setMarginUserLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2055) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | -| [getMarginUserAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2072) | :closed_lock_with_key: | GET | `/margin/user/account` | -| [getLendingMarkets()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2087) | | GET | `/margin/uni/currency_pairs` | -| [getLendingMarket()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2102) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | -| [getEstimatedInterestRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2114) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | -| [submitMarginUNIBorrowOrRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2124) | :closed_lock_with_key: | POST | `/margin/uni/loans` | -| [getMarginUNILoans()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2140) | :closed_lock_with_key: | GET | `/margin/uni/loans` | -| [getMarginUNILoanRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2150) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | -| [getMarginUNIInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2162) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | -| [getMarginUNIMaxBorrow()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2174) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | -| [getFlashSwapCurrencyPairs()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2190) | | GET | `/flash_swap/currency_pairs` | -| [submitFlashSwapOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2206) | :closed_lock_with_key: | POST | `/flash_swap/orders` | -| [getFlashSwapOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2218) | :closed_lock_with_key: | GET | `/flash_swap/orders` | -| [getFlashSwapOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2230) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | -| [submitFlashSwapOrderPreview()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2240) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | -| [getFuturesContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2257) | | GET | `/futures/{settle}/contracts` | -| [getFuturesContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2272) | | GET | `/futures/{settle}/contracts/{contract}` | -| [getFuturesOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2287) | | GET | `/futures/{settle}/order_book` | -| [getFuturesTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2300) | | GET | `/futures/{settle}/trades` | -| [getFuturesCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2315) | | GET | `/futures/{settle}/candlesticks` | -| [getPremiumIndexKLines()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2328) | | GET | `/futures/{settle}/premium_index` | -| [getFuturesTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2341) | | GET | `/futures/{settle}/tickers` | -| [getFundingRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2358) | | GET | `/futures/{settle}/funding_rate` | -| [getFuturesInsuranceBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2377) | | GET | `/futures/{settle}/insurance` | -| [getFuturesStats()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2396) | | GET | `/futures/{settle}/contract_stats` | -| [getIndexConstituents()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2407) | | GET | `/futures/{settle}/index_constituents/{index}` | -| [getLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2424) | | GET | `/futures/{settle}/liq_orders` | -| [getRiskLimitTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2441) | | GET | `/futures/{settle}/risk_limit_tiers` | -| [getFuturesAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2454) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | -| [getFuturesAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2468) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | -| [getFuturesPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2481) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | -| [getFuturesPosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2496) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | -| [updateFuturesMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2513) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | -| [updateFuturesLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2541) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | -| [updateFuturesPositionMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2561) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | -| [updatePositionRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2578) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | -| [updateFuturesDualMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2598) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | -| [getDualModePosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2614) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | -| [updateDualModePositionMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2629) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | -| [updateDualModePositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2645) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | -| [updateDualModePositionRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2669) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | -| [submitFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2696) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | -| [getFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2717) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | -| [cancelAllFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2732) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | -| [getFuturesOrdersByTimeRange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2752) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | -| [submitFuturesBatchOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2775) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | -| [getFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2800) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | -| [cancelFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2817) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | -| [updateFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2840) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | -| [getFuturesTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2861) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | -| [getFuturesTradingHistoryByTimeRange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2876) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | -| [getFuturesPositionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2889) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | -| [getFuturesLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2902) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | -| [getFuturesAutoDeleveragingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2915) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | -| [setFuturesOrderCancelCountdown()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2932) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | -| [getFuturesUserTradingFees()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2949) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | -| [batchCancelFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2967) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | -| [batchUpdateFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2994) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | -| [getRiskLimitTable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3016) | | GET | `/futures/{settle}/risk_limit_table` | -| [submitFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3029) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | -| [getFuturesAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3042) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | -| [cancelAllOpenFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3055) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | -| [getFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3071) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | -| [cancelFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3086) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | -| [updateFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3101) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/{order_id}` | -| [getFuturesPositionCloseHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3110) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | -| [getFuturesInsuranceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3119) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | -| [getAllDeliveryContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3136) | | GET | `/delivery/{settle}/contracts` | -| [getDeliveryContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3148) | | GET | `/delivery/{settle}/contracts/{contract}` | -| [getDeliveryOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3163) | | GET | `/delivery/{settle}/order_book` | -| [getDeliveryTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3176) | | GET | `/delivery/{settle}/trades` | -| [getDeliveryCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3190) | | GET | `/delivery/{settle}/candlesticks` | -| [getDeliveryTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3201) | | GET | `/delivery/{settle}/tickers` | -| [getDeliveryInsuranceBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3218) | | GET | `/delivery/{settle}/insurance` | -| [getDeliveryAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3237) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | -| [getDeliveryBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3248) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | -| [getDeliveryPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3259) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | -| [getDeliveryPosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3269) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | -| [updateDeliveryMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3284) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | -| [updateDeliveryLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3302) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | -| [updateDeliveryRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3320) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | -| [submitDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3340) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | -| [getDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3355) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | -| [cancelAllDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3368) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | -| [getDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3387) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | -| [cancelDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3402) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | -| [getDeliveryTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3417) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | -| [getDeliveryClosedPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3430) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | -| [getDeliveryLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3443) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | -| [getDeliverySettlementHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3456) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | -| [submitDeliveryTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3469) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | -| [getDeliveryAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3484) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | -| [cancelAllOpenDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3497) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | -| [getDeliveryTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3513) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | -| [cancelTriggeredDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3528) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | -| [getOptionsUnderlyings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3547) | | GET | `/options/underlyings` | -| [getOptionsExpirationTimes()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3557) | | GET | `/options/expirations` | -| [getOptionsContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3567) | | GET | `/options/contracts` | -| [getOptionsContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3580) | | GET | `/options/contracts/{contract}` | -| [getOptionsSettlementHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3590) | | GET | `/options/settlements` | -| [getOptionsContractSettlement()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3602) | | GET | `/options/settlements/{contract}` | -| [getOptionsMySettlements()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3617) | :closed_lock_with_key: | GET | `/options/my_settlements` | -| [getOptionsOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3631) | | GET | `/options/order_book` | -| [getOptionsTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3643) | | GET | `/options/tickers` | -| [getOptionsUnderlyingTicker()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3657) | | GET | `/options/underlying/tickers/{underlying}` | -| [getOptionsCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3671) | | GET | `/options/candlesticks` | -| [getOptionsUnderlyingCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3681) | | GET | `/options/underlying/candlesticks` | -| [getOptionsTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3693) | | GET | `/options/trades` | -| [getOptionsAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3704) | :closed_lock_with_key: | GET | `/options/accounts` | -| [getOptionsAccountChange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3714) | :closed_lock_with_key: | GET | `/options/account_book` | -| [getOptionsPositionsUnderlying()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3726) | :closed_lock_with_key: | GET | `/options/positions` | -| [getOptionsPositionContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3738) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | -| [getOptionsLiquidation()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3750) | :closed_lock_with_key: | GET | `/options/position_close` | -| [submitOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3763) | :closed_lock_with_key: | POST | `/options/orders` | -| [getOptionsOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3775) | :closed_lock_with_key: | GET | `/options/orders` | -| [cancelAllOpenOptionsOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3787) | :closed_lock_with_key: | DELETE | `/options/orders` | -| [getOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3801) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | -| [cancelOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3813) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | -| [submitOptionsCountdownCancel()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3832) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | -| [getOptionsPersonalHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3848) | :closed_lock_with_key: | GET | `/options/my_trades` | -| [setOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3860) | :closed_lock_with_key: | POST | `/options/mmp` | -| [getOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3872) | :closed_lock_with_key: | GET | `/options/mmp` | -| [resetOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3884) | :closed_lock_with_key: | POST | `/options/mmp/reset` | -| [getLendingCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3900) | | GET | `/earn/uni/currencies` | -| [getLendingCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3910) | | GET | `/earn/uni/currencies/{currency}` | -| [submitLendOrRedeemOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3920) | :closed_lock_with_key: | POST | `/earn/uni/lends` | -| [getLendingOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3930) | :closed_lock_with_key: | GET | `/earn/uni/lends` | -| [updateLendingOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3942) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | -| [getLendingRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3955) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | -| [getLendingTotalInterest()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3968) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | -| [getLendingInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3981) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | -| [updateInterestReinvestment()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3994) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | -| [getLendingInterestStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4010) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | -| [getLendingAnnualizedTrendChart()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4025) | :closed_lock_with_key: | GET | `/earn/uni/chart` | -| [getLendingEstimatedRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4033) | :closed_lock_with_key: | GET | `/earn/uni/rate` | -| [submitLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4050) | :closed_lock_with_key: | POST | `/loan/collateral/orders` | -| [getLoanOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4060) | :closed_lock_with_key: | GET | `/loan/collateral/orders` | -| [getLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4070) | :closed_lock_with_key: | GET | `/loan/collateral/orders/{order_id}` | -| [submitLoanRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4083) | :closed_lock_with_key: | POST | `/loan/collateral/repay` | -| [getLoanRepaymentHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4100) | :closed_lock_with_key: | GET | `/loan/collateral/repay_records` | -| [updateLoanCollateral()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4112) | :closed_lock_with_key: | POST | `/loan/collateral/collaterals` | -| [getLoanCollateralRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4122) | :closed_lock_with_key: | GET | `/loan/collateral/collaterals` | -| [getLoanTotalAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4136) | :closed_lock_with_key: | GET | `/loan/collateral/total_amount` | -| [getLoanCollateralizationRatio()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4149) | :closed_lock_with_key: | GET | `/loan/collateral/ltv` | -| [getLoanSupportedCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4165) | | GET | `/loan/collateral/currencies` | -| [submitMultiLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4185) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | -| [getMultiLoanOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4197) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | -| [getMultiLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4209) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | -| [repayMultiLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4219) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | -| [getMultiLoanRepayRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4229) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | -| [updateMultiLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4241) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | -| [getMultiLoanAdjustmentRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4253) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | -| [getMultiLoanCurrencyQuota()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4265) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | -| [getMultiLoanSupportedCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4277) | | GET | `/loan/multi_collateral/currencies` | -| [getMultiLoanRatio()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4286) | | GET | `/loan/multi_collateral/ltv` | -| [getMultiLoanFixedRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4295) | | GET | `/loan/multi_collateral/fixed_rate` | -| [getMultiLoanCurrentRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4308) | | GET | `/loan/multi_collateral/current_rate` | -| [submitEth2Swap()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4330) | :closed_lock_with_key: | POST | `/earn/staking/eth2/swap` | -| [getEth2RateHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4339) | :closed_lock_with_key: | GET | `/earn/staking/eth2/rate_records` | -| [getDualInvestmentProducts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4350) | | GET | `/earn/dual/investment_plan` | -| [getDualInvestmentOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4361) | :closed_lock_with_key: | GET | `/earn/dual/orders` | -| [submitDualInvestmentOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4373) | :closed_lock_with_key: | POST | `/earn/dual/orders` | -| [getStructuredProducts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4388) | | GET | `/earn/structured/products` | -| [getStructuredProductOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4400) | :closed_lock_with_key: | GET | `/earn/structured/orders` | -| [submitStructuredProductOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4412) | :closed_lock_with_key: | POST | `/earn/structured/orders` | -| [getStakingCoins()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4425) | :closed_lock_with_key: | GET | `/earn/staking/coins` | -| [submitStakingSwap()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4438) | :closed_lock_with_key: | POST | `/earn/staking/swap` | -| [getAccountDetail()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4457) | :closed_lock_with_key: | GET | `/account/detail` | -| [getAccountRateLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4466) | :closed_lock_with_key: | GET | `/account/rate_limit` | -| [createStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4476) | :closed_lock_with_key: | POST | `/account/stp_groups` | -| [getStpGroups()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4486) | :closed_lock_with_key: | GET | `/account/stp_groups` | -| [getStpGroupUsers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4496) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | -| [addUsersToStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4506) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | -| [deleteUserFromStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4522) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | -| [setGTDeduction()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4540) | :closed_lock_with_key: | POST | `/account/debit_fee` | -| [getGTDeduction()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4551) | :closed_lock_with_key: | GET | `/account/debit_fee` | -| [getAccountMainKeys()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4560) | :closed_lock_with_key: | GET | `/account/main_keys` | -| [getAgencyTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4576) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | -| [getAgencyCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4589) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | -| [getPartnerTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4603) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | -| [getPartnerCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4618) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | -| [getPartnerSubordinateList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4641) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | -| [getBrokerCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4655) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | -| [getBrokerTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4668) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | -| [getUserRebateInfo()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4677) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [getSystemMaintenanceStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L520) | | GET | `/v1/public/system_info` | +| [submitWithdrawal()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L537) | :closed_lock_with_key: | POST | `/withdrawals` | +| [submitSpotMainAccountTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L551) | :closed_lock_with_key: | POST | `/withdrawals/push` | +| [cancelWithdrawal()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L567) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | +| [getCurrencyChains()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L584) | | GET | `/wallet/currency_chains` | +| [createDepositAddress()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L594) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | +| [getWithdrawalRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L608) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | +| [getDepositRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L622) | :closed_lock_with_key: | GET | `/wallet/deposits` | +| [submitTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L641) | :closed_lock_with_key: | POST | `/wallet/transfers` | +| [submitMainSubTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L653) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | +| [getMainSubTransfers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L667) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | +| [submitSubToSubTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L681) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | +| [getTransferStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L696) | :closed_lock_with_key: | GET | `/wallet/order_status` | +| [getWithdrawalStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L712) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | +| [getSubBalance()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L727) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | +| [getSubMarginBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L742) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | +| [getSubFuturesBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L754) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | +| [getSubCrossMarginBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L767) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | +| [getSavedAddresses()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L779) | :closed_lock_with_key: | GET | `/wallet/saved_address` | +| [getTradingFees()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L789) | :closed_lock_with_key: | GET | `/wallet/fee` | +| [getBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L810) | :closed_lock_with_key: | GET | `/wallet/total_balance` | +| [getSmallBalances()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L819) | :closed_lock_with_key: | GET | `/wallet/small_balance` | +| [convertSmallBalance()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L829) | :closed_lock_with_key: | POST | `/wallet/small_balance` | +| [getSmallBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L842) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | +| [getPushOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L854) | :closed_lock_with_key: | GET | `/wallet/push` | +| [getLowCapExchangeList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L863) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | +| [createSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L878) | :closed_lock_with_key: | POST | `/sub_accounts` | +| [getSubAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L889) | :closed_lock_with_key: | GET | `/sub_accounts` | +| [getSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L899) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | +| [createSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L909) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | +| [getSubAccountApiKeys()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L922) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | +| [updateSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L936) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | +| [deleteSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L947) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | +| [getSubAccountApiKey()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L962) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | +| [lockSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L977) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | +| [unlockSubAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L987) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | +| [getSubAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1001) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | +| [getUnifiedAccountInfo()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1020) | :closed_lock_with_key: | GET | `/unified/accounts` | +| [getUnifiedMaxBorrow()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1036) | :closed_lock_with_key: | GET | `/unified/borrowable` | +| [getUnifiedMaxTransferable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1052) | :closed_lock_with_key: | GET | `/unified/transferable` | +| [getUnifiedMaxTransferables()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1067) | :closed_lock_with_key: | GET | `/unified/transferables` | +| [getUnifiedBatchMaxBorrowable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1076) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | +| [submitUnifiedBorrowOrRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1094) | :closed_lock_with_key: | POST | `/unified/loans` | +| [getUnifiedLoans()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1106) | :closed_lock_with_key: | GET | `/unified/loans` | +| [getUnifiedLoanRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1116) | :closed_lock_with_key: | GET | `/unified/loan_records` | +| [getUnifiedInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1128) | :closed_lock_with_key: | GET | `/unified/interest_records` | +| [getUnifiedRiskUnitDetails()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1139) | :closed_lock_with_key: | GET | `/unified/risk_units` | +| [setUnifiedAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1151) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | +| [getUnifiedAccountMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1160) | :closed_lock_with_key: | GET | `/unified/unified_mode` | +| [getUnifiedEstimateRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1172) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | +| [getUnifiedCurrencyDiscountTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1183) | | GET | `/unified/currency_discount_tiers` | +| [getLoanMarginTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1195) | | GET | `/unified/loan_margin_tiers` | +| [portfolioMarginCalculate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1212) | | POST | `/unified/portfolio_calculator` | +| [getUserCurrencyLeverageConfig()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1226) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | +| [getUserCurrencyLeverageSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1240) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | +| [updateUserCurrencyLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1255) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | +| [getUnifiedLoanCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1270) | :closed_lock_with_key: | GET | `/unified/currencies` | +| [getHistoricalLendingRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1282) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | +| [submitUnifiedLoanRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1288) | :closed_lock_with_key: | POST | `/unified/loans/repay` | +| [getSpotCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1308) | | GET | `/spot/currencies` | +| [getSpotCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1318) | | GET | `/spot/currencies/{currency}` | +| [getSpotCurrencyPairs()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1327) | | GET | `/spot/currency_pairs` | +| [getSpotCurrencyPair()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1337) | | GET | `/spot/currency_pairs/{currency_pair}` | +| [getSpotTicker()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1351) | | GET | `/spot/tickers` | +| [getSpotOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1366) | | GET | `/spot/order_book` | +| [getSpotTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1379) | | GET | `/spot/trades` | +| [getSpotCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1391) | | GET | `/spot/candlesticks` | +| [getSpotFeeRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1403) | :closed_lock_with_key: | GET | `/spot/fee` | +| [getSpotBatchFeeRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1412) | :closed_lock_with_key: | GET | `/spot/batch_fee` | +| [getSpotAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1424) | :closed_lock_with_key: | GET | `/spot/accounts` | +| [getSpotAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1436) | :closed_lock_with_key: | GET | `/spot/account_book` | +| [submitSpotBatchOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1455) | :closed_lock_with_key: | POST | `/spot/batch_orders` | +| [getSpotOpenOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1482) | :closed_lock_with_key: | GET | `/spot/open_orders` | +| [submitSpotClosePosCrossDisabled()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1498) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | +| [submitSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1514) | :closed_lock_with_key: | POST | `/spot/orders` | +| [getSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1531) | :closed_lock_with_key: | GET | `/spot/orders` | +| [cancelSpotOpenOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1546) | :closed_lock_with_key: | DELETE | `/spot/orders` | +| [batchCancelSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1574) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | +| [getSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1599) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | +| [updateSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1616) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | +| [cancelSpotOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1644) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | +| [getSpotTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1673) | :closed_lock_with_key: | GET | `/spot/my_trades` | +| [submitSpotCountdownOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1702) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | +| [batchUpdateSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1721) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | +| [getSpotInsuranceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1748) | :closed_lock_with_key: | GET | `/spot/insurance_history` | +| [submitSpotPriceTriggerOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1762) | :closed_lock_with_key: | POST | `/spot/price_orders` | +| [getSpotAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1774) | :closed_lock_with_key: | GET | `/spot/price_orders` | +| [cancelAllOpenSpotOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1786) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | +| [getPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1799) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | +| [cancelSpotTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1811) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | +| [setCollateralCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1825) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | +| [getMarginAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1846) | :closed_lock_with_key: | GET | `/margin/accounts` | +| [getMarginBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1860) | :closed_lock_with_key: | GET | `/margin/account_book` | +| [getFundingAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1878) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | +| [updateAutoRepaymentSetting()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1896) | :closed_lock_with_key: | POST | `/margin/auto_repay` | +| [getAutoRepaymentSetting()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1907) | :closed_lock_with_key: | GET | `/margin/auto_repay` | +| [getMarginTransferableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1921) | :closed_lock_with_key: | GET | `/margin/transferable` | +| [getCrossMarginCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1938) | | GET | `/margin/cross/currencies` | +| [getCrossMarginCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1949) | | GET | `/margin/cross/currencies/{currency}` | +| [getCrossMarginAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1961) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | +| [getCrossMarginAccountHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1974) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | +| [submitCrossMarginBorrowLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L1991) | :closed_lock_with_key: | POST | `/margin/cross/loans` | +| [getCrossMarginBorrowHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2006) | :closed_lock_with_key: | GET | `/margin/cross/loans` | +| [getCrossMarginBorrowLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2019) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | +| [submitCrossMarginRepayment()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2034) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | +| [getCrossMarginRepayments()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2050) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | +| [getCrossMarginInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2063) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | +| [getCrossMarginTransferableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2079) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | +| [getEstimatedInterestRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2095) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | +| [getCrossMarginBorrowableAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2109) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | +| [getMarginUserLoanTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2122) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | +| [getMarginPublicLoanTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2138) | | GET | `/margin/loan_margin_tiers` | +| [setMarginUserLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2154) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | +| [getMarginUserAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2171) | :closed_lock_with_key: | GET | `/margin/user/account` | +| [getLendingMarkets()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2186) | | GET | `/margin/uni/currency_pairs` | +| [getLendingMarket()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2201) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | +| [getEstimatedInterestRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2213) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | +| [submitMarginUNIBorrowOrRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2223) | :closed_lock_with_key: | POST | `/margin/uni/loans` | +| [getMarginUNILoans()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2239) | :closed_lock_with_key: | GET | `/margin/uni/loans` | +| [getMarginUNILoanRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2249) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | +| [getMarginUNIInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2261) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | +| [getMarginUNIMaxBorrow()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2273) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | +| [getFlashSwapCurrencyPairs()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2289) | | GET | `/flash_swap/currency_pairs` | +| [submitFlashSwapOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2305) | :closed_lock_with_key: | POST | `/flash_swap/orders` | +| [getFlashSwapOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2317) | :closed_lock_with_key: | GET | `/flash_swap/orders` | +| [getFlashSwapOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2329) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | +| [submitFlashSwapOrderPreview()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2339) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | +| [getFuturesContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2356) | | GET | `/futures/{settle}/contracts` | +| [getFuturesContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2371) | | GET | `/futures/{settle}/contracts/{contract}` | +| [getFuturesOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2386) | | GET | `/futures/{settle}/order_book` | +| [getFuturesTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2399) | | GET | `/futures/{settle}/trades` | +| [getFuturesCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2414) | | GET | `/futures/{settle}/candlesticks` | +| [getPremiumIndexKLines()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2427) | | GET | `/futures/{settle}/premium_index` | +| [getFuturesTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2440) | | GET | `/futures/{settle}/tickers` | +| [getFundingRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2457) | | GET | `/futures/{settle}/funding_rate` | +| [getFuturesInsuranceBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2476) | | GET | `/futures/{settle}/insurance` | +| [getFuturesStats()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2495) | | GET | `/futures/{settle}/contract_stats` | +| [getIndexConstituents()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2506) | | GET | `/futures/{settle}/index_constituents/{index}` | +| [getLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2523) | | GET | `/futures/{settle}/liq_orders` | +| [getRiskLimitTiers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2540) | | GET | `/futures/{settle}/risk_limit_tiers` | +| [getFuturesAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2553) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | +| [getFuturesAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2567) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | +| [getFuturesPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2580) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | +| [getFuturesPosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2595) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | +| [updateFuturesMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2612) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | +| [updateFuturesLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2640) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | +| [updateFuturesPositionMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2660) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | +| [updatePositionRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2677) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | +| [updateFuturesDualMode()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2697) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | +| [getDualModePosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2713) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | +| [updateDualModePositionMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2728) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | +| [updateDualModePositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2744) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | +| [updateDualModePositionRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2768) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | +| [submitFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2795) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | +| [getFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2816) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | +| [cancelAllFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2831) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | +| [getFuturesOrdersByTimeRange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2851) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | +| [submitFuturesBatchOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2874) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | +| [getFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2899) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | +| [cancelFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2916) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | +| [updateFuturesOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2939) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | +| [getFuturesTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2960) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | +| [getFuturesTradingHistoryByTimeRange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2975) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | +| [getFuturesPositionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L2988) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | +| [getFuturesLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3001) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | +| [getFuturesAutoDeleveragingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3014) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | +| [setFuturesOrderCancelCountdown()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3031) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | +| [getFuturesUserTradingFees()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3048) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | +| [batchCancelFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3066) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | +| [batchUpdateFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3093) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | +| [getRiskLimitTable()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3115) | | GET | `/futures/{settle}/risk_limit_table` | +| [submitFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3128) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | +| [getFuturesAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3141) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | +| [cancelAllOpenFuturesOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3154) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | +| [getFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3170) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | +| [cancelFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3185) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | +| [updateFuturesPriceTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3200) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/{order_id}` | +| [getFuturesPositionCloseHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3209) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | +| [getFuturesInsuranceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3218) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | +| [getAllDeliveryContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3235) | | GET | `/delivery/{settle}/contracts` | +| [getDeliveryContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3247) | | GET | `/delivery/{settle}/contracts/{contract}` | +| [getDeliveryOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3262) | | GET | `/delivery/{settle}/order_book` | +| [getDeliveryTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3275) | | GET | `/delivery/{settle}/trades` | +| [getDeliveryCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3289) | | GET | `/delivery/{settle}/candlesticks` | +| [getDeliveryTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3300) | | GET | `/delivery/{settle}/tickers` | +| [getDeliveryInsuranceBalanceHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3317) | | GET | `/delivery/{settle}/insurance` | +| [getDeliveryAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3336) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | +| [getDeliveryBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3347) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | +| [getDeliveryPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3358) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | +| [getDeliveryPosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3368) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | +| [updateDeliveryMargin()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3383) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | +| [updateDeliveryLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3401) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | +| [updateDeliveryRiskLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3419) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | +| [submitDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3439) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | +| [getDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3454) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | +| [cancelAllDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3467) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | +| [getDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3486) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | +| [cancelDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3501) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | +| [getDeliveryTradingHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3516) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | +| [getDeliveryClosedPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3529) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | +| [getDeliveryLiquidationHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3542) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | +| [getDeliverySettlementHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3555) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | +| [submitDeliveryTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3568) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | +| [getDeliveryAutoOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3583) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | +| [cancelAllOpenDeliveryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3596) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | +| [getDeliveryTriggeredOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3612) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | +| [cancelTriggeredDeliveryOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3627) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | +| [getOptionsUnderlyings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3646) | | GET | `/options/underlyings` | +| [getOptionsExpirationTimes()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3656) | | GET | `/options/expirations` | +| [getOptionsContracts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3666) | | GET | `/options/contracts` | +| [getOptionsContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3679) | | GET | `/options/contracts/{contract}` | +| [getOptionsSettlementHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3689) | | GET | `/options/settlements` | +| [getOptionsContractSettlement()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3701) | | GET | `/options/settlements/{contract}` | +| [getOptionsMySettlements()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3716) | :closed_lock_with_key: | GET | `/options/my_settlements` | +| [getOptionsOrderBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3730) | | GET | `/options/order_book` | +| [getOptionsTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3742) | | GET | `/options/tickers` | +| [getOptionsUnderlyingTicker()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3756) | | GET | `/options/underlying/tickers/{underlying}` | +| [getOptionsCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3770) | | GET | `/options/candlesticks` | +| [getOptionsUnderlyingCandles()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3780) | | GET | `/options/underlying/candlesticks` | +| [getOptionsTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3792) | | GET | `/options/trades` | +| [getOptionsAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3803) | :closed_lock_with_key: | GET | `/options/accounts` | +| [getOptionsAccountChange()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3813) | :closed_lock_with_key: | GET | `/options/account_book` | +| [getOptionsPositionsUnderlying()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3825) | :closed_lock_with_key: | GET | `/options/positions` | +| [getOptionsPositionContract()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3837) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | +| [getOptionsLiquidation()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3849) | :closed_lock_with_key: | GET | `/options/position_close` | +| [submitOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3862) | :closed_lock_with_key: | POST | `/options/orders` | +| [getOptionsOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3874) | :closed_lock_with_key: | GET | `/options/orders` | +| [cancelAllOpenOptionsOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3886) | :closed_lock_with_key: | DELETE | `/options/orders` | +| [getOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3900) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | +| [cancelOptionsOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3912) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | +| [submitOptionsCountdownCancel()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3931) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | +| [getOptionsPersonalHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3947) | :closed_lock_with_key: | GET | `/options/my_trades` | +| [setOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3959) | :closed_lock_with_key: | POST | `/options/mmp` | +| [getOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3971) | :closed_lock_with_key: | GET | `/options/mmp` | +| [resetOptionsMMPSettings()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3983) | :closed_lock_with_key: | POST | `/options/mmp/reset` | +| [getLendingCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L3999) | | GET | `/earn/uni/currencies` | +| [getLendingCurrency()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4009) | | GET | `/earn/uni/currencies/{currency}` | +| [submitLendOrRedeemOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4019) | :closed_lock_with_key: | POST | `/earn/uni/lends` | +| [getLendingOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4029) | :closed_lock_with_key: | GET | `/earn/uni/lends` | +| [updateLendingOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4041) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | +| [getLendingRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4054) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | +| [getLendingTotalInterest()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4067) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | +| [getLendingInterestRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4080) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | +| [updateInterestReinvestment()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4093) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | +| [getLendingInterestStatus()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4109) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | +| [getLendingAnnualizedTrendChart()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4124) | :closed_lock_with_key: | GET | `/earn/uni/chart` | +| [getLendingEstimatedRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4132) | :closed_lock_with_key: | GET | `/earn/uni/rate` | +| [submitLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4149) | :closed_lock_with_key: | POST | `/loan/collateral/orders` | +| [getLoanOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4159) | :closed_lock_with_key: | GET | `/loan/collateral/orders` | +| [getLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4169) | :closed_lock_with_key: | GET | `/loan/collateral/orders/{order_id}` | +| [submitLoanRepay()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4182) | :closed_lock_with_key: | POST | `/loan/collateral/repay` | +| [getLoanRepaymentHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4199) | :closed_lock_with_key: | GET | `/loan/collateral/repay_records` | +| [updateLoanCollateral()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4211) | :closed_lock_with_key: | POST | `/loan/collateral/collaterals` | +| [getLoanCollateralRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4221) | :closed_lock_with_key: | GET | `/loan/collateral/collaterals` | +| [getLoanTotalAmount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4235) | :closed_lock_with_key: | GET | `/loan/collateral/total_amount` | +| [getLoanCollateralizationRatio()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4248) | :closed_lock_with_key: | GET | `/loan/collateral/ltv` | +| [getLoanSupportedCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4264) | | GET | `/loan/collateral/currencies` | +| [submitMultiLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4284) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | +| [getMultiLoanOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4296) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | +| [getMultiLoanOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4308) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | +| [repayMultiLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4318) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | +| [getMultiLoanRepayRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4328) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | +| [updateMultiLoan()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4340) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | +| [getMultiLoanAdjustmentRecords()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4352) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | +| [getMultiLoanCurrencyQuota()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4364) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | +| [getMultiLoanSupportedCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4376) | | GET | `/loan/multi_collateral/currencies` | +| [getMultiLoanRatio()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4385) | | GET | `/loan/multi_collateral/ltv` | +| [getMultiLoanFixedRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4394) | | GET | `/loan/multi_collateral/fixed_rate` | +| [getMultiLoanCurrentRates()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4407) | | GET | `/loan/multi_collateral/current_rate` | +| [submitEth2Swap()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4429) | :closed_lock_with_key: | POST | `/earn/staking/eth2/swap` | +| [getEth2RateHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4438) | :closed_lock_with_key: | GET | `/earn/staking/eth2/rate_records` | +| [getDualInvestmentProducts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4449) | | GET | `/earn/dual/investment_plan` | +| [getDualInvestmentOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4460) | :closed_lock_with_key: | GET | `/earn/dual/orders` | +| [submitDualInvestmentOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4472) | :closed_lock_with_key: | POST | `/earn/dual/orders` | +| [getStructuredProducts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4487) | | GET | `/earn/structured/products` | +| [getStructuredProductOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4499) | :closed_lock_with_key: | GET | `/earn/structured/orders` | +| [submitStructuredProductOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4511) | :closed_lock_with_key: | POST | `/earn/structured/orders` | +| [getStakingCoins()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4524) | :closed_lock_with_key: | GET | `/earn/staking/coins` | +| [submitStakingSwap()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4537) | :closed_lock_with_key: | POST | `/earn/staking/swap` | +| [getAccountDetail()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4556) | :closed_lock_with_key: | GET | `/account/detail` | +| [getAccountRateLimit()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4565) | :closed_lock_with_key: | GET | `/account/rate_limit` | +| [createStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4575) | :closed_lock_with_key: | POST | `/account/stp_groups` | +| [getStpGroups()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4585) | :closed_lock_with_key: | GET | `/account/stp_groups` | +| [getStpGroupUsers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4595) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | +| [addUsersToStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4605) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | +| [deleteUserFromStpGroup()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4621) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | +| [setGTDeduction()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4639) | :closed_lock_with_key: | POST | `/account/debit_fee` | +| [getGTDeduction()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4650) | :closed_lock_with_key: | GET | `/account/debit_fee` | +| [getAccountMainKeys()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4659) | :closed_lock_with_key: | GET | `/account/main_keys` | +| [getAgencyTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4675) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | +| [getAgencyCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4688) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | +| [getPartnerTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4702) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | +| [getPartnerCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4717) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | +| [getPartnerSubordinateList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4740) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | +| [getBrokerCommissionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4754) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | +| [getBrokerTransactionHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4767) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | +| [getUserRebateInfo()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4776) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [createOTCQuote()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4811) | :closed_lock_with_key: | POST | `/otc/quote` | +| [createOTCFiatOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4823) | :closed_lock_with_key: | POST | `/otc/order/create` | +| [createOTCStablecoinOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4837) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | +| [getOTCUserDefaultBank()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4850) | :closed_lock_with_key: | GET | `/otc/get_user_def_bank` | +| [markOTCOrderAsPaid()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4862) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [cancelOTCOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4876) | :closed_lock_with_key: | POST | `/otc/order/cancel` | +| [getOTCFiatOrderList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4888) | :closed_lock_with_key: | GET | `/otc/order/list` | +| [getOTCStablecoinOrderList()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4902) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | +| [getOTCFiatOrderDetail()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4916) | :closed_lock_with_key: | GET | `/otc/order/detail` | +| [getCrossExSymbols()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4935) | | GET | `/crossex/rule/symbols` | +| [getCrossExRiskLimits()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4947) | | GET | `/crossex/rule/risk_limits` | +| [getCrossExTransferCoins()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4961) | | GET | `/crossex/transfers/coin` | +| [createCrossExTransfer()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4975) | :closed_lock_with_key: | POST | `/crossex/transfers` | +| [getCrossExTransferHistory()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L4989) | :closed_lock_with_key: | GET | `/crossex/transfers` | +| [createCrossExOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5003) | :closed_lock_with_key: | POST | `/crossex/orders` | +| [cancelCrossExOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5017) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | +| [modifyCrossExOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5030) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | +| [getCrossExOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5045) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | +| [createCrossExConvertQuote()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5057) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | +| [createCrossExConvertOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5071) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | +| [updateCrossExAccount()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5083) | :closed_lock_with_key: | PUT | `/crossex/accounts` | +| [getCrossExAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5097) | :closed_lock_with_key: | GET | `/crossex/accounts` | +| [setCrossExPositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5109) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | +| [getCrossExPositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5123) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | +| [setCrossExMarginPositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5137) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | +| [getCrossExMarginPositionLeverage()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5153) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | +| [closeCrossExPosition()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5167) | :closed_lock_with_key: | DELETE | `/crossex/position` | +| [getCrossExInterestRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5181) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | +| [getCrossExFeeRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5194) | :closed_lock_with_key: | GET | `/crossex/fee` | +| [getCrossExPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5206) | :closed_lock_with_key: | GET | `/crossex/positions` | +| [getCrossExMarginPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5220) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | +| [getCrossExAdlRank()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5234) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | +| [getCrossExOpenOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5246) | :closed_lock_with_key: | GET | `/crossex/open_orders` | +| [getCrossExHistoryOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5260) | :closed_lock_with_key: | GET | `/crossex/history_orders` | +| [getCrossExHistoryPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5274) | :closed_lock_with_key: | GET | `/crossex/history_positions` | +| [getCrossExHistoryMarginPositions()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5288) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | +| [getCrossExHistoryMarginInterests()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5302) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | +| [getCrossExHistoryTrades()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5316) | :closed_lock_with_key: | GET | `/crossex/history_trades` | +| [getCrossExAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5330) | :closed_lock_with_key: | GET | `/crossex/account_book` | +| [getCrossExCoinDiscountRate()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5344) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | +| [getAlphaAccounts()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5362) | :closed_lock_with_key: | GET | `/alpha/accounts` | +| [getAlphaAccountBook()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5374) | :closed_lock_with_key: | GET | `/alpha/account_book` | +| [createAlphaQuote()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5388) | :closed_lock_with_key: | POST | `/alpha/quote` | +| [createAlphaOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5400) | :closed_lock_with_key: | POST | `/alpha/orders` | +| [getAlphaOrders()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5412) | :closed_lock_with_key: | GET | `/alpha/orders` | +| [getAlphaOrder()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5424) | :closed_lock_with_key: | GET | `/alpha/order` | +| [getAlphaCurrencies()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5436) | | GET | `/alpha/currencies` | +| [getAlphaTickers()](https://github.com/tiagosiebler/gateio-api/blob/master/src/RestClient.ts#L5448) | | GET | `/alpha/tickers` | # WebsocketAPIClient.ts diff --git a/examples/apidoc/RestClient/cancelCrossExOrder.js b/examples/apidoc/RestClient/cancelCrossExOrder.js new file mode 100644 index 0000000..da16c9b --- /dev/null +++ b/examples/apidoc/RestClient/cancelCrossExOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/orders/{order_id} + // METHOD: DELETE + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.cancelCrossExOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/cancelOTCOrder.js b/examples/apidoc/RestClient/cancelOTCOrder.js new file mode 100644 index 0000000..7b6ddd0 --- /dev/null +++ b/examples/apidoc/RestClient/cancelOTCOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/order/cancel + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.cancelOTCOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/closeCrossExPosition.js b/examples/apidoc/RestClient/closeCrossExPosition.js new file mode 100644 index 0000000..e39affb --- /dev/null +++ b/examples/apidoc/RestClient/closeCrossExPosition.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/position + // METHOD: DELETE + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.closeCrossExPosition(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createAlphaOrder.js b/examples/apidoc/RestClient/createAlphaOrder.js new file mode 100644 index 0000000..5a32e29 --- /dev/null +++ b/examples/apidoc/RestClient/createAlphaOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/orders + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createAlphaOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createAlphaQuote.js b/examples/apidoc/RestClient/createAlphaQuote.js new file mode 100644 index 0000000..2a07937 --- /dev/null +++ b/examples/apidoc/RestClient/createAlphaQuote.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/quote + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createAlphaQuote(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createCrossExConvertOrder.js b/examples/apidoc/RestClient/createCrossExConvertOrder.js new file mode 100644 index 0000000..b030092 --- /dev/null +++ b/examples/apidoc/RestClient/createCrossExConvertOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/convert/orders + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createCrossExConvertOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createCrossExConvertQuote.js b/examples/apidoc/RestClient/createCrossExConvertQuote.js new file mode 100644 index 0000000..283c279 --- /dev/null +++ b/examples/apidoc/RestClient/createCrossExConvertQuote.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/convert/quote + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createCrossExConvertQuote(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createCrossExOrder.js b/examples/apidoc/RestClient/createCrossExOrder.js new file mode 100644 index 0000000..bcbefc8 --- /dev/null +++ b/examples/apidoc/RestClient/createCrossExOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/orders + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createCrossExOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createCrossExTransfer.js b/examples/apidoc/RestClient/createCrossExTransfer.js new file mode 100644 index 0000000..c260628 --- /dev/null +++ b/examples/apidoc/RestClient/createCrossExTransfer.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/transfers + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createCrossExTransfer(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createOTCFiatOrder.js b/examples/apidoc/RestClient/createOTCFiatOrder.js new file mode 100644 index 0000000..28801f9 --- /dev/null +++ b/examples/apidoc/RestClient/createOTCFiatOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/order/create + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createOTCFiatOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createOTCQuote.js b/examples/apidoc/RestClient/createOTCQuote.js new file mode 100644 index 0000000..e83ce3f --- /dev/null +++ b/examples/apidoc/RestClient/createOTCQuote.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/quote + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createOTCQuote(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/createOTCStablecoinOrder.js b/examples/apidoc/RestClient/createOTCStablecoinOrder.js new file mode 100644 index 0000000..d4f8551 --- /dev/null +++ b/examples/apidoc/RestClient/createOTCStablecoinOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/stable_coin/order/create + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.createOTCStablecoinOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaAccountBook.js b/examples/apidoc/RestClient/getAlphaAccountBook.js new file mode 100644 index 0000000..ebd152e --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaAccountBook.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/account_book + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaAccountBook(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaAccounts.js b/examples/apidoc/RestClient/getAlphaAccounts.js new file mode 100644 index 0000000..d6fdcd8 --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaAccounts.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/accounts + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaAccounts(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaCurrencies.js b/examples/apidoc/RestClient/getAlphaCurrencies.js new file mode 100644 index 0000000..6f9ac9c --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaCurrencies.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/currencies + // METHOD: GET + // PUBLIC: YES + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaCurrencies(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaOrder.js b/examples/apidoc/RestClient/getAlphaOrder.js new file mode 100644 index 0000000..22ef22a --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/order + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaOrders.js b/examples/apidoc/RestClient/getAlphaOrders.js new file mode 100644 index 0000000..d15bfb8 --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaOrders.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/orders + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaOrders(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getAlphaTickers.js b/examples/apidoc/RestClient/getAlphaTickers.js new file mode 100644 index 0000000..4d18127 --- /dev/null +++ b/examples/apidoc/RestClient/getAlphaTickers.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /alpha/tickers + // METHOD: GET + // PUBLIC: YES + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getAlphaTickers(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExAccountBook.js b/examples/apidoc/RestClient/getCrossExAccountBook.js new file mode 100644 index 0000000..ba41446 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExAccountBook.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/account_book + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExAccountBook(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExAccounts.js b/examples/apidoc/RestClient/getCrossExAccounts.js new file mode 100644 index 0000000..d275239 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExAccounts.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/accounts + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExAccounts(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExAdlRank.js b/examples/apidoc/RestClient/getCrossExAdlRank.js new file mode 100644 index 0000000..0f5f64e --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExAdlRank.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/adl_rank + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExAdlRank(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExCoinDiscountRate.js b/examples/apidoc/RestClient/getCrossExCoinDiscountRate.js new file mode 100644 index 0000000..71a1731 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExCoinDiscountRate.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/coin_discount_rate + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExCoinDiscountRate(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExFeeRate.js b/examples/apidoc/RestClient/getCrossExFeeRate.js new file mode 100644 index 0000000..a8d3ac7 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExFeeRate.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/fee + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExFeeRate(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExHistoryMarginInterests.js b/examples/apidoc/RestClient/getCrossExHistoryMarginInterests.js new file mode 100644 index 0000000..1847b43 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExHistoryMarginInterests.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/history_margin_interests + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExHistoryMarginInterests(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExHistoryMarginPositions.js b/examples/apidoc/RestClient/getCrossExHistoryMarginPositions.js new file mode 100644 index 0000000..9a81326 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExHistoryMarginPositions.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/history_margin_positions + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExHistoryMarginPositions(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExHistoryOrders.js b/examples/apidoc/RestClient/getCrossExHistoryOrders.js new file mode 100644 index 0000000..4ca024a --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExHistoryOrders.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/history_orders + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExHistoryOrders(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExHistoryPositions.js b/examples/apidoc/RestClient/getCrossExHistoryPositions.js new file mode 100644 index 0000000..f95896f --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExHistoryPositions.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/history_positions + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExHistoryPositions(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExHistoryTrades.js b/examples/apidoc/RestClient/getCrossExHistoryTrades.js new file mode 100644 index 0000000..2c99467 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExHistoryTrades.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/history_trades + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExHistoryTrades(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExInterestRate.js b/examples/apidoc/RestClient/getCrossExInterestRate.js new file mode 100644 index 0000000..ea21885 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExInterestRate.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/interest_rate + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExInterestRate(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExMarginPositionLeverage.js b/examples/apidoc/RestClient/getCrossExMarginPositionLeverage.js new file mode 100644 index 0000000..2f85606 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExMarginPositionLeverage.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/margin_positions/leverage + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExMarginPositionLeverage(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExMarginPositions.js b/examples/apidoc/RestClient/getCrossExMarginPositions.js new file mode 100644 index 0000000..4191ab2 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExMarginPositions.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/margin_positions + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExMarginPositions(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExOpenOrders.js b/examples/apidoc/RestClient/getCrossExOpenOrders.js new file mode 100644 index 0000000..66f5e37 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExOpenOrders.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/open_orders + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExOpenOrders(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExOrder.js b/examples/apidoc/RestClient/getCrossExOrder.js new file mode 100644 index 0000000..1746fbb --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/orders/{order_id} + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExPositionLeverage.js b/examples/apidoc/RestClient/getCrossExPositionLeverage.js new file mode 100644 index 0000000..2ce2b4f --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExPositionLeverage.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/positions/leverage + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExPositionLeverage(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExPositions.js b/examples/apidoc/RestClient/getCrossExPositions.js new file mode 100644 index 0000000..c9ae5cb --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExPositions.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/positions + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExPositions(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExRiskLimits.js b/examples/apidoc/RestClient/getCrossExRiskLimits.js new file mode 100644 index 0000000..ead4176 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExRiskLimits.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/rule/risk_limits + // METHOD: GET + // PUBLIC: YES + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExRiskLimits(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExSymbols.js b/examples/apidoc/RestClient/getCrossExSymbols.js new file mode 100644 index 0000000..b6f710e --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExSymbols.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/rule/symbols + // METHOD: GET + // PUBLIC: YES + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExSymbols(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExTransferCoins.js b/examples/apidoc/RestClient/getCrossExTransferCoins.js new file mode 100644 index 0000000..c41b028 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExTransferCoins.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/transfers/coin + // METHOD: GET + // PUBLIC: YES + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExTransferCoins(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getCrossExTransferHistory.js b/examples/apidoc/RestClient/getCrossExTransferHistory.js new file mode 100644 index 0000000..c64cca7 --- /dev/null +++ b/examples/apidoc/RestClient/getCrossExTransferHistory.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/transfers + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getCrossExTransferHistory(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getOTCFiatOrderDetail.js b/examples/apidoc/RestClient/getOTCFiatOrderDetail.js new file mode 100644 index 0000000..7158ede --- /dev/null +++ b/examples/apidoc/RestClient/getOTCFiatOrderDetail.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/order/detail + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getOTCFiatOrderDetail(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getOTCFiatOrderList.js b/examples/apidoc/RestClient/getOTCFiatOrderList.js new file mode 100644 index 0000000..a9b4ab9 --- /dev/null +++ b/examples/apidoc/RestClient/getOTCFiatOrderList.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/order/list + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getOTCFiatOrderList(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getOTCStablecoinOrderList.js b/examples/apidoc/RestClient/getOTCStablecoinOrderList.js new file mode 100644 index 0000000..0d080c4 --- /dev/null +++ b/examples/apidoc/RestClient/getOTCStablecoinOrderList.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/stable_coin/order/list + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getOTCStablecoinOrderList(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/getOTCUserDefaultBank.js b/examples/apidoc/RestClient/getOTCUserDefaultBank.js new file mode 100644 index 0000000..3f12ff3 --- /dev/null +++ b/examples/apidoc/RestClient/getOTCUserDefaultBank.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/get_user_def_bank + // METHOD: GET + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.getOTCUserDefaultBank(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/markOTCOrderAsPaid.js b/examples/apidoc/RestClient/markOTCOrderAsPaid.js new file mode 100644 index 0000000..239824e --- /dev/null +++ b/examples/apidoc/RestClient/markOTCOrderAsPaid.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /otc/order/paid + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.markOTCOrderAsPaid(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/modifyCrossExOrder.js b/examples/apidoc/RestClient/modifyCrossExOrder.js new file mode 100644 index 0000000..8124844 --- /dev/null +++ b/examples/apidoc/RestClient/modifyCrossExOrder.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/orders/{order_id} + // METHOD: PUT + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.modifyCrossExOrder(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/setCrossExMarginPositionLeverage.js b/examples/apidoc/RestClient/setCrossExMarginPositionLeverage.js new file mode 100644 index 0000000..4df773f --- /dev/null +++ b/examples/apidoc/RestClient/setCrossExMarginPositionLeverage.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/margin_positions/leverage + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.setCrossExMarginPositionLeverage(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/setCrossExPositionLeverage.js b/examples/apidoc/RestClient/setCrossExPositionLeverage.js new file mode 100644 index 0000000..86e183f --- /dev/null +++ b/examples/apidoc/RestClient/setCrossExPositionLeverage.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/positions/leverage + // METHOD: POST + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.setCrossExPositionLeverage(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/RestClient/updateCrossExAccount.js b/examples/apidoc/RestClient/updateCrossExAccount.js new file mode 100644 index 0000000..95fccec --- /dev/null +++ b/examples/apidoc/RestClient/updateCrossExAccount.js @@ -0,0 +1,20 @@ +const { RestClient } = require('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: /crossex/accounts + // METHOD: PUT + // PUBLIC: NO + +const client = new RestClient({ + apiKey: 'insert_api_key_here', + apiSecret: 'insert_api_secret_here', +}); + +client.updateCrossExAccount(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index 9e2f33a..e4da211 100644 --- a/llms.txt +++ b/llms.txt @@ -38,7 +38,7 @@ Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files -- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ +- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/, dist/, lib/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter @@ -86,7 +86,9 @@ src/ types/ request/ account.ts + alpha.ts collateralLoan.ts + crossex.ts delivery.ts earn.ts earnuni.ts @@ -96,6 +98,7 @@ src/ marginuni.ts multicollateralLoan.ts options.ts + otc.ts rebate.ts spot.ts subaccount.ts @@ -104,7 +107,9 @@ src/ withdrawal.ts response/ account.ts + alpha.ts collateralloan.ts + crossex.ts delivery.ts earn.ts earnuni.ts @@ -114,6 +119,7 @@ src/ marginuni.ts multicollateralLoan.ts options.ts + otc.ts rebate.ts spot.ts subaccount.ts @@ -130,6 +136,8 @@ src/ RestClient.ts WebsocketAPIClient.ts WebsocketClient.ts +webpack/ + webpack.config.cjs .eslintrc.cjs .gitignore .nvmrc @@ -139,7 +147,6 @@ LICENSE.md package.json postBuild.sh README.md -tea.yaml tsconfig.cjs.json tsconfig.esm.json tsconfig.json @@ -603,2670 +610,3874 @@ node ./examples/spot/getTickers.js ``` ================ -File: examples/ws-api-client.ts +File: src/lib/logger.ts ================ -import { WebsocketAPIClient, WS_KEY_MAP } from '../src/index.js'; -// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +export type LogParams = null | any; ⋮---- -async function start() +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -/** - * Optional: authenticate in advance. This will prepare and authenticate a connection. - * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. - */ -// console.log(new Date(), 'Authenticating in advance...'); -// await client.getWSClient().connectWSAPI('spotV4'); -// console.log(new Date(), 'Authenticating in advance...OK!'); +// console.log(_params); ⋮---- -/* ============ SPOT TRADING EXAMPLES ============ */ +export type DefaultLogger = typeof DefaultLogger; + +================ +File: src/lib/misc-util.ts +================ +export function neverGuard(x: never, msg: string): Error + +================ +File: src/types/request/account.ts +================ +/**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ ⋮---- -// SPOT ORDER PLACE - Submit a new spot order +export interface CreateStpGroupReq { + name: string; + id?: number; + creator_id?: number; + create_time?: number; +} + +================ +File: src/types/request/alpha.ts +================ +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ ⋮---- -// SPOT ORDER CANCEL - Cancel a specific spot order +export interface GetAlphaAccountBookReq { + from: number; // Start timestamp for the query + to?: number; // End timestamp for the query, defaults to current time if not specified + page?: number; // Page number + limit?: number; // Maximum 100 items per page +} ⋮---- -// SPOT ORDER CANCEL BY IDS - Cancel orders by ID list +from: number; // Start timestamp for the query +to?: number; // End timestamp for the query, defaults to current time if not specified +page?: number; // Page number +limit?: number; // Maximum 100 items per page ⋮---- -// SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair +export interface CreateAlphaQuoteReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) + gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) + slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom +} ⋮---- -// SPOT ORDER AMEND - Update an existing spot order +currency: string; // Trading symbol +side: 'buy' | 'sell'; // Buy or sell orders +amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) +gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) +slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom ⋮---- -// SPOT ORDER STATUS - Get status of a specific spot order +export interface CreateAlphaOrderReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) + gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) + slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom + quote_id: string; // Quote ID returned from quotation API +} ⋮---- -// SPOT ORDER LIST - Get list of spot orders +currency: string; // Trading symbol +side: 'buy' | 'sell'; // Buy or sell orders +amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) +gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) +slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom +quote_id: string; // Quote ID returned from quotation API ⋮---- -/* ============ FUTURES TRADING EXAMPLES ============ */ +export interface GetAlphaOrdersReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + from?: number; // Start time for order query + to?: number; // End time for order query, defaults to current time if not specified + limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 + page?: number; // Page number +} ⋮---- -/** - * Gate has different websocket groups depending on the futures product. - * - * This affects which connection your command is sent to, so make sure to pass one matching your request. Look at WS_KEY_MAP (or the examples below) for details on the available product groups. - */ +currency: string; // Trading symbol +side: 'buy' | 'sell'; // Buy or sell orders +status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) +from?: number; // Start time for order query +to?: number; // End time for order query, defaults to current time if not specified +limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 +page?: number; // Page number ⋮---- -/** - * Also optional, as for spot. Keep in mind the first parameter (wsKey) might vary depending on which WS URL is needed. - */ +export interface GetAlphaOrderReq { + order_id: string; // Order ID +} ⋮---- -// console.log(new Date(), 'Authenticating in advance...'); -// await client.getWSClient().connectWSAPI(futuresConnectionGroup); -// await client.getWSClient().connectWSAPI('perpFuturesUSDTV4'); -// await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); -// await client.getWSClient().connectWSAPI('deliveryFuturesUSDTV4'); -// await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); -// console.log(new Date(), 'Authenticating in advance...OK!'); +order_id: string; // Order ID ⋮---- -// FUTURES ORDER PLACE - Submit a new futures order +export interface GetAlphaCurrenciesReq { + currency?: string; // Query currency information by currency symbol + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} ⋮---- -// FUTURES ORDER BATCH PLACE - Submit multiple futures orders +currency?: string; // Query currency information by currency symbol +limit?: number; // Maximum number of records returned in a single list +page?: number; // Page number ⋮---- -// FUTURES ORDER CANCEL - Cancel a specific futures order +export interface GetAlphaTickersReq { + currency?: string; // Query by specified currency name + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} ⋮---- -// FUTURES ORDER CANCEL BY IDS - Cancel futures orders by ID list +currency?: string; // Query by specified currency name +limit?: number; // Maximum number of records returned in a single list +page?: number; // Page number + +================ +File: src/types/request/collateralLoan.ts +================ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- -// FUTURES ORDER CANCEL ALL - Cancel all open futures orders +export interface SubmitLoanOrderReq { + collateral_amount: string; + collateral_currency: string; + borrow_amount: string; + borrow_currency: string; +} ⋮---- -// FUTURES ORDER AMEND - Update an existing futures order +export interface GetLoanOrdersReq { + page?: number; + limit?: number; + collateral_currency?: string; + borrow_currency?: string; +} ⋮---- -// FUTURES ORDER LIST - Get list of futures orders +export interface GetLoanRepaymentHistoryReq { + source: 'repay' | 'liquidate'; + borrow_currency?: string; + collateral_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} ⋮---- -// FUTURES ORDER STATUS - Get status of a specific futures order +export interface UpdateLoanCollateralReq { + order_id: number; + collateral_currency: string; + collateral_amount: string; + type: 'append' | 'redeem'; +} +⋮---- +export interface GetLoanCollateralRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + borrow_currency?: string; + collateral_currency?: string; +} ================ -File: examples/ws-private-perp-futures-wsapi.ts +File: src/types/request/crossex.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ +/**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ ⋮---- -import { LogParams, WebsocketClient } from '../src/index.js'; -// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +export interface GetCrossExSymbolsReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} ⋮---- -// Define a custom logger object to handle logging at different levels +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -// Trace level logging: used for detailed debugging information +export interface GetCrossExRiskLimitsReq { + symbols: string; // Trading Pair List, multiple separated by commas +} ⋮---- -// Uncomment the line below to enable trace logging -// console.log(new Date(), 'trace', ...params); +symbols: string; // Trading Pair List, multiple separated by commas ⋮---- -// Info level logging: used for general informational messages +export interface GetCrossExTransferCoinsReq { + coin?: string; // Currency +} ⋮---- -// Error level logging: used for error messages +coin?: string; // Currency ⋮---- -async function start() +export interface CreateCrossExTransferReq { + coin: string; // Currency + amount: string; // Transfer amount + from: string; // Transfer-in account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT + to: string; // Transfer-out account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT + text?: string; // User-defined ID +} ⋮---- -// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach -// client.on('update', (data) => { -// // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); -// console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); -// }); +coin: string; // Currency +amount: string; // Transfer amount +from: string; // Transfer-in account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT +to: string; // Transfer-out account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT +text?: string; // User-defined ID ⋮---- -// Something happened, attempting to reconnect +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 +} ⋮---- -// Reconnect successful +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 ⋮---- -// Connection closed. If unexpected, expect reconnect -> reconnected. +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'; // Default GTC + 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 +} ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" -// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach -// client.on('response', (data) => { -// console.info( -// new Date(), -// 'ws server reply ', -// JSON.stringify(data, null, 2), -// '\n', -// ); -// }); +text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only +symbol: string; // Unique identifier Exchange_Business_Base_Counter ⋮---- -// Optional, listen to this event if you prefer the event-driven approach. -// See below comments on event-driven vs promise-driven. -// client.on('authenticated', (data) => { -// console.error(new Date(), 'ws authenticated: ', data); -// }); +type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) +time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC'; // Default GTC +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 ⋮---- -/** - * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. - * - * You have two ways to handle responses on the WS API. You can either: - * - event-driven: process async `response` and `update` events from the websocket client, OR - * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). - */ +export interface ModifyCrossExOrderReq { + qty?: string; // modify amount + price?: string; // modify price +} ⋮---- -/** - * To authenticate, send an empty request to "futures.login". The SDK will handle all the parameters. - * - * Optional - you can inject rich types to set the response type - * const loginResult = await client.sendWSAPIRequest>('perpFuturesUSDTV4', 'futures.login'); - */ +qty?: string; // modify amount +price?: string; // modify price ⋮---- -/** - * For other channels, the 3rd parameter should have any parameters for the request (the payload). - * - * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. - * - */ +export interface CreateCrossExConvertQuoteReq { + exchange_type: string; // Exchange Type + from_coin: string; // Asset Sold + to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT) + from_amount: string; // Amount to sell +} ⋮---- -/** - * Submit futures order - */ +exchange_type: string; // Exchange Type +from_coin: string; // Asset Sold +to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT) +from_amount: string; // Amount to sell ⋮---- -size: 20, // positive for long, negative for short +export interface CreateCrossExConvertOrderReq { + quote_id: string; // Inquiry ID +} ⋮---- -/** - * Submit batch futures order - */ +quote_id: string; // Inquiry ID ⋮---- -size: 10, // positive for long, negative for short +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/CROSSEX) +} ⋮---- -size: 10, // positive for long, negative for short +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/CROSSEX) ⋮---- -/** - * Cancel futures order - */ +export interface GetCrossExAccountsReq { + exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE) +} ⋮---- -/** - * Cancel all futures orders - */ +exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE) ⋮---- -/** - * Update/Amend Futures order - */ +export interface SetCrossExPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} ⋮---- -/** - * Get orders list - */ +symbol: string; // Currency pair +leverage: string; // leverage ⋮---- -/** - * Get order status - */ - -================ -File: examples/ws-private-perp-futures.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; -// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +export interface GetCrossExPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} ⋮---- -// Define a custom logger object to handle logging at different levels +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -// Trace level logging: used for detailed debugging information +export interface SetCrossExMarginPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} ⋮---- -// Uncomment the line below to enable trace logging -// console.log(new Date(), 'trace', ...params); +symbol: string; // Currency pair +leverage: string; // leverage ⋮---- -// Info level logging: used for general informational messages +export interface GetCrossExMarginPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} ⋮---- -// Error level logging: used for error messages +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -async function start() +export interface CloseCrossExPositionReq { + symbol: string; // Trading Pair + position_side?: string; // Position Direction +} ⋮---- -// console.log('auth with: ', account); +symbol: string; // Trading Pair +position_side?: string; // Position Direction ⋮---- -// Data received +export interface GetCrossExInterestRateReq { + coin?: string; // Currency + exchange_type?: string; // Exchange +} ⋮---- -// Something happened, attempting to reconnect +coin?: string; // Currency +exchange_type?: string; // Exchange ⋮---- -// Reconnect successful +export interface GetCrossExPositionsReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange +} ⋮---- -// Connection closed. If unexpected, expect reconnect -> reconnected. +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +export interface GetCrossExMarginPositionsReq { + symbol?: string; // Currency pair + exchange_type?: string; // Exchange +} ⋮---- -// TODO: many private topics use your user ID +symbol?: string; // Currency pair +exchange_type?: string; // Exchange ⋮---- -/** - * Either send one topic (with params) at a time - */ -// client.subscribe({ -// topic: 'futures.usertrades', -// payload: [myUserID, '!all'], -// }, 'perpFuturesUSDTV4'); +export interface GetCrossExAdlRankReq { + symbol: string; // Trading Pair +} ⋮---- -/** - * Or send multiple topics in a batch (grouped by ws connection (WsKey)) - * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: - */ - -================ -File: examples/ws-private-spot-wsapi.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -⋮---- -import { LogParams, WebsocketClient } from '../src/index.js'; -// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +symbol: string; // Trading Pair ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -⋮---- -// Define a custom logger object to handle logging at different levels -⋮---- -// Trace level logging: used for detailed debugging information -⋮---- -// Uncomment the line below to enable trace logging -// console.log(new Date(), 'trace', ...params); +export interface GetCrossExOpenOrdersReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange + business_type?: string; // Business Type +} ⋮---- -// Info level logging: used for general informational messages +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange +business_type?: string; // Business Type ⋮---- -// Error level logging: used for error messages +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 +} ⋮---- -async function start() +page?: number; // Page number +limit?: number; // Maximum number of records returned in a single list ⋮---- -// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach -// client.on('update', (data) => { -// // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); -// console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); -// }); +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -// Something happened, attempting to reconnect +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 +} ⋮---- -// Reconnect successful +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -// Connection closed. If unexpected, expect reconnect -> reconnected. +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" -// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach -// client.on('response', (data) => { -// console.info( -// new Date(), -// 'ws server reply ', -// JSON.stringify(data, null, 2), -// '\n', -// ); -// }); +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 +} ⋮---- -// Optional, listen to this event if you prefer the event-driven approach. -// See below comments on event-driven vs promise-driven. -// client.on('authenticated', (data) => { -// console.error(new Date(), 'ws authenticated: ', data); -// }); +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -/** - * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. - * - * You have two ways to handle responses on the WS API. You can either: - * - event-driven: process async `response` and `update` events from the websocket client, OR - * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). - */ +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -/** - * No need to authenticate first - the SDK will automatically authenticate for you when you send your first request. - * - * Unless you want to prepare the connection before your first request, to speed up your first request. - */ +export interface GetCrossExHistoryMarginInterestsReq { + symbol?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + exchange_type?: string; +} ⋮---- -/** - * For other channels, the 3rd parameter should have any parameters for the request (the payload that goes in req_param in the docs). - * - * See WsAPIRequestsTopicMap for a topic->parameter map. - * - * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. - */ +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 +} ⋮---- -/** - * Submit spot order - */ +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -/** - * Cancel spot order - */ +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -/** - * Batch cancel spot order - */ +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 +} ⋮---- -/** - * Amend/Update spot order - */ +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -/** - * Get spot order status - */ +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -/** - * If you don't want to use await (and prefer the async event emitter), make sure to still include a catch block. - * - * The response will come async via the event emitter in the WS Client. - */ +export interface GetCrossExCoinDiscountRateReq { + coin?: string; + exchange_type?: string; // OKX/GATE/BINANCE +} ⋮---- -// client -// .sendWSAPIRequest('spotV4', 'spot.order_status', { -// order_id: '600995435390', -// currency_pair: 'BTC_USDT', -// }) -// .catch((e) => { -// console.error(`exception ws api call, get spot order status: `, e); -// }); +exchange_type?: string; // OKX/GATE/BINANCE ================ -File: examples/ws-private-spot.ts +File: src/types/request/delivery.ts ================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; -// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -⋮---- -// Define a custom logger object to handle logging at different levels -⋮---- -// Trace level logging: used for detailed debugging information +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ ⋮---- -// Uncomment the line below to enable trace logging -// console.log(new Date(), 'trace', ...params); +export interface GetDeliveryOrderBookReq { + settle: 'usdt'; + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} ⋮---- -// Info level logging: used for general informational messages +export interface GetDeliveryTradesReq { + settle: 'usdt'; + contract: string; + limit?: number; + last_id?: string; + from?: number; + to?: number; +} ⋮---- -// Error level logging: used for error messages +export interface GetDeliveryCandlesReq { + settle: 'usdt'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: + | '10s' + | '30s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '7d' + | '1w' + | '30d'; +} ⋮---- -async function start() +export interface GetDeliveryBookReq { + settle: 'usdt'; + limit?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} ⋮---- -// console.log('auth with: ', account); +export interface SubmitDeliveryFuturesOrderReq { + settle: 'usdt'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} ⋮---- -// Data received +export interface GetDeliveryOrdersReq { + settle: 'usdt'; + contract?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} ⋮---- -// Something happened, attempting to reconnect +export interface GetDeliveryTradingHistoryReq { + settle: 'usdt'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} ⋮---- -// Reconnect successful +export interface GetDeliveryClosedPositionsReq { + settle: 'usdt'; + contract?: string; + limit?: number; +} ⋮---- -// Connection closed. If unexpected, expect reconnect -> reconnected. +export interface GetDeliveryLiquidationHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +export interface GetDeliverySettlementHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} +export interface GetDeliveryAutoOrdersReq { + settle: 'usdt'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} + +================ +File: src/types/request/earn.ts +================ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ ⋮---- -// client.subscribe(topics, 'spotV4'); +export interface GetStructuredProductListReq { + status: string; + type?: string; + page?: number; + limit?: number; +} ⋮---- -// This has the same effect as above, it's just a different way of messaging which topic this is for -// const topicWithoutParamsAsObject: WsTopicRequest = { -// topic: 'spot.balances', -// }; -⋮---- -/** - * Either send one topic (with optional params) at a time - */ -// client.subscribe(topicWithoutParamsAsObject, 'spotV4'); -⋮---- -/** - * Or send multiple topics in a batch (grouped by ws connection (WsKey)) - * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: - */ -⋮---- -/** - * You can also subscribe in separate function calls as you wish. - * - * Any duplicate requests should get filtered out (e.g. here we subscribed to "spot.balances" twice, but the WS client will filter this out) - */ +export interface GetStructuredProductOrdersReq { + from?: number; + to?: number; + page?: number; + limit?: number; +} ================ -File: examples/ws-public.ts +File: src/types/request/earnuni.ts ================ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -import { WebsocketClient, WsTopicRequest } from '../src/index.js'; -// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` -⋮---- -// const customLogger = { -// // eslint-disable-next-line @typescript-eslint/no-unused-vars -// trace: (...params: LogParams): void => { -// console.log('trace', ...params); -// }, -// info: (...params: LogParams): void => { -// console.log('info', ...params); -// }, -// error: (...params: LogParams): void => { -// console.error('error', ...params); -// }, -// }; -⋮---- -async function start() -⋮---- -// Optional, inject a custom logger -// const client = new WebsocketClient({}, customLogger); -⋮---- -// Data received -⋮---- -// Something happened, attempting to reconnect +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== + */ ⋮---- -// Reconnect successful +export interface SubmitLendOrRedeemReq { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; +} ⋮---- -// Connection closed. If unexpected, expect reconnect -> reconnected. +export interface GetLendingOrdersReq { + currency?: string; + page?: number; + limit?: number; +} ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +export interface GetLendingRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'lend' | 'redeem'; +} ⋮---- -// const topicWithoutParamsAsString = 'spot.balances'; +export interface GetLendingInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +================ +File: src/types/request/flashswap.ts +================ +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ ⋮---- -// This has the same effect as above, it's just a different way of messaging which topic this is for -// const topicWithoutParamsAsObject: WsTopicRequest = { -// topic: 'spot.balances', -// }; +export interface SubmitFlashSwapOrderReq { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; +} ⋮---- -/** - * Either send one topic (with optional params) at a time - */ -// client.subscribe(tickersRequestWithParams, 'spotV4'); +export interface GetFlashSwapOrdersReq { + status?: number; + sell_currency?: string; + buy_currency?: string; + reverse?: boolean; + limit?: number; + page?: number; +} ⋮---- -/** - * Or send multiple topics in a batch (grouped by ws connection (WsKey)) - */ +export interface GetFlashSwapOrderReq { + order_id: number; +} ⋮---- -// /** -// * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: -// */ -// client.subscribe( -// [tickersRequestWithParams, rawTradesRequestWithParams, topicWithoutParamsAsString], -// 'spotV4', -// ); +export interface SubmitFlashSwapOrderPreviewReq { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; +} ================ -File: src/lib/websocket/websocket-util.ts +File: src/types/request/margin.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. +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== */ ⋮---- -/** - * Spot & Margin - * https://www.gate.io/docs/developers/apiv4/ws/en/ - */ +export interface GetMarginBalanceHistoryReq { + currency?: string; + currency_pair?: string; + type?: string; + from?: number; + to?: number; + page?: number; + limit?: number; +} ⋮---- -/** - * Perpetual futures (USDT) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ +export interface GetCrossMarginAccountHistoryReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; +} ⋮---- -/** - * Perpetual futures (BTC) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ +export interface SubmitCrossMarginBorrowLoanReq { + currency: string; + amount: string; + text?: string; +} ⋮---- -/** - * Delivery Futures (USDT) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ +export interface GetCrossMarginBorrowHistoryReq { + status: number; + currency?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} ⋮---- -/** - * Delivery Futures (BTC) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ +export interface GetCrossMarginRepaymentsReq { + currency?: string; + loan_id?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} ⋮---- -/** - * Options - * https://www.gate.io/docs/developers/options/ws/en/ - */ +export interface GetCrossMarginInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +================ +File: src/types/request/marginuni.ts +================ +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ ⋮---- -/** - * Announcements V4 - * https://www.gate.io/docs/developers/options/ws/en/ - */ +export interface GetMarginUNILoansReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; +} ⋮---- -/** 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 interface GetMarginUNILoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + currency_pair?: string; + page?: number; + limit?: number; +} ⋮---- -export type FuturesWsKey = - | typeof WS_KEY_MAP.perpFuturesUSDTV4 - | typeof WS_KEY_MAP.perpFuturesBTCV4 - | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 - | typeof WS_KEY_MAP.deliveryFuturesBTCV4; +export interface GetMarginUNIInterestRecordsReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} ⋮---- -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; +export interface GetMarginUNIMaxBorrowReq { + currency: string; + currency_pair: string; } -⋮---- -/** - * 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. + +================ +File: src/types/request/multicollateralLoan.ts +================ +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== */ -export function getPromiseRefForWSAPIRequest( - requestEvent: WSAPIRequest, -): string -⋮---- -export function getPrivateSpotTopics(): string[] -⋮---- -// Consumeable channels for spot ⋮---- -// WebSocket API for spot +export interface SubmitMultiLoanOrderReq { + order_id?: string; + order_type?: string; + fixed_type?: string; + fixed_rate?: string; + auto_renew?: boolean; + auto_repay?: boolean; + borrow_currency: string; + borrow_amount: string; + collateral_currencies?: { + currency?: string; + amount?: string; + }[]; +} +export interface GetMultiLoanOrdersReq { + page?: number; + limit?: number; + sort?: string; + order_type?: string; +} ⋮---- -export function getPrivateFuturesTopics(): string[] +export interface RepayMultiLoanReq { + order_id: number; + repay_items: { + currency?: string; + amount?: string; + repaid_all?: boolean; + }[]; +} ⋮---- -// These are the same for perps vs delivery futures +export interface GetMultiLoanRepayRecordsReq { + type: 'repay' | 'liquidate'; + borrow_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} ⋮---- -export function getPrivateOptionsTopics(): string[] +export interface UpdateMultiLoanReq { + order_id: number; + type: 'append' | 'redeem'; + collaterals?: { + currency?: string; + amount?: 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 +export interface GetMultiLoanAdjustmentRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + collateral_currency?: string; +} ================ -File: src/lib/websocket/WsStore.ts +File: src/types/request/options.ts ================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { DefaultLogger } from '../logger.js'; -import { - DeferredPromise, - WSConnectedResult, - WsConnectionStateEnum, - WsStoredState, -} from './WsStore.types.js'; -⋮---- -/** - * Simple comparison of two objects, only checks 1-level deep (nested objects won't match) +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== */ -export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean -⋮---- -type DeferredPromiseRef = - (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF]; -⋮---- -export class WsStore< -WsKey extends string, -⋮---- -constructor(logger: DefaultLogger) -⋮---- -/** Get WS stored state for key, optionally create if missing */ -get( - key: WsKey, - createIfMissing?: true, - ): WsStoredState; -⋮---- -get( - key: WsKey, - createIfMissing?: false, - ): WsStoredState | undefined; +export interface GetOptionsSettlementHistoryReq { + underlying: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} +export interface GetOptionsMySettlementsReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -get( - key: WsKey, - createIfMissing?: boolean, -): WsStoredState | undefined +export interface GetOptionsOrderBookReq { + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} ⋮---- -getKeys(): WsKey[] +export interface GetOptionsCandlesReq { + contract: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} ⋮---- -create(key: WsKey): WsStoredState | undefined +export interface GetOptionsUnderlyingCandlesReq { + underlying: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} ⋮---- -delete(key: WsKey): void +export interface GetOptionsTradesReq { + contract?: string; + type?: 'C' | 'P'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -// TODO: should we allow this at all? Perhaps block this from happening... +export interface GetOptionsAccountChangeReq { + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; +} ⋮---- -/* connection websocket */ +export interface SubmitOptionsOrderReq { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; +} ⋮---- -hasExistingActiveConnection(key: WsKey): boolean +export interface GetOptionsOrdersReq { + contract?: string; + underlying?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -getWs(key: WsKey): WebSocket | undefined +export interface GetOptionsPersonalHistoryReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -setWs(key: WsKey, wsConnection: WebSocket): WebSocket +export interface OptionsMMPSettingsReq { + underlying: string; + window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP + frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called + qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) + delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) +} ⋮---- -/** - * deferred promises - */ -⋮---- -getDeferredPromise( - wsKey: WsKey, - promiseRef: string | DeferredPromiseRef, -): DeferredPromise | undefined -⋮---- -createDeferredPromise( - wsKey: WsKey, - promiseRef: string | DeferredPromiseRef, - throwIfExists: boolean, -): DeferredPromise -⋮---- -// console.log('existing promise'); +window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP +frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called +qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) +delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) + +================ +File: src/types/request/otc.ts +================ +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -// console.log('create promise'); +export interface CreateOTCQuoteReq { + side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount + pay_coin: string; // Currency the user pays + get_coin: string; // Currency the user receives + pay_amount?: string; // User payment currency amount (required if side is PAY) + get_amount?: string; // Amount of currency received by user (required if side is GET) + create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement + promotion_code?: string; // Promotion code (optional) +} +⋮---- +side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount +pay_coin: string; // Currency the user pays +get_coin: string; // Currency the user receives +pay_amount?: string; // User payment currency amount (required if side is PAY) +get_amount?: string; // Amount of currency received by user (required if side is GET) +create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement +promotion_code?: string; // Promotion code (optional) +⋮---- +export interface CreateOTCFiatOrderReq { + type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + side: string; // Quote direction returned by the quote API (used for order validation) + crypto_currency: string; // Cryptocurrency + fiat_currency: string; // Fiat currency + crypto_amount: string; // Amount of cryptocurrency + fiat_amount: string; // Fiat amount + promotion_code?: string; // Promotion code + quote_token: string; // Parameter returned by the quote API + bank_id: string; // Bank card ID used for the order (retrieved via the default bank card API) +} +⋮---- +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 +bank_id: string; // Bank card ID used for the order (retrieved via the default bank card API) +⋮---- +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) + promotion_code?: string; // Promotion code + quote_token?: string; // Parameter returned by the quote API +} +⋮---- +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) +promotion_code?: string; // Promotion code +quote_token?: string; // Parameter returned by the quote API +⋮---- +export interface MarkOTCOrderAsPaidReq { + order_id: string; // Order ID +} +⋮---- +order_id: string; // Order ID +⋮---- +export interface CancelOTCOrderReq { + order_id: string; // Order ID +} +⋮---- +order_id: string; // Order ID +⋮---- +export interface GetOTCFiatOrderListReq { + type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + fiat_currency?: string; // Fiat currency + crypto_currency?: string; // Digital currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // DONE: Completed + pn?: string; // Page number + ps?: string; // Number of items per page +} +⋮---- +type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) +fiat_currency?: string; // Fiat currency +crypto_currency?: string; // Digital currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // DONE: Completed +pn?: string; // Page number +ps?: string; // Number of items per page +⋮---- +export interface GetOTCStablecoinOrderListReq { + page_size?: string; // Number of records per page + page_number?: string; // Page number + coin_name?: string; // Order currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed +} +⋮---- +page_size?: string; // Number of records per page +page_number?: string; // Page number +coin_name?: string; // Order currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed +⋮---- +export interface GetOTCFiatOrderDetailReq { + order_id: string; // Order ID +} +⋮---- +order_id: string; // Order ID + +================ +File: src/types/request/rebate.ts +================ +export interface GetAgencyTransactionHistoryReq { + currency_pair?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -// TODO: Once stable, use Promise.withResolvers in future +export interface GetAgencyCommissionHistoryReq { + currency?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -resolveDeferredPromise( - wsKey: WsKey, - promiseRef: string | DeferredPromiseRef, - value: unknown, - removeAfter: boolean, -): void +export interface GetPartnerSubordinateListReq { + user_id?: number; + limit?: number; + offset?: number; +} ⋮---- -rejectDeferredPromise( - wsKey: WsKey, - promiseRef: string | DeferredPromiseRef, - value: unknown, - removeAfter: boolean, -): void +export interface GetBrokerCommissionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; + from?: number; + to?: number; +} ⋮---- -removeDeferredPromise( - wsKey: WsKey, - promiseRef: string | DeferredPromiseRef, -): void +export interface GetBrokerTransactionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; + from?: number; + to?: number; +} ⋮---- -// Just in case it's pending +// Interfaces for request and response +export interface PartnerTransactionReq { + currency_pair?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +================ +File: src/types/request/subaccount.ts +================ +export interface CreateSubAccountReq { + login_name: string; + remark?: string; + password?: string; + email?: string; +} ⋮---- -rejectAllDeferredPromises(wsKey: WsKey, reason: string): void +export interface CreateSubAccountApiKeyReq { + user_id: number; + mode?: number; // Mode: 1 - classic, 2 - portfolio account + name?: string; // API key name + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; // Permission name + read_only?: boolean; // Read only + }[]; + ip_whitelist?: string[]; // IP white list +} ⋮---- -// Skip reserved keys, such as the connection promise +mode?: number; // Mode: 1 - classic, 2 - portfolio account +name?: string; // API key name ⋮---- -/** Get promise designed to track a connection attempt in progress. Resolves once connected. */ -getConnectionInProgressPromise( - wsKey: WsKey, -): DeferredPromise | undefined +| 'loan'; // Permission name +read_only?: boolean; // Read only ⋮---- -getAuthenticationInProgressPromise( - wsKey: WsKey, -): DeferredPromise +export type UpdateSubAccountApiKeyReq = { + key: string; +} & CreateSubAccountApiKeyReq; + +================ +File: src/types/request/withdrawal.ts +================ +/**================================================================================================================================ + * WITHDRAW + * ========================================================================================================================== + */ ⋮---- -createAuthenticationInProgressPromise( - wsKey: WsKey, - throwIfExists: boolean, -): DeferredPromise -⋮---- -getTopicsByKey(): Record> -⋮---- -/** - * Find matching "topic" request from the store - * @param key - * @param topic - * @returns - */ -getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) -⋮---- -addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) -⋮---- -// Check for duplicate topic. If already tracked, don't store this one -⋮---- -deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) -⋮---- -// Check if we're subscribed to a topic like this +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; // Attribute COMMON: Normal Order, LIQ: Liquidation Takeover Order, REDUCE: Liquidation Reduce Order, ADL: Auto-Reduce + 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; // Attribute COMMON: Normal Order, LIQ: Liquidation Takeover Order, REDUCE: Liquidation Reduce Order, ADL: Auto-Reduce +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 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/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/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 +} +⋮---- +symbol: string; // Currency pair +taker_fee_rate: string; // Taker fee rate +maker_fee_rate: string; // Maker fee rate +⋮---- +export interface CrossExFeeRate { + spot_maker_fee: string; // spot Maker fee rate + spot_taker_fee: string; // spot Taker fee rate + future_maker_fee: string; // contract Maker fee rate + future_taker_fee: string; // contract Taker fee rate + special_fee_list: CrossExSpecialFee[]; +} +⋮---- +spot_maker_fee: string; // spot Maker fee rate +spot_taker_fee: string; // spot Taker fee rate +future_maker_fee: string; // contract Maker fee rate +future_taker_fee: string; // contract Taker fee rate +⋮---- +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 + 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; 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; 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 ================ -File: src/lib/websocket/WsStore.types.ts +File: src/types/response/earn.ts ================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import WebSocket from 'isomorphic-ws'; +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ ⋮---- -export enum WsConnectionStateEnum { - INITIAL = 0, - CONNECTING = 1, - CONNECTED = 2, - CLOSING = 3, - RECONNECTING = 4, - // ERROR_RECONNECTING = 5, - ERROR = 5, +export interface DualInvestmentProduct { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_copies: number; + max_copies: number; + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; } ⋮---- -// ERROR_RECONNECTING = 5, -⋮---- -export interface DeferredPromise { - resolve?: (value: TSuccess) => TSuccess; - reject?: (value: TError) => TError; - promise?: Promise; +export interface DualInvestmentOrder { + id: number; + plan_id: number; + copies: string; + invest_amount: string; + settlement_amount: string; + create_time: number; + complete_time: number; + status: + | 'INIT' + | 'SETTLEMENT_SUCCESS' + | 'SETTLEMENT_PROCESSING' + | 'CANCELED' + | 'FAILED'; + invest_currency: string; + exercise_currency: string; + exercise_price: string; + settlement_price: string; + settlement_currency: string; + apy_display: string; + apy_settlement: string; + delivery_time: number; + text: string; } ⋮---- -export interface WSConnectedResult { - wsKey: string; - ws: WebSocket; +export interface StructuredProduct { + id: number; + type: string; + name_en: string; + investment_coin: string; + investment_period: string; + min_annual_rate: string; + mid_annual_rate: string; + max_annual_rate: string; + watch_market: string; + start_time: number; + end_time: number; + status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; } ⋮---- -export interface WsStoredState { - /** The currently active websocket connection */ - ws?: WebSocket; - /** The current lifecycle state of the connection (enum) */ - connectionState?: WsConnectionStateEnum; - connectionStateChangedAt?: Date; - /** A timer that will send an upstream heartbeat (ping) when it expires */ - activePingTimer?: ReturnType | undefined; - /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ - activePongTimer?: ReturnType | undefined; - /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ - activeReconnectTimer?: ReturnType | undefined; - /** - * When a connection attempt is in progress (even for reconnect), a promise is stored here. - * - * This promise will resolve once connected (and will then get removed); - */ - // connectionInProgressPromise?: DeferredPromise | undefined; - deferredPromiseStore: Record; - /** - * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) - * - * A "Set" and a deep-object-match are used to ensure we only subscribe to a - * topic once (tracking a list of unique topics we're expected to be connected to) - */ - subscribedTopics: Set; - /** Whether this connection has completed authentication (only applies to private connections) */ - isAuthenticated?: boolean; - /** - * Whether this connection has completed authentication before for the Websocket API, so it k - * nows to automatically reauth if reconnected - */ - didAuthWSAPI?: boolean; - /** To reauthenticate on the WS API, which channel do we send to? */ - WSAPIAuthChannel?: string; +export interface StructuredProductOrder { + id: number; + pid: string; + lock_coin: string; + amount: string; + status: 'SUCCESS' | 'FAILED' | 'DONE'; + income: string; + create_time: number; } -⋮---- -/** The currently active websocket connection */ -⋮---- -/** The current lifecycle state of the connection (enum) */ -⋮---- -/** A timer that will send an upstream heartbeat (ping) when it expires */ -⋮---- -/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ -⋮---- -/** If a reconnection is in progress, this will have the timer for the delayed reconnect */ -⋮---- -/** - * When a connection attempt is in progress (even for reconnect), a promise is stored here. - * - * This promise will resolve once connected (and will then get removed); - */ -// connectionInProgressPromise?: DeferredPromise | undefined; -⋮---- -/** - * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) - * - * A "Set" and a deep-object-match are used to ensure we only subscribe to a - * topic once (tracking a list of unique topics we're expected to be connected to) - */ -⋮---- -/** Whether this connection has completed authentication (only applies to private connections) */ -⋮---- -/** - * Whether this connection has completed authentication before for the Websocket API, so it k - * nows to automatically reauth if reconnected - */ -⋮---- -/** To reauthenticate on the WS API, which channel do we send to? */ ================ -File: src/lib/BaseRestClient.ts +File: src/types/response/earnuni.ts ================ -import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; -import https from 'https'; -⋮---- -import { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; -⋮---- -/** - * Used to switch how authentication/requests work under the hood +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== */ ⋮---- -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 LendingCurrency { + currency: string; + min_lend_amount: string; + max_lend_amount: string; + max_rate: string; + min_rate: string; } ⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; +export interface LendingOrder { + currency: string; + current_amount: string; + amount: string; + lent_amount: string; + frozen_amount: string; + min_rate: string; + interest_status: string; + reinvest_left_amount: string; + create_time: number; + update_time: number; } ⋮---- -type SignMethod = 'gateV4'; +export interface LendingRecord { + currency: string; + amount: string; + last_wallet_amount: string; + last_lent_amount: string; + last_frozen_amount: string; + type: 'lend' | 'redeem'; + create_time: number; +} ⋮---- -/** - * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. - * This type anticipates these are possible in any combination. - * - * The request builder will automatically handle where parameters should go. - */ -type ParamsInQueryBodyOrHeader = { - query?: object; - body?: object; - headers?: object; -}; -⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses +export interface LendingInterestRecord { + status: number; + currency: string; + actual_rate: string; + interest: string; + interest_status: string; + create_time: number; +} + +================ +File: src/types/response/flashswap.ts +================ +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== */ ⋮---- -// request: { -// url: response.config.url, -// method: response.config.method, -// data: response.config.data, -// headers: response.config.headers, -// }, +export interface FlashSwapCurrencyPair { + currency_pair: string; + sell_currency: string; + buy_currency: string; + sell_min_amount: string; + sell_max_amount: string; + buy_min_amount: string; + buy_max_amount: string; +} ⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. +export interface FlashSwapOrder { + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; +} +⋮---- +export interface SubmitFlashSwapOrderPreviewResp { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; +} + +================ +File: src/types/response/multicollateralLoan.ts +================ +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== */ -function deleteUndefinedValues(params?: any): void ⋮---- -export abstract class BaseRestClient +export interface MultiLoanOrder { + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; +} ⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; +export interface RepayMultiLoanResp { + order_id: number; + repaid_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + repaid_principal: string; + repaid_interest: string; + }[]; +} ⋮---- -/** - * 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 MultiLoanRepayRecord { + order_id: number; + record_id: number; + init_ltv: string; + before_ltv: string; + after_ltv: string; + borrow_time: number; + repay_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + repaid_currencies: { + currency: string; + index_price: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + repaid_amount_usdt: string; + }[]; + total_interest_list: { + currency: string; + index_price: string; + amount: string; + amount_usdt: string; + }[]; + left_repay_interest_list: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} ⋮---- -/** Throw errors if any request params are empty */ +export interface UpdateMultiLoanResp { + order_id: number; + collateral_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + amount: string; + }[]; +} ⋮---- -/** in ms == 5 minutes by default */ +export interface MultiLoanAdjustmentRecord { + order_id: number; + record_id: number; + before_ltv: string; + after_ltv: string; + operate_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} ⋮---- -/** 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 MultiLoanCurrencyQuota { + currency: string; + index_price: string; + min_quota: string; + left_quota: string; + left_quote_usdt: string; +} ⋮---- -// If enabled, configure a https agent with keepAlive enabled +export interface MultiLoanSupportedCurrencies { + loan_currencies: { + currency: string; + price: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + discount: string; + }[]; +} ⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +export interface MultiLoanRatio { + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; +} ⋮---- -// 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 MultiLoanFixedRate { + currency: string; + rate_7d: string; + rate_30d: string; + update_time: number; +} + +================ +File: src/types/response/otc.ts +================ +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +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 + validity_period?: string; + ex_rate?: string; + usdc_rate?: string; + refresh_limit?: number; + refresh_limit_msg?: string; + }; + timestamp: number; +} ⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set +type: string; // BUY (on-ramp) or SELL (off-ramp) ⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number +rate_reci: string; // Reciprocal of the exchange rate ⋮---- -protected get(endpoint: string, params?: object) +order_type: string; // FIAT or STABLE +quote_token: string; // Quote token required when placing an order ⋮---- -// GET only supports params in the query string +export interface CreateOTCFiatOrderResp { + code: number; + message: string; + timestamp: number; +} ⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; +} ⋮---- -protected getPrivate(endpoint: string, params?: object) +export interface OTCBankInfo { + 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; +} ⋮---- -// GET only supports params in the query string +id: string; // Bank ID (required for order placement) ⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetOTCUserDefaultBankResp { + code: number; + message: string; + data: OTCBankInfo; + timestamp: number; +} ⋮---- -protected deletePrivate( - endpoint: string, - params?: ParamsInQueryBodyOrHeader, -) +export interface MarkOTCOrderAsPaidResp { + code: number; + message: string; + timestamp: number; +} ⋮---- -protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface CancelOTCOrderResp { + code: number; + message: string; + timestamp: number; +} ⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +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 + 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 + gate_bank_account_iban: string; // Bank account + promotion_code: string; // Promotion code +} ⋮---- -/** - * @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 +time: string; // Current time +timestamp: number; // Current timestamp ⋮---- -// Sanity check to make sure it's only ever prefixed by one forward slash +trade_no: string; // Trade number +type: string; // Quote direction buy/sell/all +status: string; // Order Status ⋮---- -// Build a request and handle signature process +fiat_currency: string; // Fiat type ⋮---- -// Dispatch request +fiat_amount: string; // Fiat amount +crypto_currency: string; // Stablecoin ⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format +crypto_amount: string; // Stablecoin amount +rate: string; // Exchange rate +transfer_remark: string; // Remark +gate_bank_account_iban: string; // Bank account +promotion_code: string; // Promotion code ⋮---- -// Throw API rejections by parsing the response code from the body +export interface GetOTCFiatOrderListResp { + code: number; + message: string; + data: { + pn: number; + ps: number; + total_pn: number; + count: number; + list: OTCFiatOrderListItem[]; + }; +} ⋮---- -/** - * @private generic handler to parse request exceptions - */ -parseException(e: any, request: AxiosRequestConfig): unknown +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 +} +⋮---- +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[]; + }; +} ⋮---- -// Something happened in setting up the request that triggered an error +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 + 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 +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; +} + +================ +File: src/types/response/subaccount.ts +================ +export interface SubAccount { + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; +} ⋮---- -// request made but no response received +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; +} ⋮---- -// The request was made and the server responded with a status code -// that falls out of the range of 2xx +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; +} ⋮---- -// console.error('err: ', response?.data); +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'; ⋮---- -// Prevent credentials from leaking into error messages +export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- -/** - * @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 WsRequestAuthGate { + method: 'api_key'; + KEY: string; + SIGN: string; +} ⋮---- -const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds +export interface WsRequestPing { + time: number; + channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; +} ⋮---- -// recvWindow: this.options.recvWindow, +export interface WsRequestOperationGate< + TWSTopic extends string, + TWSPayload = any, +> { + time: number; + id?: number; + channel: TWSTopic; + auth?: WsRequestAuthGate; + event?: WsOperation; + payload?: TWSPayload; +} ⋮---- -// It's possible to override the recv window on a per rquest level +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/index.ts +================ +// Request Types ⋮---- -// console.log('sign params: ', { -// requestBodyToHash, -// paramsStr: toSign, -// url: this.baseUrl, -// urlPath: this.baseUrlPath, -// }); +// Response Types ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +// Websockets Types ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: true, - ): Promise>; +// Shared Types + +================ +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" +} + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: false | undefined, - ): Promise>; +import type { Config } from 'jest'; ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: boolean, -) -⋮---- -/** Returns an axios request object. Handles signing process automatically if this is a private API call */ -private async buildRequest( - method: Method, - endpoint: string, - url: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, -): Promise - -================ -File: src/lib/BaseWSClient.ts -================ -import EventEmitter from 'events'; -import WebSocket from 'isomorphic-ws'; +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -import { - WebsocketClientOptions, - WSClientConfigurableOptions, -} from '../types/websockets/client.js'; -import { WsOperation } from '../types/websockets/requests.js'; -import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; -import { DefaultLogger } from './logger.js'; -import { isMessageEvent, MessageEventLike } from './requestUtils.js'; -import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; -import { - safeTerminateWs, - WsTopicRequest, - WsTopicRequestOrStringTopic, -} from './websocket/websocket-util.js'; -import { WsStore } from './websocket/WsStore.js'; -import { - WSConnectedResult, - WsConnectionStateEnum, -} from './websocket/WsStore.types.js'; +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -interface WSClientEventMap { - /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ - open: (evt: { - wsKey: WsKey; - event: any; - wsUrl: string; - ws: WebSocket; - }) => void /** Reconnecting a dropped connection */; - reconnect: (evt: { wsKey: WsKey; event: any }) => void; - /** Successfully reconnected a connection that dropped */ - reconnected: (evt: { - wsKey: WsKey; - event: any; - wsUrl: string; - ws: WebSocket; - }) => void; - /** Connection closed */ - close: (evt: { wsKey: WsKey; event: any }) => void; - /** Received reply to websocket command (e.g. after subscribing to topics) */ - response: (response: any & { wsKey: WsKey }) => void; - /** Received data for topic */ - update: (response: any & { wsKey: WsKey }) => void; - /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ - exception: (response: any & { wsKey: WsKey }) => void; - error: (response: any & { wsKey: WsKey }) => void; - /** Confirmation that a connection successfully authenticated */ - authenticated: (event: { wsKey: WsKey; event: any }) => void; -} +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -}) => void /** Reconnecting a dropped connection */; +// Indicates whether the coverage information should be collected while executing the test ⋮---- -/** Successfully reconnected a connection that dropped */ +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -/** Connection closed */ +// The directory where Jest should output its coverage files ⋮---- -/** Received reply to websocket command (e.g. after subscribing to topics) */ +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -/** Received data for topic */ +// Indicates which provider should be used to instrument code for coverage ⋮---- -/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -/** Confirmation that a connection successfully authenticated */ +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -export interface EmittableEvent { - eventType: 'response' | 'update' | 'exception' | 'authenticated'; - event: TEvent; -} +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 -export interface BaseWebsocketClient { - on>( - event: U, - listener: WSClientEventMap[U], - ): this; - - emit>( - event: U, - ...args: Parameters[U]> - ): boolean; -} +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -on>( - event: U, - listener: WSClientEventMap[U], - ): this; +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -emit>( - event: U, - ...args: Parameters[U]> - ): boolean; +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -/** - * Users can conveniently pass topics as strings or objects (object has topic name + optional params). - * - * This method normalises topics into objects (object has topic name + optional params). - */ -function getNormalisedTopicRequests( - wsTopicRequests: WsTopicRequestOrStringTopic[], -): WsTopicRequest[] +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -// passed as string, convert to object +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -// already a normalised object, thanks to user +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -/** - * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" - */ -// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -export abstract class BaseWebsocketClient< +// The 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%", ⋮---- -/** - * The WS connections supported by the client, each identified by a unique primary key - */ +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], ⋮---- -/** - * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected - */ +// An array of file extensions your modules use ⋮---- -constructor( - options?: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, -) +// modulePaths: ['src'], ⋮---- -// Some defaults: +// 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: {}, ⋮---- -// Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], ⋮---- -// Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. +// Activates notifications for test results +// notify: false, ⋮---- -// Automatically re-auth WS API, if we were auth'd before and get reconnected +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +// A preset that is used as a base for Jest's configuration +// preset: undefined, ⋮---- -protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; +// Run tests from one or more projects +// projects: undefined, ⋮---- -protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, ⋮---- -protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; +// Automatically reset mock state before every test +// resetMocks: false, ⋮---- -protected abstract isWsPing(data: any): boolean; +// Reset the module registry before running each individual test +// resetModules: false, ⋮---- -protected abstract isWsPong(data: any): boolean; +// A path to a custom resolver +// resolver: undefined, ⋮---- -protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; +// Automatically restore mock state and implementation before every test +// restoreMocks: false, ⋮---- -protected abstract isPrivateTopicRequest( - request: WsTopicRequest, - wsKey: TWSKey, - ): boolean; +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, ⋮---- -protected abstract getPrivateWSKeys(): TWSKey[]; +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], ⋮---- -protected abstract getWsUrl(wsKey: TWSKey): string; +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", ⋮---- -protected abstract getMaxTopicsPerSubscribeEvent( - wsKey: TWSKey, - ): number | null; +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], ⋮---- -/** - * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics - */ -protected abstract getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: TWSKey, - operation: WsOperation, - ): Promise; +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected abstract resolveEmittableEvents( - wsKey: TWSKey, - event: MessageEventLike, - ): EmittableEvent[]; +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -protected abstract connectAll(): Promise[]; +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], ⋮---- -protected isPrivateWsKey(wsKey: TWSKey): boolean +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", ⋮---- -/** Returns auto-incrementing request ID, used to track promise references for async requests */ -protected getNewRequestId(): string -⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params?: any, - ): Promise; +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params: any, - ): Promise; +// Adds a location field to test results +// testLocationInResults: false, ⋮---- -public getTimeOffsetMs() +// The glob patterns Jest uses to detect test files ⋮---- -// TODO: not implemented -public setTimeOffsetMs(newOffset: number) +// "**/__tests__/**/*.[jt]s?(x)", ⋮---- -/** - * Don't call directly! Use subscribe() instead! - * - * Subscribe to one or more topics on a WS connection (identified by WS Key). - * - * - Topics are automatically cached - * - Connections are automatically opened, if not yet connected - * - Authentication is automatically handled - * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). - * - * @param wsRequests array of topics to subscribe to - * @param wsKey ws key referring to the ws connection these topics should be subscribed on - */ -protected subscribeTopicsForWsKey( - wsTopicRequests: WsTopicRequestOrStringTopic[], - wsKey: TWSKey, -) +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], ⋮---- -// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, ⋮---- -// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", ⋮---- -/** - * Are we in the process of connection? Nothing to send yet. - */ +// A map from regular expressions to paths to transformers +// transform: undefined, ⋮---- -// We're connected. Check if auth is needed and if already authenticated +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], ⋮---- -/** - * If not authenticated yet and auth is required, don't request topics yet. - * - * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. - */ +// Prevents import esm module error from v1 axios release, issue #5026 ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +// 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, ⋮---- -protected unsubscribeTopicsForWsKey( - wsTopicRequests: WsTopicRequestOrStringTopic[], - wsKey: TWSKey, -) +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], ⋮---- -// If not connected, don't need to do anything. -// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. +// Whether to use watchman for file crawling +// watchman: true, + +================ +File: LICENSE.md +================ +Copyright 2022 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: postBuild.sh +================ +#!/bin/bash +# +# Add package.json files to cjs/mjs subtrees +# + +cat >dist/cjs/package.json <dist/mjs/package.json <[], - wsKey: TWSKey, -): +// Uncomment the line below to enable trace logging +// console.log(new Date(), 'trace', ...params); ⋮---- -/** Get the WsStore that tracks websockets & topics */ -public getWsStore(): WsStore> +// Info level logging: used for general informational messages ⋮---- -public close(wsKey: TWSKey, force?: boolean) +// Error level logging: used for error messages ⋮---- -public closeAll(force?: boolean) +async function start() ⋮---- -public isConnected(wsKey: TWSKey): boolean +// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach +// client.on('update', (data) => { +// // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); +// console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); +// }); ⋮---- -/** - * Request connection to a specific websocket, instead of waiting for automatic connection. - */ -protected async connect( - wsKey: TWSKey, -): Promise +// Something happened, attempting to reconnect ⋮---- -private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket +// Reconnect successful ⋮---- -private parseWsError(context: string, error: any, wsKey: TWSKey) +// Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- -/** Get a signature, build the auth request and send it */ -private async sendAuthRequest(wsKey: TWSKey): Promise +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach +// client.on('response', (data) => { +// console.info( +// new Date(), +// 'ws server reply ', +// JSON.stringify(data, null, 2), +// '\n', +// ); +// }); ⋮---- -// console.log('ws auth req', request); +// Optional, listen to this event if you prefer the event-driven approach. +// See below comments on event-driven vs promise-driven. +// client.on('authenticated', (data) => { +// console.error(new Date(), 'ws authenticated: ', data); +// }); ⋮---- -private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) +/** + * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. + * + * You have two ways to handle responses on the WS API. You can either: + * - event-driven: process async `response` and `update` events from the websocket client, OR + * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). + */ ⋮---- -private ping(wsKey: TWSKey) +/** + * To authenticate, send an empty request to "futures.login". The SDK will handle all the parameters. + * + * Optional - you can inject rich types to set the response type + * const loginResult = await client.sendWSAPIRequest>('perpFuturesUSDTV4', 'futures.login'); + */ ⋮---- -private clearTimers(wsKey: TWSKey) +/** + * For other channels, the 3rd parameter should have any parameters for the request (the payload). + * + * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. + * + */ ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: TWSKey) -⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: TWSKey) -⋮---- -// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +/** + * Submit futures order + */ ⋮---- -// this.logger.trace(`No active pong timer for "${wsKey}"`); +size: 20, // positive for long, negative for short ⋮---- /** - * Simply builds and sends subscribe events for a list of topics for a ws key - * - * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. - */ -private async requestSubscribeTopics( - wsKey: TWSKey, - topics: WsTopicRequest[], -) + * Submit batch futures order + */ ⋮---- -// Automatically splits requests into smaller batches, if needed +size: 10, // positive for long, negative for short ⋮---- -`Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +size: 10, // positive for long, negative for short ⋮---- -// console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); +/** + * Cancel futures order + */ ⋮---- -// this.logger.trace(`Sending batch via message: "${wsMessage}"`); +/** + * Cancel all futures orders + */ ⋮---- /** - * Simply builds and sends unsubscribe events for a list of topics for a ws key - * - * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. - */ -private async requestUnsubscribeTopics( - wsKey: TWSKey, - wsTopicRequests: WsTopicRequest[], -) + * Update/Amend Futures order + */ ⋮---- /** - * Try sending a string event on a WS connection (identified by the WS Key) - */ -public tryWsSend( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -) + * Get orders list + */ ⋮---- -private async onWsOpen( - event: any, - wsKey: TWSKey, - url: string, - ws: WebSocket, -) +/** + * Get order status + */ + +================ +File: examples/ws-private-perp-futures.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; +// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- -// Resolve & cleanup deferred "connection attempt in progress" promise +// Define a custom logger object to handle logging at different levels ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +// Trace level logging: used for detailed debugging information ⋮---- -// Remove before resolving, in case there's more requests queued +// Uncomment the line below to enable trace logging +// console.log(new Date(), 'trace', ...params); ⋮---- -// Some websockets require an auth packet to be sent after opening the connection +// Info level logging: used for general informational messages ⋮---- -// Reconnect to topics known before it connected +// Error level logging: used for error messages ⋮---- -// Request sub to public topics, if any +async function start() ⋮---- -// Request sub to private topics, if auth on connect isn't needed +// console.log('auth with: ', account); ⋮---- -// If enabled, automatically reauth WS API if reconnected +// Data received ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +// Something happened, attempting to reconnect +⋮---- +// Reconnect successful +⋮---- +// Connection closed. If unexpected, expect reconnect -> reconnected. +⋮---- +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +⋮---- +// TODO: many private topics use your user ID ⋮---- /** - * Handle subscription to private topics _after_ authentication successfully completes asynchronously. - * - * Only used for exchanges that require auth before sending private topic subscription requests - */ -private onWsAuthenticated( - wsKey: TWSKey, - event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, -) + * Either send one topic (with params) at a time + */ +// client.subscribe({ +// topic: 'futures.usertrades', +// payload: [myUserID, '!all'], +// }, 'perpFuturesUSDTV4'); ⋮---- -// Resolve & cleanup deferred "auth attempt in progress" promise +/** + * Or send multiple topics in a batch (grouped by ws connection (WsKey)) + * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: + */ + +================ +File: examples/ws-private-spot.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { LogParams, WebsocketClient, WsTopicRequest } from '../src/index.js'; +// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- -// Remove before continuing, in case there's more requests queued +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) +// Define a custom logger object to handle logging at different levels ⋮---- -// any message can clear the pong timer - wouldn't get a message if the ws wasn't working +// Trace level logging: used for detailed debugging information ⋮---- -// console.log(`raw event: `, { data, dataType, emittableEvents }); +// Uncomment the line below to enable trace logging +// console.log(new Date(), 'trace', ...params); ⋮---- -private onWsClose(event: unknown, wsKey: TWSKey) +// Info level logging: used for general informational messages ⋮---- -// unintentional close, attempt recovery +// Error level logging: used for error messages ⋮---- -// clean up any pending promises for this connection +async function start() ⋮---- -// intentional close - clean up -// clean up any pending promises for this connection +// console.log('auth with: ', account); ⋮---- -// clean up any pending promises for this connection +// Data received ⋮---- -// This was an intentional close, delete all state for this connection, as if it never existed: +// Something happened, attempting to reconnect ⋮---- -private getWs(wsKey: TWSKey) +// Reconnect successful ⋮---- -private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +// Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- -/** - * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) - */ -protected async assertIsConnected(wsKey: TWSKey): Promise +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" ⋮---- -// Already in progress? Await shared promise and retry +// client.subscribe(topics, 'spotV4'); ⋮---- -// Start connection, it should automatically store/return a promise. +// This has the same effect as above, it's just a different way of messaging which topic this is for +// const topicWithoutParamsAsObject: WsTopicRequest = { +// topic: 'spot.balances', +// }; ⋮---- /** - * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) - */ -public async assertIsAuthenticated(wsKey: TWSKey): Promise -⋮---- -// Already in progress? Await shared promise and retry + * Either send one topic (with optional params) at a time + */ +// client.subscribe(topicWithoutParamsAsObject, 'spotV4'); ⋮---- -// this.logger.trace('assertIsAuthenticated(): ok'); +/** + * Or send multiple topics in a batch (grouped by ws connection (WsKey)) + * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: + */ ⋮---- -// Start authentication, it should automatically store/return a promise. +/** + * You can also subscribe in separate function calls as you wish. + * + * Any duplicate requests should get filtered out (e.g. here we subscribed to "spot.balances" twice, but the WS client will filter this out) + */ ================ -File: src/lib/logger.ts +File: examples/ws-public.ts ================ -export type LogParams = null | any; -⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars +import { WebsocketClient, WsTopicRequest } from '../src/index.js'; +// import { LogParams, WebsocketClient, WsTopicRequest } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- -// console.log(_params); +// const customLogger = { +// // eslint-disable-next-line @typescript-eslint/no-unused-vars +// trace: (...params: LogParams): void => { +// console.log('trace', ...params); +// }, +// info: (...params: LogParams): void => { +// console.log('info', ...params); +// }, +// error: (...params: LogParams): void => { +// console.error('error', ...params); +// }, +// }; ⋮---- -export type DefaultLogger = typeof DefaultLogger; - -================ -File: src/lib/misc-util.ts -================ -export function neverGuard(x: never, msg: string): Error +async function start() +⋮---- +// Optional, inject a custom logger +// const client = new WebsocketClient({}, customLogger); +⋮---- +// Data received +⋮---- +// Something happened, attempting to reconnect +⋮---- +// Reconnect successful +⋮---- +// Connection closed. If unexpected, expect reconnect -> reconnected. +⋮---- +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +⋮---- +// const topicWithoutParamsAsString = 'spot.balances'; +⋮---- +// This has the same effect as above, it's just a different way of messaging which topic this is for +// const topicWithoutParamsAsObject: WsTopicRequest = { +// topic: 'spot.balances', +// }; +⋮---- +/** + * Either send one topic (with optional params) at a time + */ +// client.subscribe(tickersRequestWithParams, 'spotV4'); +⋮---- +/** + * Or send multiple topics in a batch (grouped by ws connection (WsKey)) + */ +⋮---- +// /** +// * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: +// */ +// client.subscribe( +// [tickersRequestWithParams, rawTradesRequestWithParams, topicWithoutParamsAsString], +// 'spotV4', +// ); ================ -File: src/lib/requestUtils.ts +File: src/lib/websocket/websocket-util.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- -import { GateBaseUrlKey } from '../types/shared.js'; +import { WSAPIRequest } from '../../types/websockets/requests.js'; +import { + FuturesWSAPITopic, + SpotWSAPITopic, +} from '../../types/websockets/wsAPI.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 */ +/** + * Should be one WS key per unique URL. Some URLs may need a suffix. + */ ⋮---- /** - * 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 + * Spot & Margin + * https://www.gate.io/docs/developers/apiv4/ws/en/ */ ⋮---- -/** 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' - **/ + * Perpetual futures (USDT) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ ⋮---- -// manually override with one of the known base URLs in the library +/** + * Perpetual futures (BTC) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ ⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ +/** + * Delivery Futures (USDT) + * https://www.gate.io/docs/developers/delivery/ws/en/ + */ ⋮---- /** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 + * Delivery Futures (BTC) + * https://www.gate.io/docs/developers/delivery/ws/en/ */ ⋮---- /** - * 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) + * Options + * https://www.gate.io/docs/developers/options/ws/en/ */ ⋮---- /** - * 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. + * Announcements V4 + * https://www.gate.io/docs/developers/options/ws/en/ */ ⋮---- -export function serializeParams | undefined = {}>( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, -): string +/** This is used to differentiate between each of the available websocket streams */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- -// Only prefix if there's a value +export type FuturesWsKey = + | typeof WS_KEY_MAP.perpFuturesUSDTV4 + | typeof WS_KEY_MAP.perpFuturesBTCV4 + | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 + | typeof WS_KEY_MAP.deliveryFuturesBTCV4; ⋮---- -export function getRestBaseUrl(restClientOptions: RestClientOptions): string +export type WsMarket = 'all'; ⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; +/** + * 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; } ⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike - -================ -File: src/lib/webCryptoAPI.ts -================ -import { neverGuard } from './misc-util.js'; +/** + * 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; ⋮---- -function bufferToB64(buffer: ArrayBuffer): 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 type SignEncodeMethod = 'hex' | 'base64'; -export type SignAlgorithm = 'SHA-256' | 'SHA-512'; +export function neverGuard(x: never, msg: string): Error ⋮---- /** - * Similar to node crypto's `createHash()` function + * WS API promises are stored using a primary key. This key is constructed using + * properties found in every request & reply. */ -export async function hashMessage( - message: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, -): Promise +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[] ⋮---- /** - * Sign a message, with a secret, using the Web Crypto API + * 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 async function signMessage( - message: string, - secret: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, -): Promise -⋮---- -export function checkWebCryptoAPISupported() +export function safeTerminateWs( + ws?: WebSocket | any, + fallbackToClose?: boolean, +): boolean ================ -File: src/types/request/account.ts +File: src/lib/websocket/WsStore.ts ================ -/**========================================================================================================================== - * ACCOUNT - * ========================================================================================================================== - */ +import WebSocket from 'isomorphic-ws'; ⋮---- -export interface CreateStpGroupReq { - name: string; - id?: number; - creator_id?: number; - create_time?: number; -} - -================ -File: src/types/request/collateralLoan.ts -================ -/**========================================================================================================================== - * COLLATERAL LOAN - * ========================================================================================================================== +import { DefaultLogger } from '../logger.js'; +import { + DeferredPromise, + WSConnectedResult, + WsConnectionStateEnum, + WsStoredState, +} from './WsStore.types.js'; +⋮---- +/** + * Simple comparison of two objects, only checks 1-level deep (nested objects won't match) */ +export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean ⋮---- -export interface SubmitLoanOrderReq { - collateral_amount: string; - collateral_currency: string; - borrow_amount: string; - borrow_currency: string; -} +type DeferredPromiseRef = + (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF]; ⋮---- -export interface GetLoanOrdersReq { - page?: number; - limit?: number; - collateral_currency?: string; - borrow_currency?: string; -} +export class WsStore< +WsKey extends string, ⋮---- -export interface GetLoanRepaymentHistoryReq { - source: 'repay' | 'liquidate'; - borrow_currency?: string; - collateral_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} +constructor(logger: DefaultLogger) ⋮---- -export interface UpdateLoanCollateralReq { - order_id: number; - collateral_currency: string; - collateral_amount: string; - type: 'append' | 'redeem'; -} +/** Get WS stored state for key, optionally create if missing */ +get( + key: WsKey, + createIfMissing?: true, + ): WsStoredState; ⋮---- -export interface GetLoanCollateralRecordsReq { - page?: number; - limit?: number; - from?: number; - to?: number; - borrow_currency?: string; - collateral_currency?: string; -} - -================ -File: src/types/request/delivery.ts -================ -/**========================================================================================================================== - * DELIVERY - * ========================================================================================================================== - */ +get( + key: WsKey, + createIfMissing?: false, + ): WsStoredState | undefined; ⋮---- -export interface GetDeliveryOrderBookReq { - settle: 'usdt'; - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; -} +get( + key: WsKey, + createIfMissing?: boolean, +): WsStoredState | undefined ⋮---- -export interface GetDeliveryTradesReq { - settle: 'usdt'; - contract: string; - limit?: number; - last_id?: string; - from?: number; - to?: number; -} +getKeys(): WsKey[] ⋮---- -export interface GetDeliveryCandlesReq { - settle: 'usdt'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: - | '10s' - | '30s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '7d' - | '1w' - | '30d'; -} +create(key: WsKey): WsStoredState | undefined ⋮---- -export interface GetDeliveryBookReq { - settle: 'usdt'; - limit?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; -} +delete(key: WsKey): void ⋮---- -export interface SubmitDeliveryFuturesOrderReq { - settle: 'usdt'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; -} +// TODO: should we allow this at all? Perhaps block this from happening... ⋮---- -export interface GetDeliveryOrdersReq { - settle: 'usdt'; - contract?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; -} +/* connection websocket */ ⋮---- -export interface GetDeliveryTradingHistoryReq { - settle: 'usdt'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; -} +hasExistingActiveConnection(key: WsKey): boolean ⋮---- -export interface GetDeliveryClosedPositionsReq { - settle: 'usdt'; - contract?: string; - limit?: number; -} +getWs(key: WsKey): WebSocket | undefined ⋮---- -export interface GetDeliveryLiquidationHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} +setWs(key: WsKey, wsConnection: WebSocket): WebSocket ⋮---- -export interface GetDeliverySettlementHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} -export interface GetDeliveryAutoOrdersReq { - settle: 'usdt'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} - -================ -File: src/types/request/earn.ts -================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ +/** + * deferred promises + */ ⋮---- -export interface GetStructuredProductListReq { - status: string; - type?: string; - page?: number; - limit?: number; -} +getDeferredPromise( + wsKey: WsKey, + promiseRef: string | DeferredPromiseRef, +): DeferredPromise | undefined ⋮---- -export interface GetStructuredProductOrdersReq { - from?: number; - to?: number; - page?: number; - limit?: number; -} - -================ -File: src/types/request/earnuni.ts -================ -/**========================================================================================================================== - * EARN UNI - * ========================================================================================================================== - */ +createDeferredPromise( + wsKey: WsKey, + promiseRef: string | DeferredPromiseRef, + throwIfExists: boolean, +): DeferredPromise ⋮---- -export interface SubmitLendOrRedeemReq { - currency: string; - amount: string; - type: 'lend' | 'redeem'; - min_rate?: string; -} +// console.log('existing promise'); ⋮---- -export interface GetLendingOrdersReq { - currency?: string; - page?: number; - limit?: number; -} +// console.log('create promise'); ⋮---- -export interface GetLendingRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'lend' | 'redeem'; -} +// TODO: Once stable, use Promise.withResolvers in future ⋮---- -export interface GetLendingInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -================ -File: src/types/request/flashswap.ts -================ -/**========================================================================================================================== - * FLASH SWAP - * ========================================================================================================================== - */ +resolveDeferredPromise( + wsKey: WsKey, + promiseRef: string | DeferredPromiseRef, + value: unknown, + removeAfter: boolean, +): void ⋮---- -export interface SubmitFlashSwapOrderReq { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; -} +rejectDeferredPromise( + wsKey: WsKey, + promiseRef: string | DeferredPromiseRef, + value: unknown, + removeAfter: boolean, +): void ⋮---- -export interface GetFlashSwapOrdersReq { - status?: number; - sell_currency?: string; - buy_currency?: string; - reverse?: boolean; - limit?: number; - page?: number; -} +removeDeferredPromise( + wsKey: WsKey, + promiseRef: string | DeferredPromiseRef, +): void ⋮---- -export interface GetFlashSwapOrderReq { - order_id: number; -} +// Just in case it's pending ⋮---- -export interface SubmitFlashSwapOrderPreviewReq { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; -} - -================ -File: src/types/request/futures.ts -================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ +rejectAllDeferredPromises(wsKey: WsKey, reason: string): void ⋮---- -export interface GetFuturesOrderBookReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; -} +// Skip reserved keys, such as the connection promise ⋮---- -export interface GetFuturesTradesReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; -} +/** Get promise designed to track a connection attempt in progress. Resolves once connected. */ +getConnectionInProgressPromise( + wsKey: WsKey, +): DeferredPromise | undefined ⋮---- -export interface GetFuturesCandlesReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; -} +getAuthenticationInProgressPromise( + wsKey: WsKey, +): DeferredPromise ⋮---- -export interface GetFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - from?: number; - to?: number; -} +createAuthenticationInProgressPromise( + wsKey: WsKey, + throwIfExists: boolean, +): DeferredPromise ⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} +getTopicsByKey(): Record> ⋮---- -export interface UpdateFuturesOrderReq { - xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd'; - order_id: string; - size?: number; - price?: string; - amend_text?: string; -} +/** + * Find matching "topic" request from the store + * @param key + * @param topic + * @returns + */ +getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- -export interface GetFuturesTradingHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; -} +addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- -export interface GetFuturesTradingHistoryByTimeRangeReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - role?: 'maker' | 'taker'; +// Check for duplicate topic. If already tracked, don't store this one +⋮---- +deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) +⋮---- +// Check if we're subscribed to a topic like this + +================ +File: src/lib/websocket/WsStore.types.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import WebSocket from 'isomorphic-ws'; +⋮---- +export enum WsConnectionStateEnum { + INITIAL = 0, + CONNECTING = 1, + CONNECTED = 2, + CLOSING = 3, + RECONNECTING = 4, + // ERROR_RECONNECTING = 5, + ERROR = 5, } ⋮---- -export interface GetFuturesPositionHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; +// ERROR_RECONNECTING = 5, +⋮---- +export interface DeferredPromise { + resolve?: (value: TSuccess) => TSuccess; + reject?: (value: TError) => TError; + promise?: Promise; } ⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - at?: number; +export interface WSConnectedResult { + wsKey: string; + ws: WebSocket; } ⋮---- -export interface SubmitFuturesTriggeredOrderReq { - initial: { - contract: string; - size?: number; - price: string; // Required: Order price. Set to 0 to use market price - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price: string; // Required: Price value for price trigger - rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) - expiration?: number; - }; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - settle: 'btc' | 'usdt' | 'usd'; +export interface WsStoredState { + /** The currently active websocket connection */ + ws?: WebSocket; + /** The current lifecycle state of the connection (enum) */ + connectionState?: WsConnectionStateEnum; + connectionStateChangedAt?: Date; + /** A timer that will send an upstream heartbeat (ping) when it expires */ + activePingTimer?: ReturnType | undefined; + /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ + activePongTimer?: ReturnType | undefined; + /** If a reconnection is in progress, this will have the timer for the delayed reconnect */ + activeReconnectTimer?: ReturnType | undefined; + /** + * When a connection attempt is in progress (even for reconnect), a promise is stored here. + * + * This promise will resolve once connected (and will then get removed); + */ + // connectionInProgressPromise?: DeferredPromise | undefined; + deferredPromiseStore: Record; + /** + * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) + * + * A "Set" and a deep-object-match are used to ensure we only subscribe to a + * topic once (tracking a list of unique topics we're expected to be connected to) + */ + subscribedTopics: Set; + /** Whether this connection has completed authentication (only applies to private connections) */ + isAuthenticated?: boolean; + /** + * Whether this connection has completed authentication before for the Websocket API, so it k + * nows to automatically reauth if reconnected + */ + didAuthWSAPI?: boolean; + /** To reauthenticate on the WS API, which channel do we send to? */ + WSAPIAuthChannel?: string; } ⋮---- -price: string; // Required: Order price. Set to 0 to use market price +/** The currently active websocket connection */ ⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +/** The current lifecycle state of the connection (enum) */ ⋮---- -export interface GetFuturesAutoOrdersReq { - settle: 'btc' | 'usdt' | 'usd'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} +/** A timer that will send an upstream heartbeat (ping) when it expires */ ⋮---- -/** - * 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 -} +/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */ ⋮---- -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 +/** If a reconnection is in progress, this will have the timer for the delayed reconnect */ ⋮---- -// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request -export interface GetFuturesPositionCloseHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} +/** + * When a connection attempt is in progress (even for reconnect), a promise is stored here. + * + * This promise will resolve once connected (and will then get removed); + */ +// connectionInProgressPromise?: DeferredPromise | undefined; ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: 'btc' | 'usdt' | 'usd'; - limit?: number; -} +/** + * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops) + * + * A "Set" and a deep-object-match are used to ensure we only subscribe to a + * topic once (tracking a list of unique topics we're expected to be connected to) + */ ⋮---- -export interface UpdateFuturesPriceTriggeredOrderReq { - settle: 'btc' | 'usdt' | 'usd'; - order_id: string; - contract?: string; - size?: number; - price?: string; - trigger_price?: string; - price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price - auto_size?: string; // Not required in single position mode -} +/** Whether this connection has completed authentication (only applies to private connections) */ ⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode +/** + * Whether this connection has completed authentication before for the Websocket API, so it k + * nows to automatically reauth if reconnected + */ +⋮---- +/** To reauthenticate on the WS API, which channel do we send to? */ ================ -File: src/types/request/margin.ts +File: src/lib/requestUtils.ts ================ -/**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ -⋮---- -export interface GetMarginBalanceHistoryReq { - currency?: string; - currency_pair?: string; - type?: string; - from?: number; - to?: number; - page?: number; - limit?: number; -} +import WebSocket from 'isomorphic-ws'; ⋮---- -export interface GetCrossMarginAccountHistoryReq { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; -} +import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- -export interface SubmitCrossMarginBorrowLoanReq { - currency: string; - amount: string; - text?: string; +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; } ⋮---- -export interface GetCrossMarginBorrowHistoryReq { - status: number; - currency?: string; - limit?: number; - offset?: number; - reverse?: boolean; -} +/** Your API key */ ⋮---- -export interface GetCrossMarginRepaymentsReq { - currency?: string; - loan_id?: string; - limit?: number; - offset?: number; - reverse?: boolean; -} +/** Your API secret */ ⋮---- -export interface GetCrossMarginInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -================ -File: src/types/request/marginuni.ts -================ -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ +/** + * 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 + */ ⋮---- -export interface GetMarginUNILoansReq { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; -} +/** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- -export interface GetMarginUNILoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - currency_pair?: string; - page?: number; - limit?: number; -} +/** + * Optionally override API protocol + domain + * e.g baseUrl: 'https://api.gate.io' + **/ ⋮---- -export interface GetMarginUNIInterestRecordsReq { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} +// manually override with one of the known base URLs in the library ⋮---- -export interface GetMarginUNIMaxBorrowReq { - currency: string; - currency_pair: string; +/** 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/types/request/multicollateralLoan.ts +File: src/lib/webCryptoAPI.ts ================ -/**========================================================================================================================== - * MULTI COLLATERAL LOAN - * ========================================================================================================================== - */ +import { neverGuard } from './misc-util.js'; ⋮---- -export interface SubmitMultiLoanOrderReq { - order_id?: string; - order_type?: string; - fixed_type?: string; - fixed_rate?: string; - auto_renew?: boolean; - auto_repay?: boolean; - borrow_currency: string; - borrow_amount: string; - collateral_currencies?: { - currency?: string; - amount?: string; - }[]; -} -export interface GetMultiLoanOrdersReq { - page?: number; - limit?: number; - sort?: string; - order_type?: string; -} +function bufferToB64(buffer: ArrayBuffer): string ⋮---- -export interface RepayMultiLoanReq { - order_id: number; - repay_items: { - currency?: string; - amount?: string; - repaid_all?: boolean; - }[]; -} +export type SignEncodeMethod = 'hex' | 'base64'; +export type SignAlgorithm = 'SHA-256' | 'SHA-512'; ⋮---- -export interface GetMultiLoanRepayRecordsReq { - type: 'repay' | 'liquidate'; - borrow_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} +/** + * Similar to node crypto's `createHash()` function + */ +export async function hashMessage( + message: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, +): Promise ⋮---- -export interface UpdateMultiLoanReq { - order_id: number; - type: 'append' | 'redeem'; - collaterals?: { - currency?: string; - amount?: string; - }[]; -} +/** + * Sign a message, with a secret, using the Web Crypto API + */ +export async function signMessage( + message: string, + secret: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, +): Promise ⋮---- -export interface GetMultiLoanAdjustmentRecordsReq { - page?: number; - limit?: number; - from?: number; - to?: number; - collateral_currency?: string; -} +export function checkWebCryptoAPISupported() ================ -File: src/types/request/options.ts +File: src/types/request/spot.ts ================ /**========================================================================================================================== - * OPTIONS + * SPOT * ========================================================================================================================== */ -export interface GetOptionsSettlementHistoryReq { - underlying: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} -export interface GetOptionsMySettlementsReq { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} ⋮---- -export interface GetOptionsOrderBookReq { - contract: string; - interval?: '0' | '0.1' | '0.01'; +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; limit?: number; with_id?: boolean; } ⋮---- -export interface GetOptionsCandlesReq { - contract: string; +export interface GetSpotTradesReq { + currency_pair: string; limit?: number; + last_id?: string; + reverse?: boolean; from?: number; to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; + page?: number; } ⋮---- -export interface GetOptionsUnderlyingCandlesReq { - underlying: string; +export interface GetSpotCandlesReq { + currency_pair: string; limit?: number; from?: number; to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; + interval?: + | '1s' + | '10s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '4h' + | '8h' + | '1d' + | '7d' + | '30d'; } ⋮---- -export interface GetOptionsTradesReq { - contract?: string; - type?: 'C' | 'P'; - limit?: number; - offset?: number; +export interface GetSpotAccountBookReq { + currency?: string; from?: number; to?: number; -} -⋮---- -export interface GetOptionsAccountChangeReq { + page?: number; limit?: number; - offset?: number; - from?: number; - to?: number; - type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + type?: string; + code?: string; } ⋮---- -export interface SubmitOptionsOrderReq { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; +export interface SubmitSpotClosePosCrossDisabledReq { text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface GetOptionsOrdersReq { - contract?: string; - underlying?: string; +export interface GetSpotOrdersReq { + currency_pair: string; status: 'open' | 'finished'; + page?: number; limit?: number; - offset?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; + side?: 'buy' | 'sell'; } ⋮---- -export interface GetOptionsPersonalHistoryReq { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; +export interface CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface OptionsMMPSettingsReq { - underlying: string; - window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP - frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called - qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) - delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) -} -⋮---- -window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP -frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called -qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) -delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) - -================ -File: src/types/request/rebate.ts -================ -export interface GetAgencyTransactionHistoryReq { - currency_pair?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetAgencyCommissionHistoryReq { - currency?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetPartnerSubordinateListReq { - user_id?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetBrokerCommissionHistoryReq { - limit?: number; - offset?: number; - user_id?: number; - from?: number; - to?: number; -} -⋮---- -export interface GetBrokerTransactionHistoryReq { - limit?: number; - offset?: number; - user_id?: number; - from?: number; - to?: number; -} -⋮---- -// Interfaces for request and response -export interface PartnerTransactionReq { - currency_pair?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; -} - -================ -File: src/types/request/spot.ts -================ -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ -⋮---- -export interface GetSpotOrderBookReq { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; -} -⋮---- -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; -} -⋮---- -export interface GetSpotCandlesReq { - currency_pair: string; - limit?: number; - from?: number; - to?: number; - interval?: - | '1s' - | '10s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '4h' - | '8h' - | '1d' - | '7d' - | '30d'; -} -⋮---- -export interface GetSpotAccountBookReq { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; - code?: string; -} -⋮---- -export interface SubmitSpotClosePosCrossDisabledReq { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} -⋮---- -export interface GetSpotOrdersReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; - side?: 'buy' | 'sell'; -} -⋮---- -export interface CancelSpotBatchOrdersReq { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} -⋮---- -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - xGateExptime?: number; +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: number; } ⋮---- export interface GetSpotOrderReq { @@ -3341,48 +4552,6 @@ export interface UpdateSpotOrderReq { action_mode?: 'ACK' | 'RESULT' | 'FULL'; } -================ -File: src/types/request/subaccount.ts -================ -export interface CreateSubAccountReq { - login_name: string; - remark?: string; - password?: string; - email?: string; -} -⋮---- -export interface CreateSubAccountApiKeyReq { - user_id: number; - mode?: number; // Mode: 1 - classic, 2 - portfolio account - name?: string; // API key name - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; // Permission name - read_only?: boolean; // Read only - }[]; - ip_whitelist?: string[]; // IP white list -} -⋮---- -mode?: number; // Mode: 1 - classic, 2 - portfolio account -name?: string; // API key name -⋮---- -| 'loan'; // Permission name -read_only?: boolean; // Read only -⋮---- -ip_whitelist?: string[]; // IP white list -⋮---- -export type UpdateSubAccountApiKeyReq = { - key: string; -} & CreateSubAccountApiKeyReq; - ================ File: src/types/request/unified.ts ================ @@ -3548,23 +4717,6 @@ export interface SubmitMainSubTransferReq { sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } -================ -File: src/types/request/withdrawal.ts -================ -/**================================================================================================================================ - * WITHDRAW - * ========================================================================================================================== - */ -⋮---- -export interface SubmitWithdrawalReq { - amount: string; - currency: string; - chain: string; - withdraw_order_id?: string; - address?: string; - memo?: string; -} - ================ File: src/types/response/account.ts ================ @@ -3626,80 +4778,263 @@ state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified ================ -File: src/types/response/collateralloan.ts +File: src/types/response/margin.ts ================ /**========================================================================================================================== - * COLLATERAL LOAN + * MARGIN * ========================================================================================================================== */ ⋮---- -export interface LoanOrder { - order_id: number; - collateral_currency: string; - collateral_amount: string; - borrow_currency: string; - borrow_amount: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - init_ltv: string; - current_ltv: string; - liquidate_ltv: string; - status: string; - borrow_time: number; - left_repay_total: string; - left_repay_principal: string; - left_repay_interest: string; -} -⋮---- -export interface LoanRepaymentHistoryRecord { - order_id: number; - record_id: number; - repaid_amount: string; - borrow_currency: string; - collateral_currency: string; - init_ltv: string; - borrow_time: number; - repay_time: number; - total_interest: string; - before_left_principal: string; - after_left_principal: string; - before_left_collateral: string; - after_left_collateral: string; +export interface 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 LoanCollateralRecord { - order_id: number; - record_id: number; - borrow_currency: string; - borrow_amount: string; - collateral_currency: string; - before_collateral: string; - after_collateral: string; - before_ltv: string; - after_ltv: string; - operate_time: number; +export interface MarginBalanceHistoryRecord { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; } ⋮---- -export interface LoanCollateralRatio { - collateral_currency: string; - borrow_currency: string; - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; +export interface CrossMarginCurrency { + name: string; + rate: string; + prec: string; + discount: string; min_borrow_amount: string; - left_borrowable_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/delivery.ts +File: src/types/response/marginuni.ts ================ /**========================================================================================================================== - * DELIVERY + * MARGIN UNI * ========================================================================================================================== */ ⋮---- -export interface DeliveryOrderBook { +export interface LendingMarket { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; +} +⋮---- +export interface MarginUNILoan { + currency: string; + currency_pair: string; + amount: string; + type: string; // 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/options.ts +================ +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ +⋮---- +export interface OptionsContract { + name: string; + tag: string; // Expiry period: day, week, month + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id?: number; // Deprecated + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date + multiplier: string; // Option contract multiplier + order_price_round: string; + mark_price_round: string; // Minimum unit of mark price + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate?: string; // Deprecated + order_size_min: number; + order_size_max: number; + orders_limit: number; // Maximum number of orders per user in this market +} +⋮---- +tag: string; // Expiry period: day, week, month +⋮---- +trade_id?: number; // Deprecated +⋮---- +underlying_price: string; // Forward futures price for the delivery date +multiplier: string; // Option contract multiplier +⋮---- +mark_price_round: string; // Minimum unit of mark price +⋮---- +order_price_deviate?: string; // Deprecated +⋮---- +orders_limit: number; // Maximum number of orders per user in this market +⋮---- +export interface OptionsSettlementHistoryRecord { + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; +} +⋮---- +export interface OptionsUserSettlement { + time: number; + underlying: string; + contract: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; +} +⋮---- +export interface OptionsOrderBook { id?: number; current: number; update: number; @@ -3707,17 +5042,30 @@ export interface DeliveryOrderBook { bids: { p: string; s: number }[]; } ⋮---- -export interface DeliveryTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; +export interface OptionsTicker { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; // Leverage calculation formula updated with reference note + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; } ⋮---- -export interface DeliveryCandle { +leverage: string; // Leverage calculation formula updated with reference note +⋮---- +export interface OptionsCandle { t: number; v?: number; c: string; @@ -3726,438 +5074,818 @@ export interface DeliveryCandle { o: string; } ⋮---- -export interface DeliveryTicker { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; +export interface OptionsUnderlyingCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; } ⋮---- -export interface DeliveryAccount { - total: string; - unrealised_pnl: string; - position_margin: 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; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic: boolean; - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - isolated_position_margin: string; - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - enable_tiered_mm: boolean; + 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 DeliveryBook { +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' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; text: string; - contract?: string; - trade_id?: string; } ⋮---- -export interface DeliveryTradingHistoryRecord { - id: number; - create_time: number; +export interface OptionsPositionsUnderlying { + user: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date contract: string; - order_id: string; size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; } ⋮---- -export interface DeliveryClosedPosition { +underlying_price: string; // Forward futures price for the delivery date +⋮---- +export interface GetOptionsLiquidationResp { 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; + settle_size: string; } ⋮---- -export interface DeliveryLiquidationHistoryRecord { - time: number; +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; - leverage?: string; size: number; - margin?: string; - entry_price?: string; - liq_price?: string; - mark_price?: string; - order_id?: number; - order_price: string; - fill_price: string; + 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 DeliverySettlementHistoryRecord { - time: number; +export interface OptionsUserHistoryRecord { + id: number; + create_time: number; contract: string; - leverage: string; + order_id: number; size: number; - margin: string; - entry_price: string; - settle_price: string; - profit: string; - fee: string; + 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/earn.ts +File: src/types/response/rebate.ts ================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ +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 DualInvestmentProduct { - id: number; - instrument_name: string; - invest_currency: string; - exercise_currency: string; - exercise_price: number; - delivery_time: number; - min_copies: number; - max_copies: number; - per_value: string; - apy_display: string; - start_time: number; - end_time: number; - status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; +export interface AgencyCommissionHistoryRecord { + commission_time: number; + user_id: number; + group_name: string; + commission_amount: string; + commission_asset: string; + source: 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; +export interface PartnerSubordinate { + user_id: number; + user_join_time: number; + type: number; + desc: string; } ⋮---- -export interface StructuredProduct { - id: number; - type: string; - name_en: string; - investment_coin: string; - investment_period: string; - min_annual_rate: string; - mid_annual_rate: string; - max_annual_rate: string; - watch_market: string; - start_time: number; - end_time: number; - status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; +export interface BrokerCommissionHistoryRecord { + commission_time: number; + user_id: number; + group_name: string; + amount: string; + fee: string; + fee_asset: string; + rebate_fee: string; + source: string; + currency_pair: string; + sub_broker_info: { + user_id: number; + original_commission_rate: string; + relative_commission_rate: string; + commission_rate: string; + }; } ⋮---- -export interface StructuredProductOrder { - id: number; - pid: string; - lock_coin: string; +export interface BrokerTransactionHistoryRecord { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + currency_pair: string; amount: string; - status: 'SUCCESS' | 'FAILED' | 'DONE'; - income: string; - create_time: number; + fee_asset: string; + source: string; + sub_broker_info: { + user_id: number; + original_commission_rate: string; + relative_commission_rate: string; + commission_rate: string; + }; +} +⋮---- +export interface PartnerCommission { + commission_time: number; + user_id: number; + group_name: string; + commission_amount: string; + commission_asset: string; + source: string; +} +⋮---- +export interface PartnerTransaction { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + fee_asset: string; + currency_pair: string; + amount: string; + amount_asset: string; + source: string; } ================ -File: src/types/response/earnuni.ts +File: src/types/response/wallet.ts ================ -/**========================================================================================================================== - * EARN UNI - * ========================================================================================================================== - */ +export interface CurrencyChain { + chain: string; + name_cn: string; + name_en: string; + contract_address: string; + is_disabled: number; + is_deposit_disabled: number; + is_withdraw_disabled: number; + decimal: string; +} ⋮---- -export interface LendingCurrency { +export interface DepositRecord { + id: string; + txid: string; + timestamp: string; + amount: string; currency: string; - min_lend_amount: string; - max_lend_amount: string; - max_rate: string; - min_rate: 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; } ⋮---- -export interface LendingOrder { +| 'BLOCKED' // Deposit Blocked +| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock +| 'DONE' // Funds Credited to Spot Account +| 'INVALID' // Invalid Transaction +| 'MANUAL' // Manual Review Required +| 'PEND' // Processing +| 'REVIEW' // Under Compliance Review +| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit +⋮---- +export interface CreateDepositAddressResp { currency: string; - current_amount: string; - amount: string; - lent_amount: string; - frozen_amount: string; - min_rate: string; - interest_status: string; - reinvest_left_amount: string; - create_time: number; - update_time: number; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; } ⋮---- -export interface LendingRecord { +export interface SubAccountTransferRecord { currency: string; + sub_account: string; + direction: 'to' | 'from'; amount: string; - last_wallet_amount: string; - last_lent_amount: string; - last_frozen_amount: string; - type: 'lend' | 'redeem'; - create_time: number; + uid: string; + client_order_id: string; + timest: string; + source: string; + sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- -export interface LendingInterestRecord { - status: number; +export interface WithdrawalStatus { currency: string; - actual_rate: string; - interest: string; - interest_status: string; - create_time: number; + 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 }; } - -================ -File: src/types/response/flashswap.ts -================ -/**========================================================================================================================== - * FLASH SWAP - * ========================================================================================================================== - */ ⋮---- -export interface FlashSwapCurrencyPair { +export interface SubAccountMarginBalance { currency_pair: string; - sell_currency: string; - buy_currency: string; - sell_min_amount: string; - sell_max_amount: string; - buy_min_amount: string; - buy_max_amount: string; -} -⋮---- -export interface FlashSwapOrder { - id: number; - create_time: number; - user_id: number; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - status: number; + 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 SubmitFlashSwapOrderPreviewResp { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; +export interface SubAccountFuturesBalancesResp { + uid: string; + available: { + [key: string]: { + total: string; + unrealised_pnl: string; + position_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic: boolean; + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + isolated_position_margin: string; + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + }; + }; } - -================ -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 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 FuturesTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; +export interface SavedAddress { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; } ⋮---- -export interface FuturesCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; +export interface TradingFees { + user_id: number; + taker_fee: string; + maker_fee: string; + gt_discount: boolean; + gt_taker_fee: string; + gt_maker_fee: string; + loan_fee: string; + point_type: string; + futures_taker_fee: string; + futures_maker_fee: string; + delivery_taker_fee: string; + delivery_maker_fee: string; + debit_fee: number; } ⋮---- -export interface PremiumIndexKLine { - t: number; - c: string; - h: string; - l: string; - o: 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; + }; + }; } ⋮---- -export interface FuturesTicker { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; - lowest_size: string; - highest_size: string; +export interface SmallBalanceRecord { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } ⋮---- -export interface FuturesStats { - time: number; - lsr_taker: number; - lsr_account: number; - long_liq_size: number; - long_liq_amount: number; - long_liq_usd: number; - short_liq_size: number; - short_liq_amount: number; - short_liq_usd: number; - open_interest: number; - open_interest_usd: number; - top_lsr_account: number; - top_lsr_size: number; +export interface SmallBalanceHistoryRecord { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; } ⋮---- -export interface IndexConstituents { - index: string; - constituents: { - exchange: string; - symbols: string[]; - }[]; +export interface PushOrder { + id: number; + push_uid: number; + receive_uid: number; + currency: string; + amount: string; + create_time: number; + status: + | 'CREATING' + | 'PENDING' + | 'CANCELLING' + | 'CANCELLED' + | 'REFUSING' + | 'REFUSED' + | 'RECEIVING' + | 'RECEIVED'; + message: string; } -⋮---- -export interface LiquidationHistoryRecord { - time: number; - contract: string; - size: number; - order_size: number; - order_price: string; - fill_price: string; - left: number; + +================ +File: src/types/response/withdrawal.ts +================ +export interface WithdrawalRecord { + id: string; + txid: string; + block_number: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'BCODE' // Deposit Code Operation + | 'CANCEL' // Cancelled + | 'CANCELPEND' // Withdrawal Cancellation Pending + | 'DMOVE' // Pending Manual Review + | 'DONE' // Completed (Only considered truly on-chain when block_number > 0) + | 'EXTPEND' // Sent and Waiting for Confirmation + | 'FAIL' // On-Chain Failure Pending Confirmation + | 'FVERIFY' // Facial Verification in Progress + | 'INVALID' // Invalid Transaction + | 'LOCKED' // Wallet-Side Order Locked + | 'MANUAL' // Pending Manual Review + | 'PEND' // Processing + | 'PROCES' // Processing + | 'REJECT' // Rejected + | 'REQUEST' // Request in Progress + | 'REVIEW' // Under Review + | 'SPLITPEND' // Split Pending + | 'VERIFY'; // Verification in Progress + chain: string; } ⋮---- -export interface RiskLimitTier { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; - leverage_max: string; - contract: string; +| 'BCODE' // Deposit Code Operation +| 'CANCEL' // Cancelled +| 'CANCELPEND' // Withdrawal Cancellation Pending +| 'DMOVE' // Pending Manual Review +| 'DONE' // Completed (Only considered truly on-chain when block_number > 0) +| 'EXTPEND' // Sent and Waiting for Confirmation +| 'FAIL' // On-Chain Failure Pending Confirmation +| 'FVERIFY' // Facial Verification in Progress +| 'INVALID' // Invalid Transaction +| 'LOCKED' // Wallet-Side Order Locked +| 'MANUAL' // Pending Manual Review +| 'PEND' // Processing +| 'PROCES' // Processing +| 'REJECT' // Rejected +| 'REQUEST' // Request in Progress +| 'REVIEW' // Under Review +| 'SPLITPEND' // Split Pending +| 'VERIFY'; // Verification in Progress + +================ +File: src/types/shared.ts +================ +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'futuresTestnet'; +⋮---- +// interfaces +⋮---- +export interface FromToPageLimit { + from: number; + to: number; + page: number; + limit: number; } ⋮---- -export interface FuturesAccount { - total: string; - unrealised_pnl: string; - position_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; +// Used for spot and flash swap +export interface CurrencyPair { + id?: string; + base?: string; + base_name?: string; + quote?: string; + quote_name?: string; + fee?: string; + min_base_amount?: string; + min_quote_amount?: string; + max_base_amount?: string; + max_quote_amount?: string; + amount_precision?: number; + precision?: number; + trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; + sell_start?: number; + buy_start?: number; + type: string; + delisting_time?: number; + trade_url?: string; + up_rate?: string; // v4.106.4: Maximum price increase percentage + down_rate?: string; // v4.106.4: Maximum price decrease percentage +} +⋮---- +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage + +================ +File: .nvmrc +================ +v22.17.0 + +================ +File: tsconfig.json +================ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "baseUrl": ".", + "noEmitOnError": true, + "declaration": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": false, + "inlineSourceMap": false, + "lib": ["esnext"], + "listEmittedFiles": false, + "listFiles": false, + "moduleResolution": "node", + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noUnusedParameters": true, + "pretty": true, + "removeComments": false, + "resolveJsonModule": true, + "skipLibCheck": false, + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "types": ["node", "jest"], + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext" + }, + "compileOnSave": true, + "exclude": ["node_modules", "dist"], + "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] +} + +================ +File: examples/ws-private-spot-wsapi.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +⋮---- +import { LogParams, WebsocketClient } from '../src/index.js'; +// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +⋮---- +// Define a custom logger object to handle logging at different levels +⋮---- +// Trace level logging: used for detailed debugging information +⋮---- +// Uncomment the line below to enable trace logging +// console.log(new Date(), 'trace', ...params); +⋮---- +// Info level logging: used for general informational messages +⋮---- +// Error level logging: used for error messages +⋮---- +async function start() +⋮---- +// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach +// client.on('update', (data) => { +// // console.info(new Date(), 'ws data received: ', JSON.stringify(data)); +// console.info(new Date(), 'ws data received: ', JSON.stringify(data, null, 2)); +// }); +⋮---- +// Something happened, attempting to reconnect +⋮---- +// Reconnect successful +⋮---- +// Connection closed. If unexpected, expect reconnect -> reconnected. +⋮---- +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +// See comments below about event-driven vs promise-driven. Not needed if using the promise-driven approach +// client.on('response', (data) => { +// console.info( +// new Date(), +// 'ws server reply ', +// JSON.stringify(data, null, 2), +// '\n', +// ); +// }); +⋮---- +// Optional, listen to this event if you prefer the event-driven approach. +// See below comments on event-driven vs promise-driven. +// client.on('authenticated', (data) => { +// console.error(new Date(), 'ws authenticated: ', data); +// }); +⋮---- +/** + * All WebSocket API (WS API) messaging should be done via the sendWSAPIRequest method. + * + * You have two ways to handle responses on the WS API. You can either: + * - event-driven: process async `response` and `update` events from the websocket client, OR + * - promise-driven: await every call to `client.sendWSAPIRequest`, this can behave similar to using a REST API (successful responses resolve, exceptions reject). + */ +⋮---- +/** + * No need to authenticate first - the SDK will automatically authenticate for you when you send your first request. + * + * Unless you want to prepare the connection before your first request, to speed up your first request. + */ +⋮---- +/** + * For other channels, the 3rd parameter should have any parameters for the request (the payload that goes in req_param in the docs). + * + * See WsAPIRequestsTopicMap for a topic->parameter map. + * + * Note that internal parameters such as "signature" etc are all handled automatically by the SDK. + */ +⋮---- +/** + * Submit spot order + */ +⋮---- +/** + * Cancel spot order + */ +⋮---- +/** + * Batch cancel spot order + */ +⋮---- +/** + * Amend/Update spot order + */ +⋮---- +/** + * Get spot order status + */ +⋮---- +/** + * If you don't want to use await (and prefer the async event emitter), make sure to still include a catch block. + * + * The response will come async via the event emitter in the WS Client. + */ +⋮---- +// client +// .sendWSAPIRequest('spotV4', 'spot.order_status', { +// order_id: '600995435390', +// currency_pair: 'BTC_USDT', +// }) +// .catch((e) => { +// console.error(`exception ws api call, get spot order status: `, e); +// }); + +================ +File: 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; + 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; - margin_mode: number; + 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; @@ -4171,105 +5899,40 @@ export interface FuturesAccount { bonus_offset: string; }; enable_tiered_mm: boolean; - funding_balance?: string; } ⋮---- -export interface FuturesAccountBookRecord { +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: string; - text: string; - contract?: string; - trade_id: string; - id: string; -} -⋮---- -export interface FuturesOrder { - id?: number; - user?: number; - create_time?: number; - finish_time?: number; - finish_as?: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed' - | 'stp'; - status?: 'open' | 'finished'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - is_close?: boolean; - reduce_only?: boolean; - is_reduce_only?: boolean; - is_liq?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - left?: number; - fill_price?: string; - text?: string; - tkfr?: string; - mkfr?: string; - refu?: number; - auto_size?: 'close_long' | 'close_short'; - stp_id?: number; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - amend_text?: string; - biz_info?: string; -} -⋮---- -export interface FuturesPosition { - user?: number; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; contract?: string; - size?: number; - leverage?: string; - risk_limit?: string; - leverage_max?: string; - maintenance_rate?: string; - value?: string; - margin?: string; - entry_price?: string; - liq_price?: string; - liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management - mark_price?: string; - initial_margin?: string; - maintenance_margin?: string; - unrealised_pnl?: string; - realised_pnl?: string; - pnl_pnl?: string; - pnl_fund?: string; - pnl_fee?: string; - history_pnl?: string; - last_close_pnl?: string; - realised_point?: string; - history_point?: string; - adl_ranking?: number; - pending_orders?: number; - close_order?: { - id?: number; - price?: string; - is_liq?: boolean; - } | null; - mode?: 'single' | 'dual_long' | 'dual_short'; - cross_leverage_limit?: string; - update_time?: number; - update_id?: number; - open_time?: number; - settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support - isolated_margin?: string; // v4.104.6: Add isolated_margin field + trade_id?: string; } ⋮---- -liquidation_price?: string; // v4.105.7: Add liquidation_price field for better risk management -⋮---- -settlement_currency?: string; // v4.105.9: Add settlement_currency field for multi-settlement support -isolated_margin?: string; // v4.104.6: Add isolated_margin field -⋮---- -export interface FuturesTradingHistoryRecord { +export interface DeliveryTradingHistoryRecord { id: number; create_time: number; contract: string; @@ -4280,10 +5943,9 @@ export interface FuturesTradingHistoryRecord { text: string; fee: string; point_fee: string; - close_size: number; } ⋮---- -export interface FuturesPositionHistoryRecord { +export interface DeliveryClosedPosition { time: number; contract: string; side: 'long' | 'short'; @@ -4296,2313 +5958,2977 @@ export interface FuturesPositionHistoryRecord { first_open_time: number; long_price: string; short_price: string; - accum_size: string; } ⋮---- -export interface FuturesLiquidationHistoryRecord { +export interface DeliveryLiquidationHistoryRecord { time: number; contract: string; - leverage: string; + leverage?: string; size: number; - margin: string; - entry_price: string; - liq_price: string; - mark_price: string; - order_id: 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 { +⋮---- +export interface DeliverySettlementHistoryRecord { time: number; - user: number; - order_id: number; contract: string; leverage: string; - cross_leverage_limit: string; + size: number; + margin: string; entry_price: string; - fill_price: string; - trade_size: number; - position_size: number; + settle_price: string; + profit: string; + fee: string; } -⋮---- -export interface DeleteFuturesBatchOrdersResp { + +================ +File: src/types/response/unified.ts +================ +export interface UnifiedAccountInfo { user_id: number; - id: string; - succeeded: boolean; - message: string; + refresh_time: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + spot_in_use: string; + funding: string; + funding_version: string; + cross_balance: string; // Full margin balance is valid in single currency margin mode, and is 0 in other modes such as cross currency margin/combined margin mode + iso_balance: string; // Isolated Margin Balance applies to Single-Currency Margin Mode and Cross-Currency Margin Mode, and is 0 in other modes such as Portfolio Margin Mode + im: string; + mm: string; + mmr: string; + margin_balance: string; + available_margin: string; + imr?: string; + enabled_collateral?: boolean; + }; + }; + total: string; + borrowed: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + unified_account_total: string; + unified_account_total_liab: string; + unified_account_total_equity: string; + leverage: string; + spot_order_loss: string; // Spot Pending Order Loss, in USDT, effective only in Cross-Currency Margin Mode and Portfolio Margin Mode + options_order_loss?: string; // v4.105.29: Option Pending Order Loss, in USDT, effective only in Portfolio Margin Mode + spot_hedge: boolean; + margin_mode?: string; + total_balance?: string; + cross_leverage?: string; + portfolio_margin?: string; + risk_level?: string; + is_all_collateral?: boolean; + borrow_amount?: string; + cross_margin_leverage?: string; + use_funding?: boolean; } ⋮---- -export interface FuturesContract { - name?: string; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; - mark_type?: 'internal' | 'index'; - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; - funding_rate?: string; - funding_interval?: number; - funding_next_apply?: number; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - orderbook_id?: number; - trade_id?: number; - trade_size?: number; - position_size?: number; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; - enable_bonus?: boolean; - enable_credit?: boolean; - create_time?: number; - funding_cap_ratio?: string; -} +cross_balance: string; // Full margin balance is valid in single currency margin mode, and is 0 in other modes such as cross currency margin/combined margin mode +iso_balance: string; // Isolated Margin Balance applies to Single-Currency Margin Mode and Cross-Currency Margin Mode, and is 0 in other modes such as Portfolio Margin Mode ⋮---- -export interface FuturesPriceTriggeredOrder { - initial: { - contract: string; - size?: number; - price?: string; - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - is_reduce_only?: boolean; - is_close?: boolean; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price?: string; - rule?: 1 | 2; - expiration?: number; - }; - id?: number; - user?: number; - create_time?: number; - finish_time?: number; - trade_id?: number; - status?: 'open' | 'finished' | 'inactive' | 'invalid'; - finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; - reason?: string; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - me_order_id?: number; +spot_order_loss: string; // Spot Pending Order Loss, in USDT, effective only in Cross-Currency Margin Mode and Portfolio Margin Mode +options_order_loss?: string; // v4.105.29: Option Pending Order Loss, in USDT, effective only in Portfolio Margin Mode +⋮---- +export interface UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -export interface FuturesDeliveryContract { - name?: string; - underlying?: string; - cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; - mark_type?: 'internal' | 'index'; - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; - basis_rate?: string; - basis_value?: string; - basis_impact_value?: string; - settle_price?: string; - settle_price_interval?: number; - settle_price_duration?: number; - expire_time?: number; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - orderbook_id?: number; - trade_id?: number; - trade_size?: number; - position_size?: number; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; -} -⋮---- -export interface BatchAmendOrderResp { - succeeded: boolean; - label?: string; - detail?: string; +export interface UnifiedLoanRecord { id: number; - user: number; + type: 'borrow' | 'repay'; + repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; + currency_pair: string; + currency: string; + amount: string; create_time: number; - finish_time?: number; - finish_as?: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed' - | 'reduce_out' - | 'stp'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc' | 'fok'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - stp_act: 'co' | 'cn' | 'cb' | '-'; - stp_id: number; + borrow_type: string; } -⋮---- -/** - * @deprecated - Use FuturesAccount instead - */ -export interface UpdateFuturesDualModeResp { - total: string; - unrealised_pnl: string; - position_margin: string; - order_margin: string; - available: string; - point: string; +export interface UnifiedInterestRecord { currency: string; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic: boolean; - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; -} -⋮---- -export interface RiskLimitTableTier { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; - leverage_max: string; - deduction: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint types -export interface FuturesInsuranceHistory { - t: number; - b: string; +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; + }[]; } - -================ -File: src/types/response/margin.ts -================ -/**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ ⋮---- -export interface MarginAccount { - currency_pair: string; - locked: boolean; - risk: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; +export interface UnifiedCurrencyDiscountTiers { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: string; + }[]; } ⋮---- -export interface MarginBalanceHistoryRecord { - id: string; - time: string; - time_ms: number; - currency: string; - currency_pair: string; - change: string; - balance: string; - type: 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 CrossMarginCurrency { +export interface UnifiedLoanCurrency { 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; + loan_status: 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 UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; } ⋮---- -export interface CrossMarginAccountHistoryRecord { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: 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 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 MarginUserAccount { - currency_pair: string; - account_type: string; - leverage: string; - locked: boolean; - risk?: string; - mmr?: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; +export interface UnifiedCollateralCurrenciesResp { + is_success: boolean; } ================ -File: src/types/response/marginuni.ts +File: src/types/websockets/client.ts ================ -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; +⋮---- +/** + * Event args for subscribing/unsubscribing */ ⋮---- -export interface LendingMarket { - currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; +// export type WsTopicSubscribePrivateArgsV2 = +// | WsTopicSubscribePrivateInstIdArgsV2 +// | WsTopicSubscribePrivateCoinArgsV2; +⋮---- +// export type WsTopicSubscribeEventArgsV2 = +// | WsTopicSubscribePublicArgsV2 +// | WsTopicSubscribePrivateArgsV2; +⋮---- +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + useTestnet?: boolean; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + requestOptions?: {}; + + wsUrl?: string; + + wsOptions?: { + protocols?: string[]; + agent?: any; + } & Partial; + + /** + * 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 MarginUNILoan { - currency: string; +/** Your API key */ +⋮---- +/** Your API secret */ +⋮---- +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +⋮---- +/** How often to check if the connection is alive */ +⋮---- +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +⋮---- +/** Delay in milliseconds before respawning the connection */ +⋮---- +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ +⋮---- +/** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pingInterval: number; + pongTimeout: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; + reauthWSAPIOnReconnect: boolean; +} + +================ +File: src/types/websockets/wsAPI.ts +================ +import { WsKey } from '../../lib/websocket/websocket-util.js'; +⋮---- +export type SpotWSAPITopic = + | 'spot.login' + | 'spot.order_place' + | 'spot.order_cancel' + | 'spot.order_cancel_ids' + | 'spot.order_cancel_cp' + | 'spot.order_amend' + | 'spot.order_status' + | 'spot.order_list'; +⋮---- +export type FuturesWSAPITopic = + | 'futures.login' + | 'futures.order_place' + | 'futures.order_batch_place' + | 'futures.order_cancel' + | 'futures.order_cancel_cp' + | 'futures.order_amend' + | 'futures.order_list' + | 'futures.order_status' + | 'futures.order_cancel_ids'; +⋮---- +export interface WsAPIWsKeyTopicMap { + spotV4: SpotWSAPITopic; + perpFuturesUSDTV4: FuturesWSAPITopic; + perpFuturesBTCV4: FuturesWSAPITopic; + deliveryFuturesUSDTV4: FuturesWSAPITopic; + deliveryFuturesBTCV4: FuturesWSAPITopic; + // optionsV4: never; + // announcementsV4: never; +} +⋮---- +// optionsV4: never; +// announcementsV4: never; +⋮---- +export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; +export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; +⋮---- +// ==================================== +// Spot WebSocket API Request Types +// ==================================== +⋮---- +export interface WSAPISpotOrderPlaceReq { + text?: string; currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'unified' | 'cross_margin'; + side: 'buy' | 'sell'; amount: string; - type: string; - create_time: number; - update_time: number; + 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 MarginUNILoanRecord { - type: string; +export interface WSAPISpotOrderCancelReq { + order_id: string; currency_pair: string; - currency: string; - amount: string; - create_time: number; + account?: string; } ⋮---- -export interface MarginUNIInterestRecord { - currency: string; +export interface WSAPISpotOrderCancelIdsReq { currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; - create_time: number; + id: string; + account?: string; } ⋮---- -export interface MarginUNIMaxBorrowable { - currency: string; +export interface WSAPISpotOrderCancelCPReq { currency_pair: string; - borrowable: string; + side?: 'buy' | 'sell'; + account?: string; } - -================ -File: src/types/response/multicollateralLoan.ts -================ -/**========================================================================================================================== - * MULTI COLLATERAL LOAN - * ========================================================================================================================== - */ ⋮---- -export interface MultiLoanOrder { +export interface WSAPISpotOrderAmendReq { + amount?: string; + price?: string; + amend_text?: string; order_id: string; - order_type: string; - fixed_type: string; - fixed_rate: string; - expire_time: number; - auto_renew: boolean; - auto_repay: boolean; - current_ltv: string; - status: string; - borrow_time: number; - total_left_repay_usdt: string; - total_left_collateral_usdt: string; - borrow_currencies: { - currency: string; - index_price: string; - left_repay_principal: string; - left_repay_interest: string; - left_repay_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - left_collateral: string; - left_collateral_usdt: string; - }[]; + currency_pair: string; + account?: string; } ⋮---- -export interface RepayMultiLoanResp { - order_id: number; - repaid_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - repaid_principal: string; - repaid_interest: string; - }[]; +export interface WSAPISpotOrderStatusReq { + order_id: string; + currency_pair: string; + account?: string; } ⋮---- -export interface MultiLoanRepayRecord { - order_id: number; - record_id: number; - init_ltv: string; - before_ltv: string; - after_ltv: string; - borrow_time: number; - repay_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - repaid_currencies: { - currency: string; - index_price: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - repaid_amount_usdt: string; - }[]; - total_interest_list: { - currency: string; - index_price: string; - amount: string; - amount_usdt: string; - }[]; - left_repay_interest_list: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; +export interface WSAPISpotOrderListReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: string; + from?: number; + to?: number; + side?: 'buy' | 'sell'; } ⋮---- -export interface UpdateMultiLoanResp { - order_id: number; - collateral_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - amount: string; - }[]; -} +// ==================================== +// Futures WebSocket API Request Types +// ==================================== ⋮---- -export interface MultiLoanAdjustmentRecord { - order_id: number; - record_id: number; - before_ltv: string; - after_ltv: string; - operate_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; +export interface WSAPIFuturesOrderPlaceReq { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + text?: string; + auto_size?: 'close_long' | 'close_short'; + stp_act?: 'cn' | 'co' | 'cb'; } ⋮---- -export interface MultiLoanCurrencyQuota { - currency: string; - index_price: string; - min_quota: string; - left_quota: string; - left_quote_usdt: string; +export interface WSAPIFuturesOrderCancelReq { + order_id: string; } ⋮---- -export interface MultiLoanSupportedCurrencies { - loan_currencies: { - currency: string; - price: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - discount: string; - }[]; +export interface WSAPIFuturesOrderCancelCPReq { + contract: string; + side?: 'bid' | 'ask'; } ⋮---- -export interface MultiLoanRatio { - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; +export interface WSAPIFuturesOrderAmendReq { + order_id: string; + price?: string; + size?: number; + amend_text?: string; } ⋮---- -export interface MultiLoanFixedRate { - currency: string; - rate_7d: string; - rate_30d: string; - update_time: number; +export interface WSAPIFuturesOrderListReq { + contract: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: number; } - -================ -File: src/types/response/options.ts -================ -/**========================================================================================================================== - * OPTIONS - * ========================================================================================================================== - */ ⋮---- -export interface OptionsContract { - name: string; - tag: string; - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id: number; - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; - multiplier: string; - order_price_round: string; - mark_price_round: string; - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate: string; - order_size_min: number; - order_size_max: number; - orders_limit: number; +export interface WSAPIFuturesOrderStatusReq { + order_id: string; } ⋮---- -export interface OptionsSettlementHistoryRecord { - time: number; - contract: string; - profit: string; +// ==================================== +// Spot WebSocket API Response Types +// ==================================== +⋮---- +export interface WSAPISpotOrder { + id: string; + text: string; + amend_text: string; + create_time: string; + update_time: string; + create_time_ms: number; + update_time_ms: number; + status: string; + currency_pair: string; + type: string; + account: string; + side: string; + amount: string; + price: string; + time_in_force: string; + iceberg: string; + left: string; + fill_price?: string; + filled_amount?: string; + filled_total: string; + avg_deal_price?: string; fee: string; - strike_price: string; - settle_price: 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 OptionsUserSettlement { - time: number; - underlying: string; - contract: string; - strike_price: string; - settle_price: string; - size: number; - settle_profit: string; - fee: string; - realised_pnl: string; -} -⋮---- -export interface OptionsOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} -⋮---- -export interface OptionsTicker { - name: string; - last_price: string; - mark_price: string; - index_price: string; - ask1_size: number; - ask1_price: string; - bid1_size: number; - bid1_price: string; - position_size: number; - mark_iv: string; - bid_iv: string; - ask_iv: string; - leverage: string; - delta: string; - gamma: string; - vega: string; - theta: string; - rho: string; -} -⋮---- -export interface OptionsCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} -⋮---- -export interface OptionsUnderlyingCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} -⋮---- -export interface OptionsTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; -} -⋮---- -export interface OptionsAccount { - user: number; - total: string; - short_enabled: boolean; - unrealised_pnl: string; - init_margin: string; - maint_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; -} -export interface OptionsAccountChangeRecord { - time: number; - change: string; - balance: string; - type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - text: string; -} -⋮---- -export interface OptionsPositionsUnderlying { - user: number; - underlying: string; - underlying_price: string; - contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; +export interface WSAPISpotOrderCancelIdsRespItem { + currency_pair: string; + id: string; + succeeded: boolean; } ⋮---- -export interface GetOptionsLiquidationResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - text: string; - settle_size: string; -} +// ==================================== +// Futures WebSocket API Response Types +// ==================================== ⋮---- -export interface SubmitOptionsOrderResp { +export interface WSAPIFuturesOrder { 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'; + finish_time?: number; + update_time?: number; + finish_as?: string; + status: string; contract: string; size: number; - iceberg: number; price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; + tif: string; + left?: number; fill_price: string; text: string; tkfr: string; mkfr: string; - refu: number; - refr: string; + stp_id?: number; + stp_act?: string; + amend_text?: string; } ⋮---- -export interface OptionsUserHistoryRecord { - id: number; - create_time: number; - contract: string; - order_id: number; - size: number; - price: string; - underlying_price: string; - role: 'taker' | 'maker'; +export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { + succeeded: boolean; } ⋮---- -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 WSAPIFuturesOrderCancelIdsRespItem { + id: string; + user_id: number; + succeeded?: boolean; + message?: 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 +// ==================================== +// Request Parameter Mapping +// ==================================== +⋮---- +export interface WsAPITopicRequestParamMap { + 'spot.login': undefined; + 'futures.login': undefined; -================ -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; + '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 AgencyCommissionHistoryRecord { - commission_time: number; - user_id: number; - group_name: string; - commission_amount: string; - commission_asset: string; - source: string; +export type WsAPITopicRequestParams = + WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; +⋮---- +// ==================================== +// Response Headers and Base Response +// ==================================== +⋮---- +export interface WSAPIResponseHeader { + /** String timestamp as ms */ + response_time: string; + /** Status of WS API call. "200" if successful, else exception is thrown */ + status: '200' | string; + channel: TChannel; + event: 'api'; + client_id: string; } ⋮---- -export interface PartnerSubordinate { - user_id: number; - user_join_time: number; - type: number; - desc: string; +/** String timestamp as ms */ +⋮---- +/** Status of WS API call. "200" if successful, else exception is thrown */ +⋮---- +export interface WSAPILoginResponse { + api_key: string; + uid: string; } ⋮---- -export interface BrokerCommissionHistoryRecord { - commission_time: number; - user_id: number; - group_name: string; +export interface WSAPIOrderStatusResponse { + left: string; + update_time: string; amount: string; - fee: string; - fee_asset: string; - rebate_fee: string; - source: string; + create_time: string; + price: string; + finish_as: string; + time_in_force: string; currency_pair: string; - sub_broker_info: { - user_id: number; - original_commission_rate: string; - relative_commission_rate: string; - commission_rate: string; - }; + type: string; + account: string; + side: string; + amend_text: string; + text: string; + status: string; + iceberg: string; + avg_deal_price: string; + filled_total: string; + id: string; + fill_price: string; + update_time_ms: number; + create_time_ms: number; } ⋮---- -export interface BrokerTransactionHistoryRecord { - transaction_time: number; - user_id: number; - group_name: string; - fee: string; - currency_pair: string; - amount: string; - fee_asset: string; - source: string; - sub_broker_info: { - user_id: number; - original_commission_rate: string; - relative_commission_rate: string; - commission_rate: string; +export 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 PartnerCommission { - commission_time: number; - user_id: number; - group_name: string; - commission_amount: string; - commission_asset: string; - source: string; -} +/** Auto-generated */ ⋮---- -export interface PartnerTransaction { - transaction_time: number; - user_id: number; - group_name: string; - fee: string; - fee_asset: string; - currency_pair: string; - amount: string; - amount_asset: string; - source: string; +// ==================================== +// Response Type Mapping +// ==================================== +⋮---- +export interface WsAPITopicResponseMap { + 'spot.login': WSAPIResponse; + 'futures.login': WSAPIResponse; + + 'spot.order_place': WSAPIResponse; + 'spot.order_cancel': WSAPIResponse; + 'spot.order_cancel_ids': WSAPIResponse< + WSAPISpotOrderCancelIdsRespItem[], + 'spot.order_cancel_ids' + >; + 'spot.order_cancel_cp': WSAPIResponse< + WSAPISpotOrder[], + 'spot.order_cancel_cp' + >; + 'spot.order_amend': WSAPIResponse; + 'spot.order_status': WSAPIResponse; + 'spot.order_list': WSAPIResponse; + + 'futures.order_place': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_place' + >; + 'futures.order_batch_place': WSAPIResponse< + WSAPIFuturesOrderBatchPlaceRespItem[], + 'futures.order_batch_place' + >; + 'futures.order_cancel': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_cancel' + >; + 'futures.order_cancel_ids': WSAPIResponse< + WSAPIFuturesOrderCancelIdsRespItem[], + 'futures.order_cancel_ids' + >; + 'futures.order_cancel_cp': WSAPIResponse< + WSAPIFuturesOrder[], + 'futures.order_cancel_cp' + >; + 'futures.order_amend': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_amend' + >; + 'futures.order_list': WSAPIResponse< + WSAPIFuturesOrder[], + 'futures.order_list' + >; + 'futures.order_status': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_status' + >; } +⋮---- +// export interface WsAPIResponseMap { +// 'spot.login': WSAPIResponse; +// 'futures.login': WSAPIResponse; +// string: object; +// } ================ -File: src/types/response/spot.ts +File: webpack/webpack.config.cjs +================ +function generateConfig(name) +⋮---- +// Add '.ts' and '.tsx' as resolvable extensions. +⋮---- +// Node.js core modules not available in browsers +// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +⋮---- +// Code is already transpiled from TypeScript, no additional loaders needed + +================ +File: .eslintrc.cjs +================ +// 'no-unused-vars': ['warn'], + +================ +File: .gitignore +================ +!.gitkeep +.DS_STORE +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json +pids +*.pid +*.seed +*.pid.lock +node_modules/ +.npm +.eslintcache +.node_repl_history +*.tgz +.yarn-integrity +.env +.env.test +.cache +bundleReport.html +.history/ +dist +coverage +localtest.sh +repomix.sh +doc + +ws-private-spot-wsapi-performance.ts +ws-private-perp-futures-wsapi-readonly.ts +privatetest.ts + +privaterepotracker +restClientRegex.ts + +testfile.ts + +================ +File: src/types/request/futures.ts ================ /**========================================================================================================================== - * SPOT + * FUTURES * ========================================================================================================================== */ -export interface SpotCurrencyChain { - name: string; - addr?: string; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; +⋮---- +export interface GetFuturesOrderBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; } ⋮---- -export interface SpotCurrency { - currency: string; - name: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - chain: string; - chains: SpotCurrencyChain[]; +export interface GetFuturesTradesReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; } ⋮---- -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 GetFuturesCandlesReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; } ⋮---- -export interface SpotOrderBook { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; +export interface GetFuturesStatsReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + interval?: string; + limit?: number; } ⋮---- -export interface SpotTrade { - id: string; - create_time: string; - create_time_ms: string; - currency_pair: string; - side: 'buy' | 'sell'; - role: 'taker' | 'maker'; - amount: string; - price: string; - order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; +export interface GetFundingRatesReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + from?: number; + to?: number; } ⋮---- -export type SpotCandle = [ - string, // Unix timestamp with second precision - string, // Trading volume in quote currency - string, // Closing price - string, // Highest price - string, // Lowest price - string, // Opening price - string, // Trading volume in base currency - boolean, // Whether the window is closed -]; +export interface GetLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; +} ⋮---- -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 GetRiskLimitTiersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; +} ⋮---- -export interface SpotFeeRates { - user_id: number; - taker_fee: string; - maker_fee: string; - gt_discount: boolean; - gt_taker_fee: string; - gt_maker_fee: string; - loan_fee: string; - point_type: string; - currency_pair: string; - debit_fee: number; +export interface GetRiskLimitTableReq { + settle: 'btc' | 'usdt' | 'usd'; + table_id: string; } ⋮---- -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 GetFuturesAccountBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; } ⋮---- -export interface SpotAccountBook { - id: string; - time: number; - currency: string; +export interface GetFuturesPositionsReq { + settle: 'btc' | 'usdt' | 'usd'; + holding?: boolean; + limit?: number; + offset?: number; + position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support + hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +} +⋮---- +position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support +hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +⋮---- +export interface UpdateDualModePositionMarginReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; change: string; - balance: string; - type: string; - code: string; - text: string; + dual_side: 'dual_long' | 'dual_short'; } ⋮---- -export interface SubmitSpotBatchOrdersResp { - order_id: string; - amend_text: string; - text: string; - succeeded: boolean; - label: string; - message: string; - id: string; - create_time: string; - update_time: string; - create_time_ms: number; - update_time_ms: number; - status: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type: 'limit' | 'market'; - account: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; - price: string; - time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg: string; - auto_repay: boolean; - left: string; - filled_amount: string; - fill_price: string; - filled_total: string; - avg_deal_price: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - gt_discount: boolean; - rebated_fee: string; - rebated_fee_currency: string; - stp_id: number; - stp_act: 'cn' | 'co' | 'cb' | '-'; - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; +export interface UpdateDualModePositionLeverageReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + leverage: string; + cross_leverage_limit?: string; } ⋮---- -export interface SpotOrder { - id?: string; - text?: string; - amend_text?: string; - create_time?: string; - update_time?: string; - create_time_ms?: number; - update_time_ms?: number; - status?: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; +export interface SubmitFuturesOrderReq { + xGateExptime?: number; + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + size: number; + iceberg?: number; price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - left?: string; - filled_amount?: string; - fill_price?: string; - filled_total?: string; - avg_deal_price?: string; - fee?: string; - fee_currency?: string; - point_fee?: string; - gt_fee?: string; - gt_maker_fee?: string; - gt_taker_fee?: string; - gt_discount?: boolean; - rebated_fee?: string; - rebated_fee_currency?: string; - stp_id?: number; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; } ⋮---- -export interface SpotInsuranceHistory { - currency: string; - balance: string; - time: number; +export interface GetFuturesOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; } ⋮---- -export interface SpotPriceTriggeredOrder { - trigger: { - price: string; - rule: '>=' | '<='; - expiration: number; - }; - put: { - type?: 'limit' | 'market'; - side: 'buy' | 'sell'; - price: string; - amount: string; - account: 'normal' | 'margin' | 'cross_margin'; - time_in_force?: 'gtc' | 'ioc'; - text?: string; - }; - id?: number; - user?: number; - market: string; - ctime?: number; - ftime?: number; - fired_order_id?: number; - status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; - reason?: string; +export interface DeleteAllFuturesOrdersReq { + xGateExptime?: number; + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + side?: string; } ⋮---- -export interface GetSpotOpenOrdersResp { - currency_pair: string; - total: number; - orders: SpotOrder[]; +export interface GetFuturesOrdersByTimeRangeReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; } ⋮---- -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; +export interface UpdateFuturesOrderReq { + xGateExptime?: number; + settle: 'btc' | 'usdt' | 'usd'; order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; + size?: number; + price?: string; + amend_text?: string; } - -================ -File: src/types/response/subaccount.ts -================ -export interface SubAccount { - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; +⋮---- +export interface GetFuturesTradingHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; } ⋮---- -export interface CreatedSubAccountAPIKey { - user_id: string; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; - key: string; - state: number; - created_at: number; - updated_at: number; - last_access: number; +export interface GetFuturesTradingHistoryByTimeRangeReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + role?: 'maker' | 'taker'; } ⋮---- -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 GetFuturesPositionHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; } ⋮---- -export interface SubAccountMode { - user_id: number; - is_unified: boolean; - mode: 'classic' | 'multi_currency' | 'portfolio'; +export interface GetFuturesLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + at?: number; } - -================ -File: src/types/response/unified.ts -================ -export interface UnifiedAccountInfo { - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [key: string]: { - available: string; - freeze: string; - borrowed: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - spot_in_use: string; - funding: string; - funding_version: string; - cross_balance: string; - iso_balance: string; - im: string; - mm: string; - mmr: string; - margin_balance: string; - available_margin: string; - imr?: string; - enabled_collateral?: boolean; - }; +⋮---- +export interface SubmitFuturesTriggeredOrderReq { + initial: { + contract: string; + size?: number; + price: string; // Required: Order price. Set to 0 to use market price + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; }; - total: string; - borrowed: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - unified_account_total: string; - unified_account_total_liab: string; - unified_account_total_equity: string; - leverage: string; - spot_order_loss: string; - spot_hedge: boolean; - margin_mode?: string; - total_balance?: string; - cross_leverage?: string; - portfolio_margin?: string; - risk_level?: string; - is_all_collateral?: boolean; - borrow_amount?: string; - cross_margin_leverage?: string; - use_funding?: boolean; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price: string; // Required: Price value for price trigger + rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) + expiration?: number; + }; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + settle: 'btc' | 'usdt' | 'usd'; } ⋮---- -export interface UnifiedLoan { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; -} +price: string; // Required: Order price. Set to 0 to use market price ⋮---- -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; +price: string; // Required: Price value for price trigger +rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +⋮---- +export interface GetFuturesAutoOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; } ⋮---- -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; - }[]; +/** + * Modify contract order parameters + */ +export interface BatchAmendOrderReq { + order_id?: number; // Order id, order_id and text must contain at least one + text?: string; // User-defined order text, at least one of order_id and text must be passed + size?: number; // The new order size, including the executed order size + price?: string; // New order price + amend_text?: string; // Custom info during amending order } ⋮---- -export interface 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; -} +order_id?: number; // Order id, order_id and text must contain at least one +text?: string; // User-defined order text, at least one of order_id and text must be passed +size?: number; // The new order size, including the executed order size +price?: string; // New order price +amend_text?: string; // Custom info during amending order ⋮---- -export interface UnifiedHistoryLendingRate { - currency: string; - tier: string; - tier_up_rate: string; - rates: { - time: number; - rate: string; - }[]; +// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request +export interface GetFuturesPositionCloseHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; } ⋮---- -export interface MarginTier { - tier: string; - margin_rate: string; - lower_limit: string; - upper_limit: string; +// v4.104.6: New GET /futures/{settle}/insurance endpoint request +export interface GetFuturesInsuranceReq { + settle: 'btc' | 'usdt' | 'usd'; + limit?: number; } ⋮---- -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 UpdateFuturesPriceTriggeredOrderReq { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + contract?: string; + size?: number; + price?: string; + trigger_price?: string; + price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price + auto_size?: string; // Not required in single position mode } ⋮---- -export interface UnifiedCollateralCurrenciesResp { - is_success: boolean; -} +price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price +auto_size?: string; // Not required in single position mode ================ -File: src/types/response/wallet.ts +File: src/types/response/futures.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; +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ +⋮---- +export interface FuturesOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: 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; +export interface FuturesTrade { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; // Deprecated } ⋮---- -| '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 +is_internal?: boolean; // Deprecated ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; +export interface FuturesCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; } ⋮---- -export interface SubAccountTransferRecord { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - uid: string; - client_order_id: string; - timest: string; - source: string; - sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; +export interface PremiumIndexKLine { + t: number; + c: string; + h: string; + l: string; + o: 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 }; +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; } ⋮---- -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; - }; -} +quanto_base_rate?: string; // Deprecated ⋮---- -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 FuturesStats { + time: number; + lsr_taker: number; + lsr_account: number; + long_liq_size: number; + long_liq_amount: number; + long_liq_usd: number; + short_liq_size: number; + short_liq_amount: number; + short_liq_usd: number; + open_interest: number; + open_interest_usd: number; + top_lsr_account: number; + top_lsr_size: number; } ⋮---- -export interface 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 IndexConstituents { + index: string; + constituents: { + exchange: string; + symbols: string[]; + }[]; } ⋮---- -export interface SavedAddress { +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; - chain: string; - address: string; - name: string; - tag: string; - verified: 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; + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'stp'; + status?: 'open' | 'finished'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + is_close?: boolean; + reduce_only?: boolean; + is_reduce_only?: boolean; + is_liq?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + left?: number; + fill_price?: string; + text?: string; + tkfr?: string; + mkfr?: string; + refu?: number; + auto_size?: 'close_long' | 'close_short'; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + amend_text?: string; + biz_info?: string; +} +⋮---- +export interface FuturesPosition { + user?: number; + contract?: string; + size?: number; + leverage?: string; // 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 +} +⋮---- +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 +⋮---- +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 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 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; + 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 + funding_rate?: string; + funding_interval?: number; + funding_next_apply?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; + enable_bonus?: boolean; + enable_credit?: boolean; + create_time?: number; + funding_cap_ratio?: string; // Deprecated + funding_rate_limit?: string; // v4.106.4: Funding rate cap value +} +⋮---- +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 +⋮---- +funding_cap_ratio?: string; // Deprecated +funding_rate_limit?: string; // v4.106.4: Funding rate cap value +⋮---- +export interface FuturesPriceTriggeredOrder { + initial: { + contract: string; + size?: number; + price?: string; + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + is_reduce_only?: boolean; + is_close?: boolean; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price?: string; + rule?: 1 | 2; + expiration?: number; + }; + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + trade_id?: number; + status?: 'open' | 'finished' | 'inactive' | 'invalid'; + finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; + reason?: string; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + me_order_id?: number; +} +⋮---- +export interface FuturesDeliveryContract { + name?: string; + underlying?: string; + cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; // 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; +} +⋮---- +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; + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'reduce_out' + | 'stp'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc' | 'fok'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + stp_act: 'co' | 'cn' | 'cb' | '-'; + stp_id: number; +} +⋮---- +/** + * @deprecated - Use FuturesAccount instead + */ +export interface UpdateFuturesDualModeResp { + total: string; + unrealised_pnl: string; + position_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic: boolean; + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; +} +⋮---- +export interface RiskLimitTableTier { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; // 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; +} + +================ +File: src/types/response/spot.ts +================ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ +export interface SpotCurrencyChain { + name: string; + addr?: string; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; +} +⋮---- +export interface SpotCurrency { + currency: string; + name: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + chain: string; + chains: SpotCurrencyChain[]; +} +⋮---- +export interface SpotTicker { + currency_pair: string; + last: string; + lowest_ask: string; + lowest_size: string; + highest_bid: string; + highest_size: string; + change_percentage: string; + change_utc0: string; + change_utc8: string; + base_volume: string; + quote_volume: string; + high_24h: string; + low_24h: string; + etf_net_value: string; + etf_pre_net_value: string | null; + etf_pre_timestamp: number | null; + etf_leverage: string | null; +} +⋮---- +export interface SpotOrderBook { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; +} +⋮---- +export interface SpotTrade { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; + order_id: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; +} +⋮---- +export type SpotCandle = [ + string, // Unix timestamp with second precision + string, // Trading volume in quote currency + string, // Closing price + string, // Highest price + string, // Lowest price + string, // Opening price + string, // Trading volume in base currency + boolean, // Whether the window is closed +]; +⋮---- +string, // Unix timestamp with second precision +string, // Trading volume in quote currency +string, // Closing price +string, // Highest price +string, // Lowest price +string, // Opening price +string, // Trading volume in base currency +boolean, // Whether the window is closed +⋮---- +export interface SpotFeeRates { + user_id: number; + taker_fee: string; // 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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; +} +⋮---- +export interface SpotOrder { + id?: string; + text?: string; + amend_text?: string; + create_time?: string; + update_time?: string; + create_time_ms?: number; + update_time_ms?: number; + status?: 'open' | 'closed' | 'cancelled'; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + side: 'buy' | 'sell'; + amount: string; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + left?: string; + filled_amount?: string; + fill_price?: string; + filled_total?: string; + avg_deal_price?: string; + fee?: string; + fee_currency?: string; + point_fee?: string; + gt_fee?: string; + gt_maker_fee?: string; + gt_taker_fee?: string; + gt_discount?: boolean; + rebated_fee?: string; + rebated_fee_currency?: string; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} +⋮---- +export interface SpotInsuranceHistory { + currency: string; + balance: string; + time: number; +} +⋮---- +export interface SpotPriceTriggeredOrder { + trigger: { + price: string; + rule: '>=' | '<='; + expiration: number; + }; + put: { + type?: 'limit' | 'market'; + side: 'buy' | 'sell'; + price: string; + amount: string; + account: 'normal' | 'margin' | 'cross_margin'; + time_in_force?: 'gtc' | 'ioc'; + text?: string; + }; + id?: number; + user?: number; + market: string; + ctime?: number; + ftime?: number; + fired_order_id?: number; + status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; + reason?: string; +} +⋮---- +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: SpotOrder[]; +} +⋮---- +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; + text: string; +} +⋮---- +export interface SpotHistoricTradeRecord { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; + order_id: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; + deal?: string; // v4.105.29: Total Executed Value +} +⋮---- +deal?: string; // v4.105.29: Total Executed Value + +================ +File: examples/ws-api-client.ts +================ +import { WebsocketAPIClient, WS_KEY_MAP } from '../src/index.js'; +// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` +⋮---- +async function start() +⋮---- +/** + * Optional: authenticate in advance. This will prepare and authenticate a connection. + * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. + */ +// console.log(new Date(), 'Authenticating in advance...'); +// await client.getWSClient().connectWSAPI('spotV4'); +// console.log(new Date(), 'Authenticating in advance...OK!'); +⋮---- +/* ============ SPOT TRADING EXAMPLES ============ */ +⋮---- +// SPOT ORDER PLACE - Submit a new spot order +⋮---- +// SPOT ORDER CANCEL - Cancel a specific spot order +⋮---- +// SPOT ORDER CANCEL BY IDS - Cancel orders by ID list +⋮---- +// SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair +⋮---- +// SPOT ORDER AMEND - Update an existing spot order +⋮---- +// SPOT ORDER STATUS - Get status of a specific spot order +⋮---- +// SPOT ORDER LIST - Get list of spot orders +⋮---- +/* ============ FUTURES TRADING EXAMPLES ============ */ +⋮---- +/** + * Gate has different websocket groups depending on the futures product. + * + * This affects which connection your command is sent to, so make sure to pass one matching your request. Look at WS_KEY_MAP (or the examples below) for details on the available product groups. + */ +⋮---- +/** + * Also optional, as for spot. Keep in mind the first parameter (wsKey) might vary depending on which WS URL is needed. + */ +⋮---- +// console.log(new Date(), 'Authenticating in advance...'); +// await client.getWSClient().connectWSAPI(futuresConnectionGroup); +// await client.getWSClient().connectWSAPI('perpFuturesUSDTV4'); +// await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); +// await client.getWSClient().connectWSAPI('deliveryFuturesUSDTV4'); +// await client.getWSClient().connectWSAPI('perpFuturesBTCV4'); +// console.log(new Date(), 'Authenticating in advance...OK!'); +⋮---- +// FUTURES ORDER PLACE - Submit a new futures order +⋮---- +// FUTURES ORDER BATCH PLACE - Submit multiple futures orders +⋮---- +// FUTURES ORDER CANCEL - Cancel a specific futures order +⋮---- +// FUTURES ORDER CANCEL BY IDS - Cancel futures orders by ID list +⋮---- +// FUTURES ORDER CANCEL ALL - Cancel all open futures orders +⋮---- +// FUTURES ORDER AMEND - Update an existing futures order +⋮---- +// FUTURES ORDER LIST - Get list of futures orders +⋮---- +// FUTURES ORDER STATUS - Get status of a specific futures order + +================ +File: src/lib/BaseWSClient.ts +================ +import EventEmitter from 'events'; +import WebSocket from 'isomorphic-ws'; +⋮---- +import { + WebsocketClientOptions, + WSClientConfigurableOptions, +} from '../types/websockets/client.js'; +import { WsOperation } from '../types/websockets/requests.js'; +import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; +import { DefaultLogger } from './logger.js'; +import { isMessageEvent, MessageEventLike } from './requestUtils.js'; +import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; +import { + safeTerminateWs, + WsTopicRequest, + WsTopicRequestOrStringTopic, +} from './websocket/websocket-util.js'; +import { WsStore } from './websocket/WsStore.js'; +import { + WSConnectedResult, + WsConnectionStateEnum, +} from './websocket/WsStore.types.js'; +⋮---- +interface WSClientEventMap { + /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ + open: (evt: { + wsKey: WsKey; + event: any; + wsUrl: string; + ws: WebSocket; + }) => void /** Reconnecting a dropped connection */; + reconnect: (evt: { wsKey: WsKey; event: any }) => void; + /** Successfully reconnected a connection that dropped */ + reconnected: (evt: { + wsKey: WsKey; + event: any; + wsUrl: string; + ws: WebSocket; + }) => void; + /** Connection closed */ + close: (evt: { wsKey: WsKey; event: any }) => void; + /** Received reply to websocket command (e.g. after subscribing to topics) */ + response: (response: any & { wsKey: WsKey }) => void; + /** Received data for topic */ + update: (response: any & { wsKey: WsKey }) => void; + /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ + exception: (response: any & { wsKey: WsKey }) => void; + error: (response: any & { wsKey: WsKey }) => void; + /** Confirmation that a connection successfully authenticated */ + authenticated: (event: { wsKey: WsKey; event: any }) => void; +} +⋮---- +/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +⋮---- +}) => void /** Reconnecting a dropped connection */; +⋮---- +/** Successfully reconnected a connection that dropped */ +⋮---- +/** Connection closed */ +⋮---- +/** Received reply to websocket command (e.g. after subscribing to topics) */ +⋮---- +/** Received data for topic */ +⋮---- +/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +⋮---- +/** Confirmation that a connection successfully authenticated */ +⋮---- +export interface EmittableEvent { + eventType: 'response' | 'update' | 'exception' | 'authenticated'; + event: TEvent; +} +⋮---- +// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 +export interface BaseWebsocketClient { + on>( + event: U, + listener: WSClientEventMap[U], + ): this; + + emit>( + event: U, + ...args: Parameters[U]> + ): boolean; +} +⋮---- +on>( + event: U, + listener: WSClientEventMap[U], + ): this; +⋮---- +emit>( + event: U, + ...args: Parameters[U]> + ): boolean; +⋮---- +/** + * Users can conveniently pass topics as strings or objects (object has topic name + optional params). + * + * This method normalises topics into objects (object has topic name + optional params). + */ +function getNormalisedTopicRequests( + wsTopicRequests: WsTopicRequestOrStringTopic[], +): WsTopicRequest[] +⋮---- +// passed as string, convert to object +⋮---- +// already a normalised object, thanks to user +⋮---- +/** + * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" + */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging +export abstract class BaseWebsocketClient< +⋮---- +/** + * The WS connections supported by the client, each identified by a unique primary key + */ +⋮---- +/** + * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected + */ +⋮---- +constructor( + options?: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, +) +⋮---- +// Some defaults: +⋮---- +// Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. +⋮---- +// Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. +⋮---- +// Automatically re-auth WS API, if we were auth'd before and get reconnected +⋮---- +// Check Web Crypto API support when credentials are provided and no custom sign function is used +⋮---- +protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; +⋮---- +protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; +⋮---- +protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; +⋮---- +protected abstract isWsPing(data: any): boolean; +⋮---- +protected abstract isWsPong(data: any): boolean; +⋮---- +protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; +⋮---- +protected abstract isPrivateTopicRequest( + request: WsTopicRequest, + wsKey: TWSKey, + ): boolean; +⋮---- +protected abstract getPrivateWSKeys(): TWSKey[]; +⋮---- +protected abstract getWsUrl(wsKey: TWSKey): string; +⋮---- +protected abstract getMaxTopicsPerSubscribeEvent( + wsKey: TWSKey, + ): number | null; +⋮---- +/** + * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics + */ +protected abstract getWsOperationEventsForTopics( + topics: WsTopicRequest[], + wsKey: TWSKey, + operation: WsOperation, + ): Promise; +⋮---- +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected abstract resolveEmittableEvents( + wsKey: TWSKey, + event: MessageEventLike, + ): EmittableEvent[]; +⋮---- +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +protected abstract connectAll(): Promise[]; +⋮---- +protected isPrivateWsKey(wsKey: TWSKey): boolean +⋮---- +/** Returns auto-incrementing request ID, used to track promise references for async requests */ +protected getNewRequestId(): string +⋮---- +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params?: any, + ): Promise; +⋮---- +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params: any, + ): Promise; +⋮---- +public getTimeOffsetMs() +⋮---- +// TODO: not implemented +public setTimeOffsetMs(newOffset: number) +⋮---- +/** + * Don't call directly! Use subscribe() instead! + * + * Subscribe to one or more topics on a WS connection (identified by WS Key). + * + * - Topics are automatically cached + * - Connections are automatically opened, if not yet connected + * - Authentication is automatically handled + * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). + * + * @param wsRequests array of topics to subscribe to + * @param wsKey ws key referring to the ws connection these topics should be subscribed on + */ +protected subscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, +) +⋮---- +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +⋮---- +// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +⋮---- +// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +⋮---- +/** + * Are we in the process of connection? Nothing to send yet. + */ +⋮---- +// We're connected. Check if auth is needed and if already authenticated +⋮---- +/** + * If not authenticated yet and auth is required, don't request topics yet. + * + * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. + */ +⋮---- +// Finally, request subscription to topics if the connection is healthy and ready +⋮---- +protected unsubscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, +) +⋮---- +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +⋮---- +// If not connected, don't need to do anything. +// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. +⋮---- +// We're connected. Check if auth is needed and if already authenticated +⋮---- +/** + * If not authenticated yet and auth is required, don't need to do anything. + * We don't subscribe to topics until auth is complete anyway. + */ +⋮---- +// Finally, request subscription to topics if the connection is healthy and ready +⋮---- +/** + * Splits topic requests into two groups, public & private topic requests + */ +private sortTopicRequestsIntoPublicPrivate( + wsTopicRequests: WsTopicRequest[], + wsKey: TWSKey, +): +⋮---- +/** Get the WsStore that tracks websockets & topics */ +public getWsStore(): WsStore> +⋮---- +public close(wsKey: TWSKey, force?: boolean) +⋮---- +public closeAll(force?: boolean) +⋮---- +public isConnected(wsKey: TWSKey): boolean +⋮---- +/** + * Request connection to a specific websocket, instead of waiting for automatic connection. + */ +protected async connect( + wsKey: TWSKey, +): Promise +⋮---- +private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket +⋮---- +private parseWsError(context: string, error: any, wsKey: TWSKey) +⋮---- +/** Get a signature, build the auth request and send it */ +private async sendAuthRequest(wsKey: TWSKey): Promise +⋮---- +// console.log('ws auth req', request); +⋮---- +private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) +⋮---- +private ping(wsKey: TWSKey) +⋮---- +private clearTimers(wsKey: TWSKey) +⋮---- +// Send a ping at intervals +private clearPingTimer(wsKey: TWSKey) +⋮---- +// Expect a pong within a time limit +private clearPongTimer(wsKey: TWSKey) +⋮---- +// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +⋮---- +// this.logger.trace(`No active pong timer for "${wsKey}"`); +⋮---- +/** + * Simply builds and sends subscribe events for a list of topics for a ws key + * + * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. + */ +private async requestSubscribeTopics( + wsKey: TWSKey, + topics: WsTopicRequest[], +) +⋮---- +// Automatically splits requests into smaller batches, if needed +⋮---- +`Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +⋮---- +// console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); +⋮---- +// this.logger.trace(`Sending batch via message: "${wsMessage}"`); +⋮---- +/** + * Simply builds and sends unsubscribe events for a list of topics for a ws key + * + * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. + */ +private async requestUnsubscribeTopics( + wsKey: TWSKey, + wsTopicRequests: WsTopicRequest[], +) +⋮---- +/** + * Try sending a string event on a WS connection (identified by the WS Key) + */ +public tryWsSend( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, +) +⋮---- +private async onWsOpen( + event: any, + wsKey: TWSKey, + url: string, + ws: WebSocket, +) +⋮---- +// Resolve & cleanup deferred "connection attempt in progress" promise +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +⋮---- +// Remove before resolving, in case there's more requests queued +⋮---- +// Some websockets require an auth packet to be sent after opening the connection +⋮---- +// Reconnect to topics known before it connected +⋮---- +// Request sub to public topics, if any +⋮---- +// Request sub to private topics, if auth on connect isn't needed +⋮---- +// If enabled, automatically reauth WS API if reconnected +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +⋮---- +/** + * Handle subscription to private topics _after_ authentication successfully completes asynchronously. + * + * Only used for exchanges that require auth before sending private topic subscription requests + */ +private onWsAuthenticated( + wsKey: TWSKey, + event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, +) +⋮---- +// Resolve & cleanup deferred "auth attempt in progress" promise +⋮---- +// Remove before continuing, in case there's more requests queued +⋮---- +private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) +⋮---- +// any message can clear the pong timer - wouldn't get a message if the ws wasn't working +⋮---- +// console.log(`raw event: `, { data, dataType, emittableEvents }); +⋮---- +private onWsClose(event: unknown, wsKey: TWSKey) +⋮---- +// unintentional close, attempt recovery +⋮---- +// clean up any pending promises for this connection +⋮---- +// intentional close - clean up +// clean up any pending promises for this connection +⋮---- +// clean up any pending promises for this connection +⋮---- +// This was an intentional close, delete all state for this connection, as if it never existed: +⋮---- +private getWs(wsKey: TWSKey) +⋮---- +private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +⋮---- +/** + * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) + */ +protected async assertIsConnected(wsKey: TWSKey): Promise +⋮---- +// Already in progress? Await shared promise and retry +⋮---- +// Start connection, it should automatically store/return a promise. +⋮---- +/** + * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) + */ +public async assertIsAuthenticated(wsKey: TWSKey): Promise +⋮---- +// Already in progress? Await shared promise and retry +⋮---- +// this.logger.trace('assertIsAuthenticated(): ok'); +⋮---- +// Start authentication, it should automatically store/return a promise. + +================ +File: src/WebsocketAPIClient.ts +================ +import { DefaultLogger } from './lib/logger.js'; +import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; +import { WSClientConfigurableOptions } from './types/websockets/client.js'; +import { + WSAPIFuturesOrder, + WSAPIFuturesOrderAmendReq, + WSAPIFuturesOrderBatchPlaceRespItem, + WSAPIFuturesOrderCancelCPReq, + WSAPIFuturesOrderCancelIdsRespItem, + WSAPIFuturesOrderCancelReq, + WSAPIFuturesOrderListReq, + WSAPIFuturesOrderPlaceReq, + WSAPIFuturesOrderStatusReq, + WSAPIResponse, + WSAPISpotOrder, + WSAPISpotOrderAmendReq, + WSAPISpotOrderCancelCPReq, + WSAPISpotOrderCancelIdsReq, + WSAPISpotOrderCancelIdsRespItem, + WSAPISpotOrderCancelReq, + WSAPISpotOrderListReq, + WSAPISpotOrderPlaceReq, + WSAPISpotOrderStatusReq, + WSAPIWsKey, +} from './types/websockets/wsAPI.js'; +import { WebsocketClient } from './WebsocketClient.js'; +⋮---- +/** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ + attachEventListeners: boolean; +} +⋮---- +/** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ +⋮---- +/** + * This is a minimal Websocket API wrapper around the WebsocketClient. + * + * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should + * be used to transmit that message. This is only useful if you wish to use an alternative wss + * domain that is supported by the SDK. + * + * Note: To use testnet, don't set the wsKey - use `testnet: true` in + * the constructor instead. + * + * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some + * may find the below methods slightly more intuitive. + * + * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: + * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 + */ +export class WebsocketAPIClient +⋮---- +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) +⋮---- +public getWSClient(): WebsocketClient ⋮---- -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; - }; - }; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -export interface SmallBalanceRecord { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; -} +/* + * + * SPOT - Trading requests + * + */ ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; -} +/** + * Submit a spot order + */ +submitNewSpotOrder( + params: WSAPISpotOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface PushOrder { - id: number; - push_uid: number; - receive_uid: number; - currency: string; - amount: string; - create_time: number; - status: - | 'CREATING' - | 'PENDING' - | 'CANCELLING' - | 'CANCELLED' - | 'REFUSING' - | 'REFUSED' - | 'RECEIVING' - | 'RECEIVED'; - message: string; -} - -================ -File: src/types/response/withdrawal.ts -================ -export interface WithdrawalRecord { - id: string; - txid: string; - block_number: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'BCODE' // Deposit Code Operation - | 'CANCEL' // Cancelled - | 'CANCELPEND' // Withdrawal Cancellation Pending - | 'DMOVE' // Pending Manual Review - | 'DONE' // Completed (Only considered truly on-chain when block_number > 0) - | 'EXTPEND' // Sent and Waiting for Confirmation - | 'FAIL' // On-Chain Failure Pending Confirmation - | 'FVERIFY' // Facial Verification in Progress - | 'INVALID' // Invalid Transaction - | 'LOCKED' // Wallet-Side Order Locked - | 'MANUAL' // Pending Manual Review - | 'PEND' // Processing - | 'PROCES' // Processing - | 'REJECT' // Rejected - | 'REQUEST' // Request in Progress - | 'REVIEW' // Under Review - | 'SPLITPEND' // Split Pending - | 'VERIFY'; // Verification in Progress - chain: string; -} +/** + * Cancel a spot order + */ +cancelSpotOrder( + params: WSAPISpotOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -| 'BCODE' // Deposit Code Operation -| 'CANCEL' // Cancelled -| 'CANCELPEND' // Withdrawal Cancellation Pending -| 'DMOVE' // Pending Manual Review -| 'DONE' // Completed (Only considered truly on-chain when block_number > 0) -| 'EXTPEND' // Sent and Waiting for Confirmation -| 'FAIL' // On-Chain Failure Pending Confirmation -| 'FVERIFY' // Facial Verification in Progress -| 'INVALID' // Invalid Transaction -| 'LOCKED' // Wallet-Side Order Locked -| 'MANUAL' // Pending Manual Review -| 'PEND' // Processing -| 'PROCES' // Processing -| 'REJECT' // Rejected -| 'REQUEST' // Request in Progress -| 'REVIEW' // Under Review -| 'SPLITPEND' // Split Pending -| 'VERIFY'; // Verification in Progress - -================ -File: src/types/websockets/client.ts -================ /** - * Event args for subscribing/unsubscribing - */ + * Cancel all spot orders with the given id list + */ +cancelSpotOrderById( + params: WSAPISpotOrderCancelIdsReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// export type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +/** + * Cancel a spot order for a given symbol + */ +cancelSpotOrderForSymbol( + params: WSAPISpotOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +/** + * Update a spot order + */ +updateSpotOrder( + params: WSAPISpotOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** General configuration for the WebsocketClient */ -export interface WSClientConfigurableOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - useTestnet?: boolean; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - requestOptions?: {}; - - wsUrl?: string; - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method +/** + * 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 * - * 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. +⋮---- +/** + * Submit a futures order. + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ - reauthWSAPIOnReconnect?: boolean; -} +submitNewFuturesOrder( + params: WSAPIFuturesOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** Your API key */ +/** + * Submit a batch of futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +submitNewFuturesBatchOrder( + params: WSAPIFuturesOrderPlaceReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** Your API secret */ +/** + * Cancel a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrder( + params: WSAPIFuturesOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +/** + * Cancel futures orders by id list + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrderById( + params: string[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** How often to check if the connection is alive */ +/** + * Cancel all open futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesAllOpenOrders( + params: WSAPIFuturesOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +/** + * Update a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +updateFuturesOrder( + params: WSAPIFuturesOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -/** Delay in milliseconds before respawning the connection */ +/** + * Get all futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrders( + params: WSAPIFuturesOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * Get futures order status * - * Look in the examples folder for a demonstration on using node's createHmac instead. + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection */ +getFuturesOrderStatus( + params: WSAPIFuturesOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- /** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * */ ⋮---- +private setupDefaultEventListeners() +⋮---- /** - * 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; -} + * General event handlers for monitoring the WebsocketClient + */ +⋮---- +// Blind JSON.stringify can fail on circular references +⋮---- +// JSON.stringify({ ...data, target: 'WebSocket' }), ================ -File: src/types/websockets/events.ts +File: src/WebsocketClient.ts ================ -export interface WsDataEvent { - data: TData; - table: string; - wsKey: TWSKey; +import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; +import { neverGuard } from './lib/misc-util.js'; +import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; +import { + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './lib/webCryptoAPI.js'; +import { + getPrivateFuturesTopics, + getPrivateOptionsTopics, + getPrivateSpotTopics, + getPromiseRefForWSAPIRequest, + WS_BASE_URL_MAP, + WS_KEY_MAP, + WsKey, + WsMarket, + WsTopicRequest, +} from './lib/websocket/websocket-util.js'; +import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; +import { + WSAPIRequest, + WsOperation, + WsRequestOperationGate, + WsRequestPing, +} from './types/websockets/requests.js'; +import { + WsAPITopicRequestParamMap, + WsAPITopicResponseMap, + WSAPIWsKey, + WsAPIWsKeyTopicMap, +} from './types/websockets/wsAPI.js'; +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; } - -================ -File: src/types/websockets/requests.ts -================ -import { CHANNEL_ID } from '../../lib/requestUtils.js'; -import { WSAPITopic } from './wsAPI.js'; ⋮---- -export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; +/** If true, will skip auth requirement for WS API connection */ ⋮---- -export interface WsRequestAuthGate { - method: 'api_key'; - KEY: string; - SIGN: string; -} +/** + * WS topics are always a string for gate. Some exchanges use complex objects + */ +export type WsTopic = string; ⋮---- -export interface WsRequestPing { - time: number; - channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; -} +export class WebsocketClient extends BaseWebsocketClient ⋮---- -export interface WsRequestOperationGate< - TWSTopic extends string, - TWSPayload = any, -> { - time: number; - id?: number; - channel: TWSTopic; - auth?: WsRequestAuthGate; - event?: WsOperation; - payload?: TWSPayload; -} +/** + * 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[] ⋮---- -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'; +/** + * 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 ⋮---- -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'; +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -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'; +/** + * 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, +) ⋮---- -export interface WsAPIWsKeyTopicMap { - spotV4: SpotWSAPITopic; - perpFuturesUSDTV4: FuturesWSAPITopic; - perpFuturesBTCV4: FuturesWSAPITopic; - deliveryFuturesUSDTV4: FuturesWSAPITopic; - deliveryFuturesBTCV4: FuturesWSAPITopic; - // optionsV4: never; - // announcementsV4: never; -} +/** + * 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, +) ⋮---- -// optionsV4: never; -// announcementsV4: never; +/** + * WS API Methods - similar to the REST API, but via WebSockets + */ ⋮---- -export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; -export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; +/** + * 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 + */ ⋮---- -// ==================================== -// Spot WebSocket API Request 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 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'; -} +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 WSAPISpotOrderCancelReq { - order_id: string; - currency_pair: string; - account?: string; -} +// Some commands don't require authentication. ⋮---- -export interface WSAPISpotOrderCancelIdsReq { - currency_pair: string; - id: string; - account?: string; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -export interface WSAPISpotOrderCancelCPReq { - currency_pair: string; - side?: 'buy' | 'sell'; - account?: string; -} +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- -export interface WSAPISpotOrderAmendReq { - amount?: string; - price?: string; - amend_text?: string; - order_id: string; - currency_pair: string; - account?: string; -} +// id: timeInSeconds, ⋮---- -export interface WSAPISpotOrderStatusReq { - order_id: string; - currency_pair: string; - account?: string; -} +/** + * 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. + */ ⋮---- -export interface WSAPISpotOrderListReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: string; - from?: number; - to?: number; - side?: 'buy' | 'sell'; -} +// Sign request ⋮---- -// ==================================== -// Futures WebSocket API Request Types -// ==================================== +// Store deferred promise ⋮---- -export interface WSAPIFuturesOrderPlaceReq { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - text?: string; - auto_size?: 'close_long' | 'close_short'; - stp_act?: 'cn' | 'co' | 'cb'; -} +// Enrich returned promise with request context for easier debugging ⋮---- -export interface WSAPIFuturesOrderCancelReq { - order_id: string; -} +// throw e; ⋮---- -export interface WSAPIFuturesOrderCancelCPReq { - contract: string; - side?: 'bid' | 'ask'; -} +// Send event ⋮---- -export interface WSAPIFuturesOrderAmendReq { - order_id: string; - price?: string; - size?: number; - amend_text?: string; -} +// Return deferred promise, so caller can await this call ⋮---- -export interface WSAPIFuturesOrderListReq { - contract: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: number; -} +/** + * + * Internal methods - not intended for public use + * + */ ⋮---- -export interface WSAPIFuturesOrderStatusReq { - order_id: string; -} +protected getWsUrl(wsKey: WsKey): string ⋮---- -// ==================================== -// Spot WebSocket API Response Types -// ==================================== +protected sendPingEvent(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; -} +protected sendPongEvent(wsKey: WsKey) ⋮---- -export interface WSAPISpotOrderCancelIdsRespItem { - currency_pair: string; - id: string; - succeeded: boolean; -} +// Send a protocol layer pong ⋮---- -// ==================================== -// Futures WebSocket API Response Types -// ==================================== +// 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 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; -} +protected isWsPong(msg: any): boolean ⋮---- -export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { - succeeded: boolean; -} +/** + * Parse incoming events into categories, before emitting to the user + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] ⋮---- -export interface WSAPIFuturesOrderCancelIdsRespItem { - id: string; - user_id: number; - succeeded?: boolean; - message?: string; -} +// WS API Exception ⋮---- -// ==================================== -// Request Parameter Mapping -// ==================================== +// WS API Success ⋮---- -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; -} +// 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. ⋮---- -export type WsAPITopicRequestParams = - WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- -// ==================================== -// Response Headers and Base Response -// ==================================== +// Request/reply pattern for authentication success ⋮---- -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; -} +/** + * Determines if a topic is for a private channel, using a hardcoded list of strings + */ +protected isPrivateTopicRequest( + request: WsTopicRequest, + wsKey: WsKey, +): boolean ⋮---- -/** String timestamp as ms */ +// No private announcements channels ⋮---- -/** Status of WS API call. "200" if successful, else exception is thrown */ +/** + * Not in use for gate.io + */ ⋮---- -export interface WSAPILoginResponse { - api_key: string; - uid: string; -} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket ⋮---- -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; -} +/** + * Not in use for gate.io + */ +protected getPrivateWSKeys(): WsKey[] ⋮---- -export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -export interface WSAPIResponse< - TResponseData extends object = WSAPIResponseData | object, - TChannel extends WSAPITopic = WSAPITopic, -> { - wsKey: WsKey; - header: WSAPIResponseHeader; - data: { - result: TResponseData; - }; - /** Auto-generated */ - request_id: string; -} +/** 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 ⋮---- -/** Auto-generated */ +/** + * 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 ⋮---- -// ==================================== -// Response Type Mapping -// ==================================== +// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); +// console.trace(); ⋮---- -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' - >; -} +// Events that are ready to send (usually stringified JSON) ⋮---- -// export interface WsAPIResponseMap { -// 'spot.login': WSAPIResponse; -// 'futures.login': WSAPIResponse; -// string: object; -// } - -================ -File: src/types/shared.ts -================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'futuresTestnet'; +/** + * @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[]> ⋮---- -// interfaces +// If private topic request, build auth part for request ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; -} +// No key or secret, push event as failed ⋮---- -// Used for spot and flash swap -export interface CurrencyPair { - id?: string; - base?: string; - base_name?: string; - quote?: string; - quote_name?: string; - fee?: string; - min_base_amount?: string; - min_quote_amount?: string; - max_base_amount?: string; - max_quote_amount?: string; - amount_precision?: number; - precision?: number; - trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; - sell_start?: number; - buy_start?: number; - type: string; - delisting_time?: number; - trade_url?: string; -} - -================ -File: src/index.ts -================ -// Request Types +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise ⋮---- -// Response Types +protected async getWsAuthRequestEvent(wsKey: WsKey): Promise ⋮---- -// Websockets Types +// id: timeInSeconds, ⋮---- -// Shared Types +/** + * + * @param requestEvent + * @returns A signed updated WS API request object, ready to be sent + */ +private async signWSAPIRequest( + requestEvent: WSAPIRequest, +): Promise> ================ File: src/RestClient.ts @@ -6616,6 +8942,15 @@ import { } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { CreateStpGroupReq } from './types/request/account.js'; +import { + CreateAlphaOrderReq, + CreateAlphaQuoteReq, + GetAlphaAccountBookReq, + GetAlphaCurrenciesReq, + GetAlphaOrderReq, + GetAlphaOrdersReq, + GetAlphaTickersReq, +} from './types/request/alpha.js'; import { GetLoanCollateralRecordsReq, GetLoanOrdersReq, @@ -6623,6 +8958,36 @@ import { SubmitLoanOrderReq, UpdateLoanCollateralReq, } from './types/request/collateralLoan.js'; +import { + CloseCrossExPositionReq, + CreateCrossExConvertOrderReq, + CreateCrossExConvertQuoteReq, + CreateCrossExOrderReq, + CreateCrossExTransferReq, + GetCrossExAccountBookReq, + GetCrossExAccountsReq, + GetCrossExAdlRankReq, + GetCrossExCoinDiscountRateReq, + GetCrossExHistoryMarginInterestsReq, + GetCrossExHistoryMarginPositionsReq, + GetCrossExHistoryOrdersReq, + GetCrossExHistoryPositionsReq, + GetCrossExHistoryTradesReq, + GetCrossExInterestRateReq, + GetCrossExMarginPositionLeverageReq, + GetCrossExMarginPositionsReq, + GetCrossExOpenOrdersReq, + GetCrossExPositionLeverageReq, + GetCrossExPositionsReq, + GetCrossExRiskLimitsReq, + GetCrossExSymbolsReq, + GetCrossExTransferCoinsReq, + GetCrossExTransferHistoryReq, + ModifyCrossExOrderReq, + SetCrossExMarginPositionLeverageReq, + SetCrossExPositionLeverageReq, + UpdateCrossExAccountReq, +} from './types/request/crossex.js'; import { GetDeliveryAutoOrdersReq, GetDeliveryBookReq, @@ -6715,6 +9080,16 @@ import { OptionsMMPSettingsReq, SubmitOptionsOrderReq, } from './types/request/options.js'; +import { + CancelOTCOrderReq, + CreateOTCFiatOrderReq, + CreateOTCQuoteReq, + CreateOTCStablecoinOrderReq, + GetOTCFiatOrderDetailReq, + GetOTCFiatOrderListReq, + GetOTCStablecoinOrderListReq, + MarkOTCOrderAsPaidReq, +} from './types/request/otc.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, @@ -6773,12 +9148,51 @@ import { StpGroup, StpGroupUser, } from './types/response/account.js'; +import { + AlphaAccount, + AlphaAccountBook, + AlphaCurrency, + AlphaOrder, + AlphaTicker, + CreateAlphaOrderResp, + CreateAlphaQuoteResp, +} from './types/response/alpha.js'; import { LoanCollateralRatio, LoanCollateralRecord, LoanOrder, LoanRepaymentHistoryRecord, } from './types/response/collateralloan.js'; +import { + CancelCrossExOrderResp, + CloseCrossExPositionResp, + CreateCrossExConvertQuoteResp, + CreateCrossExOrderResp, + CreateCrossExTransferResp, + CrossExAccount, + CrossExAccountBook, + CrossExAdlRank, + CrossExCoinDiscountRate, + CrossExFeeRate, + CrossExHistoryMarginInterest, + CrossExHistoryMarginPosition, + CrossExHistoryPosition, + CrossExHistoryTrade, + CrossExInterestRate, + CrossExMarginPosition, + CrossExMarginPositionLeverage, + CrossExOrder, + CrossExPosition, + CrossExPositionLeverage, + CrossExRiskLimit, + CrossExSymbol, + CrossExTransferCoin, + CrossExTransferHistory, + ModifyCrossExOrderResp, + SetCrossExMarginPositionLeverageResp, + SetCrossExPositionLeverageResp, + UpdateCrossExAccountResp, +} from './types/response/crossex.js'; import { DeliveryAccount, DeliveryBook, @@ -6878,6 +9292,17 @@ import { OptionsUserSettlement, SubmitOptionsOrderResp, } from './types/response/options.js'; +import { + CancelOTCOrderResp, + CreateOTCFiatOrderResp, + CreateOTCQuoteResp, + CreateOTCStablecoinOrderResp, + GetOTCFiatOrderDetailResp, + GetOTCFiatOrderListResp, + GetOTCStablecoinOrderListResp, + GetOTCUserDefaultBankResp, + MarkOTCOrderAsPaidResp, +} from './types/response/otc.js'; import { AgencyCommissionHistoryRecord, AgencyTransactionHistoryRecord, @@ -7261,6 +9686,13 @@ getSmallBalanceHistory( */ getPushOrders(params?: ListPushOrdersReq): Promise ⋮---- +/** + * Retrieve the list of low-liquidity or low-cap tokens + * + * @returns Promise + */ +getLowCapExchangeList(): Promise +⋮---- /**========================================================================================================================== * SUBACCOUNT * ========================================================================================================================== @@ -7314,6 +9746,8 @@ getSubAccountApiKeys(params: { /** * Update API key of the sub-account * + * Note: This interface cannot modify the mode account type attribute + * * @param params Parameters for updating API key of the sub-account * @returns Promise */ @@ -7378,6 +9812,9 @@ getSubAccountMode(): Promise * Get unified account information * * The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account. + * + * For specific formulas, please refer to Margin Formula + * * @param params Parameters for retrieving unified account information * @returns Promise */ @@ -7873,9 +10310,16 @@ cancelSpotOrder(params: DeleteSpotOrderReq): Promise /** * List personal trading history * - * Spot, portfolio and margin trades are queried by default. If cross margin trades are needed, account must be set to cross_margin. + * By default query of transaction records for spot, unified account and warehouse-by-site leverage accounts. * - * You can also set from and/or to to query by time range. If you don't specify from and/or to parameters, only the last 7 days of data will be returned. The range of from and to is not allowed to exceed 30 days. Time range parameters are handled as order finish time. + * The history within a specified time range can be queried by specifying from or (and) to. + * + * If no time parameters are specified, only data for the last 7 days can be obtained. + * If only any parameter of from or to is specified, only 7-day data from the start (or end) of the specified time is returned. + * The range not allowed to exceed 30 days. + * The parameters of the time range filter are processed according to the order end time. + * + * The maximum number of pages when searching data using limit&page paging function is 100,0, that is, limit * (page - 1) <= 100,0. * * @param params Parameters for listing personal trading history * @returns Promise @@ -8601,6 +11045,8 @@ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise /** * Query futures account * + * Query account information for classic future account and unified account + * * @param params Parameters for querying futures account * @returns Promise */ @@ -8633,6 +11079,8 @@ getFuturesPositions( /** * Get single position * + * Clarifies dual-position query method when holding both long and short positions in the same contract market + * * @param params Parameters for retrieving a single position * @returns Promise */ @@ -8644,6 +11092,8 @@ getFuturesPosition(params: { /** * Update position margin * + * Under the new risk limit rules, the position limit is related to the leverage you set; a lower leverage will result in a higher position limit. Please use the leverage adjustment api to adjust the position limit. + * * @param params Parameters for updating position margin * @returns Promise */ @@ -8656,6 +11106,17 @@ updateFuturesMargin(params: { /** * Update position leverage * + * Position Mode Switching Rules: + * - leverage ≠ 0: Isolated Margin Mode (Regardless of whether cross_leverage_limit is filled, this parameter will be ignored) + * - leverage = 0: Cross Margin Mode (Use cross_leverage_limit to set the leverage multiple) + * + * Examples: + * - Set isolated margin with 10x leverage: leverage=10 + * - Set cross margin with 10x leverage: leverage=0&cross_leverage_limit=10 + * - leverage=5&cross_leverage_limit=10 → Result: Isolated margin with 5x leverage (cross_leverage_limit is ignored) + * + * Warning: Incorrect settings may cause unexpected position mode switching, affecting risk management. + * * @param params Parameters for updating position leverage * @returns Promise */ @@ -8664,8 +11125,11 @@ updateFuturesLeverage(params: { contract: string; leverage: string; cross_leverage_limit?: string; + pid?: number; // Product ID }): Promise ⋮---- +pid?: number; // Product ID +⋮---- /** * Update position by store mode * @@ -8740,6 +11204,14 @@ updateDualModePositionLeverage( * @param params Parameters for updating position risk limit in dual mode * @returns Promise */ +/** + * Update position risk limit in dual mode + * + * See risk limit rules for more information + * + * @param params Parameters for updating position risk limit in dual mode + * @returns Promise + */ updateDualModePositionRiskLimit(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; @@ -9498,6 +11970,8 @@ getOptionsTrades(params: GetOptionsTradesReq): Promise /** * List options account * + * Indicates support for querying both classic options accounts and unified accounts + * * @returns Promise */ getOptionsAccount(): Promise @@ -10166,1083 +12640,950 @@ getStpGroupUsers(params: */ addUsersToStpGroup(params: { stp_id: number; - body: number[]; -}): Promise -⋮---- -/** - * Delete the user in the STP group - * - * @param params Parameters for deleting users from the STP group - * @returns Promise - */ -deleteUserFromStpGroup(params: { - stp_id: number; - user_id: number; -}): Promise -⋮---- -/** - * Set GT deduction - * - * Enable or disable GT deduction for the current account. - * - * @param params Parameters for setting GT deduction - * @returns Promise - */ -setGTDeduction(params: -⋮---- -/** - * Query GT deduction configuration - * - * Query the current GT deduction configuration for the account. - * - * @returns Promise<{ enabled: boolean }> - */ -getGTDeduction(): Promise< -⋮---- -/** - * Query all main account API key information - * - * @returns Promise - */ -getAccountMainKeys(): Promise -⋮---- -/**========================================================================================================================== - * REBATES - * ========================================================================================================================== - */ -⋮---- -/** - * The agency obtains the transaction history of the recommended user. - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving transaction history - * @returns Promise - */ -getAgencyTransactionHistory( - params: GetAgencyTransactionHistoryReq, -): Promise< -⋮---- -/** - * The agency obtains the commission history of the recommended user. - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving commission history - * @returns Promise - */ -getAgencyCommissionHistory( - params: GetAgencyCommissionHistoryReq, -): Promise< -⋮---- -/** - * Partner obtains transaction records of recommended users - * - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving transaction records - * @returns Promise - */ -getPartnerTransactionHistory(params?: PartnerTransactionReq): Promise< -⋮---- -/** - * Partner obtains commission records of recommended users - * - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving commission records - * @returns Promise - */ -getPartnerCommissionHistory(params?: PartnerTransactionReq): Promise< -⋮---- -/** - * Partner subordinate list - * - * Including sub-agents, direct customers, indirect customers - * - * @param params Parameters for retrieving partner subordinate list - * @returns Promise<{ - * total: number; - * list: { - * user_id: number; - * user_join_time: number; - * type: number; - * desc: string; - * }[]; - * }> - */ -getPartnerSubordinateList(params?: GetPartnerSubordinateListReq): Promise< -⋮---- -/** - * The broker obtains the user's commission rebate records. - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving commission rebate records - * @returns Promise - */ -getBrokerCommissionHistory( - params: GetBrokerCommissionHistoryReq, -): Promise< -⋮---- -/** - * The broker obtains the user's trading history. - * Record time range cannot exceed 30 days. - * - * @param params Parameters for retrieving trading history - * @returns Promise - */ -getBrokerTransactionHistory( - params: GetBrokerTransactionHistoryReq, -): Promise< -⋮---- -/** - * User retrieves rebate information. - */ -getUserRebateInfo(): Promise< -⋮---- -/** - * Query user-subordinate relationship - * - * Checks whether specified users are in the system and their relationship status - */ -getUserSubordinateRelationships(params: { - user_id_list: string; // Comma-separated list of user IDs (max 100) -}): Promise< -⋮---- -user_id_list: string; // Comma-separated list of user IDs (max 100) - -================ -File: src/WebsocketAPIClient.ts -================ -import { DefaultLogger } from './lib/logger.js'; -import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; -import { WSClientConfigurableOptions } from './types/websockets/client.js'; -import { - WSAPIFuturesOrder, - WSAPIFuturesOrderAmendReq, - WSAPIFuturesOrderBatchPlaceRespItem, - WSAPIFuturesOrderCancelCPReq, - WSAPIFuturesOrderCancelIdsRespItem, - WSAPIFuturesOrderCancelReq, - WSAPIFuturesOrderListReq, - WSAPIFuturesOrderPlaceReq, - WSAPIFuturesOrderStatusReq, - WSAPIResponse, - WSAPISpotOrder, - WSAPISpotOrderAmendReq, - WSAPISpotOrderCancelCPReq, - WSAPISpotOrderCancelIdsReq, - WSAPISpotOrderCancelIdsRespItem, - WSAPISpotOrderCancelReq, - WSAPISpotOrderListReq, - WSAPISpotOrderPlaceReq, - WSAPISpotOrderStatusReq, - WSAPIWsKey, -} from './types/websockets/wsAPI.js'; -import { WebsocketClient } from './WebsocketClient.js'; -⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; -} -⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ -⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should - * be used to transmit that message. This is only useful if you wish to use an alternative wss - * domain that is supported by the SDK. - * - * Note: To use testnet, don't set the wsKey - use `testnet: true` in - * the constructor instead. - * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. - * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 - */ -export class WebsocketAPIClient -⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) -⋮---- -public getWSClient(): WebsocketClient -⋮---- -public setTimeOffsetMs(newOffset: number): void -⋮---- -/* - * - * SPOT - Trading requests - * - */ + body: number[]; +}): Promise ⋮---- /** - * Submit a spot order + * Delete the user in the STP group + * + * @param params Parameters for deleting users from the STP group + * @returns Promise */ -submitNewSpotOrder( - params: WSAPISpotOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +deleteUserFromStpGroup(params: { + stp_id: number; + user_id: number; +}): Promise ⋮---- /** - * Cancel a spot order + * Set GT deduction + * + * Enable or disable GT deduction for the current account. + * + * @param params Parameters for setting GT deduction + * @returns Promise */ -cancelSpotOrder( - params: WSAPISpotOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +setGTDeduction(params: ⋮---- /** - * Cancel all spot orders with the given id list + * Query GT deduction configuration + * + * Query the current GT deduction configuration for the account. + * + * @returns Promise<{ enabled: boolean }> */ -cancelSpotOrderById( - params: WSAPISpotOrderCancelIdsReq[], - wsKey?: WSAPIWsKey, -): Promise> +getGTDeduction(): Promise< ⋮---- /** - * Cancel a spot order for a given symbol + * Query all main account API key information + * + * @returns Promise */ -cancelSpotOrderForSymbol( - params: WSAPISpotOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +getAccountMainKeys(): Promise ⋮---- -/** - * Update a spot order +/**========================================================================================================================== + * REBATES + * ========================================================================================================================== */ -updateSpotOrder( - params: WSAPISpotOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> ⋮---- /** - * Get the status of a spot order + * The agency obtains the transaction history of the recommended user. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving transaction history + * @returns Promise */ -getSpotOrderStatus( - params: WSAPISpotOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +getAgencyTransactionHistory( + params: GetAgencyTransactionHistoryReq, +): Promise< ⋮---- /** - * Get all spot orders + * The agency obtains the commission history of the recommended user. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving commission history + * @returns Promise */ -getSpotOrders( - params: WSAPISpotOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> +getAgencyCommissionHistory( + params: GetAgencyCommissionHistoryReq, +): Promise< ⋮---- -/* +/** + * Partner obtains transaction records of recommended users * - * Futures - Trading requests + * Record time range cannot exceed 30 days. * + * @param params Parameters for retrieving transaction records + * @returns Promise */ +getPartnerTransactionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** - * Submit a futures order. + * Partner obtains commission records of recommended users * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving commission records + * @returns Promise */ -submitNewFuturesOrder( - params: WSAPIFuturesOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +getPartnerCommissionHistory(params?: PartnerTransactionReq): Promise< ⋮---- /** - * Submit a batch of futures orders + * Partner subordinate list * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * Including sub-agents, direct customers, indirect customers + * + * @param params Parameters for retrieving partner subordinate list + * @returns Promise<{ + * total: number; + * list: { + * user_id: number; + * user_join_time: number; + * type: number; + * desc: string; + * }[]; + * }> */ -submitNewFuturesBatchOrder( - params: WSAPIFuturesOrderPlaceReq[], - wsKey?: WSAPIWsKey, -): Promise> +getPartnerSubordinateList(params?: GetPartnerSubordinateListReq): Promise< ⋮---- /** - * Cancel a futures order + * The broker obtains the user's commission rebate records. + * Record time range cannot exceed 30 days. * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * @param params Parameters for retrieving commission rebate records + * @returns Promise */ -cancelFuturesOrder( - params: WSAPIFuturesOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +getBrokerCommissionHistory( + params: GetBrokerCommissionHistoryReq, +): Promise< ⋮---- /** - * Cancel futures orders by id list + * The broker obtains the user's trading history. + * Record time range cannot exceed 30 days. * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * @param params Parameters for retrieving trading history + * @returns Promise */ -cancelFuturesOrderById( - params: string[], - wsKey?: WSAPIWsKey, -): Promise> +getBrokerTransactionHistory( + params: GetBrokerTransactionHistoryReq, +): Promise< ⋮---- /** - * Cancel all open futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * User retrieves rebate information. */ -cancelFuturesAllOpenOrders( - params: WSAPIFuturesOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +getUserRebateInfo(): Promise< ⋮---- /** - * Update a futures order + * Query user-subordinate relationship * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * Checks whether specified users are in the system and their relationship status */ -updateFuturesOrder( - params: WSAPIFuturesOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +getUserSubordinateRelationships(params: { + user_id_list: string; // Comma-separated list of user IDs (max 100) +}): Promise< ⋮---- -/** - * Get all futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection +user_id_list: string; // Comma-separated list of user IDs (max 100) +⋮---- +/**========================================================================================================================== + * OTC + * ========================================================================================================================== */ -getFuturesOrders( - params: WSAPIFuturesOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> ⋮---- /** - * Get futures order status + * Fiat and stablecoin quote * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + * Create fiat and stablecoin quotes, supporting both PAY and GET directions + * + * @param params Quote parameters + * @returns Promise with quote details including rate, amounts, and quote_token */ -getFuturesOrderStatus( - params: WSAPIFuturesOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +createOTCQuote(params: CreateOTCQuoteReq): Promise ⋮---- /** + * Create fiat order * + * Create a fiat order, supporting BUY for on-ramp and SELL for off-ramp * + * @param params Fiat order parameters + * @returns Promise with order creation confirmation + */ +createOTCFiatOrder( + params: CreateOTCFiatOrderReq, +): Promise +⋮---- +/** + * Create stablecoin order * + * Create stablecoin order * + * @param params Stablecoin order parameters + * @returns Promise with order creation confirmation + */ +createOTCStablecoinOrder( + params: CreateOTCStablecoinOrderReq, +): Promise +⋮---- +/** + * Get user's default bank account information * + * Get user's default bank account information for order placement * + * @returns Promise with default bank account details + */ +getOTCUserDefaultBank(): Promise +⋮---- +/** + * Mark fiat order as paid * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * + * Mark fiat order as paid * + * @param params Parameters with order_id + * @returns Promise with confirmation */ -⋮---- -private setupDefaultEventListeners() +markOTCOrderAsPaid( + params: MarkOTCOrderAsPaidReq, +): Promise ⋮---- /** - * General event handlers for monitoring the WebsocketClient - */ -⋮---- -// Blind JSON.stringify can fail on circular references -⋮---- -// JSON.stringify({ ...data, target: 'WebSocket' }), - -================ -File: src/WebsocketClient.ts -================ -import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; -import { neverGuard } from './lib/misc-util.js'; -import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; -import { - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './lib/webCryptoAPI.js'; -import { - getPrivateFuturesTopics, - getPrivateOptionsTopics, - getPrivateSpotTopics, - getPromiseRefForWSAPIRequest, - WS_BASE_URL_MAP, - WS_KEY_MAP, - WsKey, - WsMarket, - WsTopicRequest, -} from './lib/websocket/websocket-util.js'; -import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; -import { - WSAPIRequest, - WsOperation, - WsRequestOperationGate, - WsRequestPing, -} from './types/websockets/requests.js'; -import { - WsAPITopicRequestParamMap, - WsAPITopicResponseMap, - WSAPIWsKey, - WsAPIWsKeyTopicMap, -} from './types/websockets/wsAPI.js'; -⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} -⋮---- -/** If true, will skip auth requirement for WS API connection */ + * Fiat order cancellation + * + * Cancel fiat order + * + * @param params Parameters with order_id + * @returns Promise with cancellation confirmation + */ +cancelOTCOrder(params: CancelOTCOrderReq): Promise ⋮---- /** - * WS topics are always a string for gate. Some exchanges use complex objects - */ -export type WsTopic = string; -⋮---- -export class WebsocketClient extends BaseWebsocketClient + * Fiat order list + * + * Query the fiat order list with filters such as type, currency, time range, and status + * + * @param params Filter parameters for fiat order list + * @returns Promise with paginated fiat order list + */ +getOTCFiatOrderList( + params?: GetOTCFiatOrderListReq, +): Promise ⋮---- /** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. + * Stablecoin order list * - * Returns array of promises that individually resolve when each connection is successfully opened. + * Query stablecoin order list with filtering by currency, time range, status, etc. + * + * @param params Filter parameters for stablecoin order list + * @returns Promise with paginated stablecoin order list */ -public connectAll(): Promise[] +getOTCStablecoinOrderList( + params?: GetOTCStablecoinOrderListReq, +): Promise ⋮---- /** - * Ensures the WS API connection is active and ready. + * Fiat order details * - * 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). + * Query fiat order details + * + * @param params Parameters with order_id + * @returns Promise with fiat order details */ -public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise +getOTCFiatOrderDetail( + params: GetOTCFiatOrderDetailReq, +): Promise ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +/**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ ⋮---- /** - * 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}. + * Query Trading Pair Information * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. + * Query trading pair information for cross-exchange trading * - * Call `unsubscribe(topics)` to remove topics + * @param params Optional parameters to filter symbols + * @returns Promise with array of symbol information */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +getCrossExSymbols(params?: GetCrossExSymbolsReq): Promise ⋮---- /** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * Query Risk Limit Information * - * - 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. + * Query risk limit information for futures/margin trading pairs + * + * @param params Parameters with required symbols + * @returns Promise with array of risk limit information */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +getCrossExRiskLimits( + params: GetCrossExRiskLimitsReq, +): Promise ⋮---- /** - * WS API Methods - similar to the REST API, but via WebSockets + * Query Supported Transfer Currencies + * + * Query supported transfer currencies for cross-exchange + * + * @param params Optional currency filter + * @returns Promise with array of transfer coin information */ +getCrossExTransferCoins( + params?: GetCrossExTransferCoinsReq, +): Promise ⋮---- /** - * Send a Websocket API event on a connection. Returns a promise that resolves on reply. + * Fund Transfer * - * 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. + * Transfer funds between accounts. Rate limit: 10 requests per 10 seconds * - * 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). + * @param params Transfer parameters + * @returns Promise with transfer confirmation + */ +createCrossExTransfer( + params: CreateCrossExTransferReq, +): Promise +⋮---- +/** + * Query Fund Transfer History * - * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. + * Query fund transfer history. Rate Limit: 200 requests per 10 seconds * - * @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 + * @param params Optional filter parameters + * @returns Promise with array of transfer history records */ -⋮---- -// This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends - WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], - TWSAPIResponse extends - | WsAPITopicResponseMap[TWSChannel] - | object = WsAPITopicResponseMap[TWSChannel], - >( - wsKey: TWSKey, - channel: TWSChannel, - params?: TWSParams extends void | never ? undefined : TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; -⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, - TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends - WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], - TWSAPIResponse = object, - >( - wsKey: TWSKey, - channel: TWSChannel, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, -): Promise -⋮---- -// Some commands don't require authentication. -⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); -⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); -⋮---- -// id: timeInSeconds, +getCrossExTransferHistory( + params?: GetCrossExTransferHistoryReq, +): Promise ⋮---- /** - * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated - * can introduce a small delay before the actual request is sent, if not connected before that request is - * made. This can lead to a curious race condition, where the request timestamp is before - * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. - * - * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, - * it offsets that timestamp by the delay. - */ -⋮---- -// Sign request -⋮---- -// Store deferred promise -⋮---- -// Enrich returned promise with request context for easier debugging -⋮---- -// throw e; -⋮---- -// Send event -⋮---- -// Return deferred promise, so caller can await this call + * Create an order + * + * Create an order for cross-exchange trading. Rate Limit: 100 requests per 10 seconds + * + * @param params Order parameters + * @returns Promise with order creation response + */ +createCrossExOrder( + params: CreateCrossExOrderReq, +): Promise ⋮---- /** + * Cancel Order * - * Internal methods - not intended for public use + * Cancel an order. Rate Limit: 100 requests per 10 seconds * + * @param order_id Order ID or Text for Cancel Order + * @returns Promise with cancellation confirmation */ -⋮---- -protected getWsUrl(wsKey: WsKey): string -⋮---- -protected sendPingEvent(wsKey: WsKey) -⋮---- -protected sendPongEvent(wsKey: WsKey) -⋮---- -// Send a protocol layer pong -⋮---- -// NOT IN USE for gate.io, pings for gate are protocol layer pings -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected isWsPing(_msg: any): boolean -⋮---- -protected isWsPong(msg: any): boolean +cancelCrossExOrder(order_id: string): Promise ⋮---- /** - * Parse incoming events into categories, before emitting to the user + * Modify Order + * + * Modify an existing order. Rate Limit: 100 requests per 10 seconds + * + * @param order_id Order ID or Text for Modify Order + * @param params Modification parameters + * @returns Promise with modification confirmation */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] -⋮---- -// WS API Exception -⋮---- -// WS API Success +modifyCrossExOrder( + order_id: string, + params: ModifyCrossExOrderReq, +): Promise ⋮---- -// Most events use "event: 'update'" for topic updates -// The legacy "futures.order_book" topic uses "all" for this field -// 'futures.obu' is used for the orderbook v2 event. Oddly in a different structure than the other topics. -⋮---- -// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) -⋮---- -// Request/reply pattern for authentication success +/** + * Query order details + * + * Query order details by order ID or custom text. Rate Limit: 200 requests per 10 seconds + * + * @param order_id Order ID or custom text + * @returns Promise with order details + */ +getCrossExOrder(order_id: string): Promise ⋮---- /** - * Determines if a topic is for a private channel, using a hardcoded list of strings + * Flash Swap Inquiry + * + * Create a flash swap quote. Rate Limit: 100 requests per day + * + * @param params Quote parameters + * @returns Promise with quote details */ -protected isPrivateTopicRequest( - request: WsTopicRequest, - wsKey: WsKey, -): boolean +createCrossExConvertQuote( + params: CreateCrossExConvertQuoteReq, +): Promise ⋮---- -// No private announcements channels +/** + * Flash Swap Transaction + * + * Execute a flash swap transaction. Rate limit: 10 requests per 10 seconds + * + * @param params Parameters with quote_id + * @returns Promise with transaction confirmation + */ +createCrossExConvertOrder(params: CreateCrossExConvertOrderReq): Promise< ⋮---- /** - * Not in use for gate.io + * Modify Account Contract Position Mode and Account Mode + * + * Modify account settings. Rate Limit: 100 requests per 60 seconds + * + * @param params Account modification parameters + * @returns Promise with update confirmation */ +updateCrossExAccount( + params: UpdateCrossExAccountReq, +): Promise ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket +/** + * Query Account Assets + * + * Query account assets and balances. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional exchange_type filter + * @returns Promise with account information + */ +getCrossExAccounts(params?: GetCrossExAccountsReq): Promise ⋮---- /** - * Not in use for gate.io + * Modify Contract Trading Pair Leverage Multiplier + * + * Modify leverage for contract trading pair. Rate Limit: 100 requests per 10 seconds + * + * @param params Leverage modification parameters + * @returns Promise with leverage update confirmation */ -protected getPrivateWSKeys(): WsKey[] +setCrossExPositionLeverage( + params: SetCrossExPositionLeverageReq, +): Promise ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +/** + * Query Contract Trading Pair Leverage Multiplier + * + * Query leverage for contract trading pairs. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional symbols filter + * @returns Promise with array of leverage information + */ +getCrossExPositionLeverage( + params?: GetCrossExPositionLeverageReq, +): Promise ⋮---- -/** 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 +/** + * Modify Leveraged Trading Pair Leverage Multiplier + * + * Modify leverage for margin trading pair. Rate Limit: 100 requests per 10 seconds + * + * @param params Leverage modification parameters + * @returns Promise with leverage update confirmation + */ +setCrossExMarginPositionLeverage( + params: SetCrossExMarginPositionLeverageReq, +): Promise ⋮---- /** - * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) + * Query Leveraged Trading Pair Leverage Multiplier + * + * Query leverage for margin trading pairs. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional symbols filter + * @returns Promise with array of leverage information */ -protected async getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: WsKey, - operation: WsOperation, -): Promise +getCrossExMarginPositionLeverage( + params?: GetCrossExMarginPositionLeverageReq, +): Promise ⋮---- -// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); -// console.trace(); +/** + * Full Close Position + * + * Fully close a position. Rate Limit: 100 requests per day + * + * @param params Position close parameters + * @returns Promise with close position confirmation + */ +closeCrossExPosition( + params: CloseCrossExPositionReq, +): Promise ⋮---- -// Events that are ready to send (usually stringified JSON) +/** + * Query margin asset interest rates + * + * Query interest rates for margin assets. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of interest rates + */ +getCrossExInterestRate( + params?: GetCrossExInterestRateReq, +): Promise ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + * Query User Fee Rates + * + * Query user fee rates. Rate Limit: 200 requests per 10 seconds + * + * @returns Promise with fee rate information */ -private async getWsRequestEvents( - market: WsMarket, - operation: WsOperation, - requests: WsTopicRequest[], - wsKey: WsKey, -): Promise[]> +getCrossExFeeRate(): Promise ⋮---- -// If private topic request, build auth part for request +/** + * Query Contract Positions + * + * Query contract positions. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of positions + */ +getCrossExPositions( + params?: GetCrossExPositionsReq, +): Promise ⋮---- -// No key or secret, push event as failed +/** + * Query Leveraged Positions + * + * Query margin/leveraged positions. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of margin positions + */ +getCrossExMarginPositions( + params?: GetCrossExMarginPositionsReq, +): Promise ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +/** + * Query ADL Position Reduction Ranking + * + * Query ADL position reduction ranking. Rate Limit: 200 requests per 10 seconds + * + * @param params Parameters with required symbol + * @returns Promise with array of ADL rankings + */ +getCrossExAdlRank(params: GetCrossExAdlRankReq): Promise ⋮---- -protected async getWsAuthRequestEvent(wsKey: WsKey): Promise +/** + * Query All Current Open Orders + * + * Query all current open orders. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of open orders + */ +getCrossExOpenOrders( + params?: GetCrossExOpenOrdersReq, +): Promise ⋮---- -// id: timeInSeconds, +/** + * Query order history + * + * Query historical orders. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical orders + */ +getCrossExHistoryOrders( + params?: GetCrossExHistoryOrdersReq, +): Promise ⋮---- /** + * Query Contract Position History * - * @param requestEvent - * @returns A signed updated WS API request object, ready to be sent + * Query contract position history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical positions */ -private async signWSAPIRequest( - requestEvent: WSAPIRequest, -): Promise> - -================ -File: .eslintrc.cjs -================ -// 'no-unused-vars': ['warn'], - -================ -File: .gitignore -================ -!.gitkeep -.DS_STORE -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json -pids -*.pid -*.seed -*.pid.lock -node_modules/ -.npm -.eslintcache -.node_repl_history -*.tgz -.yarn-integrity -.env -.env.test -.cache -bundleReport.html -.history/ -dist -coverage -localtest.sh -repomix.sh - -ws-private-spot-wsapi-performance.ts -ws-private-perp-futures-wsapi-readonly.ts -privatetest.ts - -privaterepotracker -restClientRegex.ts - -testfile.ts - -================ -File: .nvmrc -================ -v22.17.0 - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} - -================ -File: jest.config.ts -================ +getCrossExHistoryPositions( + params?: GetCrossExHistoryPositionsReq, +): Promise +⋮---- /** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ + * Query Leveraged Position History + * + * Query margin position history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical margin positions + */ +getCrossExHistoryMarginPositions( + params?: GetCrossExHistoryMarginPositionsReq, +): Promise ⋮---- -import type { Config } from 'jest'; +/** + * Query Leveraged Interest Deduction History + * + * Query margin interest deduction history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of interest deduction records + */ +getCrossExHistoryMarginInterests( + params?: GetCrossExHistoryMarginInterestsReq, +): Promise ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +/** + * Query filled history + * + * Query trade execution history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of trade records + */ +getCrossExHistoryTrades( + params?: GetCrossExHistoryTradesReq, +): Promise ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +/** + * Query Account Asset Change History + * + * Query account balance change history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of account book records + */ +getCrossExAccountBook( + params?: GetCrossExAccountBookReq, +): Promise ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +/** + * Query currency discount rate + * + * Query currency discount rate (for margin currency in isolated exchange mode). Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of coin discount rates + */ +getCrossExCoinDiscountRate( + params?: GetCrossExCoinDiscountRateReq, +): Promise ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ ⋮---- -// Indicates whether the coverage information should be collected while executing the test +/** + * Query position assets + * + * Query alpha account position assets + * + * @returns Promise with array of account balances + */ +getAlphaAccounts(): Promise ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +/** + * Query asset transactions + * + * Query alpha account transaction history + * + * @param params Parameters with required from timestamp + * @returns Promise with array of transaction records + */ +getAlphaAccountBook( + params: GetAlphaAccountBookReq, +): Promise ⋮---- -// The directory where Jest should output its coverage files +/** + * Alpha Quote API + * + * Get a quote for alpha trading. Quote is valid for 1 minute. Rate-limited at 10 requests per second per user. + * + * @param params Quote parameters + * @returns Promise with quote details + */ +createAlphaQuote(params: CreateAlphaQuoteReq): Promise ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +/** + * Alpha Order API + * + * Create an alpha order. Rate-limited at 5 requests per second per user. + * + * @param params Order parameters including quote_id + * @returns Promise with order details + */ +createAlphaOrder(params: CreateAlphaOrderReq): Promise ⋮---- -// Indicates which provider should be used to instrument code for coverage +/** + * Alpha Order List API + * + * Query alpha order list with filters + * + * @param params Filter parameters + * @returns Promise with array of orders + */ +getAlphaOrders(params: GetAlphaOrdersReq): Promise ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +/** + * Alpha Single Order Query API + * + * Query a single alpha order by order ID + * + * @param params Parameters with order_id + * @returns Promise with order details + */ +getAlphaOrder(params: GetAlphaOrderReq): Promise ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +/** + * Query currency information + * + * Query alpha currency information. When currency is provided, returns specific currency info; otherwise returns paginated list. + * + * @param params Optional filter parameters + * @returns Promise with array of currency information + */ +getAlphaCurrencies(params?: GetAlphaCurrenciesReq): Promise ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +/** + * Query currency ticker + * + * Query alpha currency ticker. When currency is provided, returns specific ticker; otherwise returns paginated list. + * + * @param params Optional filter parameters + * @returns Promise with array of ticker information + */ +getAlphaTickers(params?: GetAlphaTickersReq): Promise + +================ +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'; ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +/** + * Used to switch how authentication/requests work under the hood + */ ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; + recvWindow: number; +} ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; +} ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +type SignMethod = 'gateV4'; ⋮---- -// 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 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; +}; ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ ⋮---- -// An array of file extensions your modules use +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, ⋮---- -// modulePaths: ['src'], +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void ⋮---- -// 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: {}, +export abstract class BaseRestClient ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- -// Activates notifications for test results -// notify: false, +/** + * 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 = {}, +) ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +/** Throw errors if any request params are empty */ ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +/** in ms == 5 minutes by default */ ⋮---- -// Run tests from one or more projects -// projects: undefined, +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +// 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. ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties ⋮---- -// A path to a custom resolver -// resolver: undefined, +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +protected get(endpoint: string, params?: object) ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +// GET only supports params in the query string ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +protected getPrivate(endpoint: string, params?: object) ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +// GET only supports params in the query string ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// The glob patterns Jest uses to detect test files +/** + * @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 ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], +// Build a request and handle signature process ⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +// Dispatch request ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +// Throw API rejections by parsing the response code from the body ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +// Something happened in setting up the request that triggered an error ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +// request made but no response received ⋮---- -// 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, +// The request was made and the server responded with a status code +// that falls out of the range of 2xx ⋮---- -// Indicates whether each individual test should be reported during the run -// verbose: undefined, -verbose: true, // report individual test +// console.error('err: ', response?.data); ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +// Prevent credentials from leaking into error messages ⋮---- -// Whether to use watchman for file crawling -// watchman: true, - -================ -File: LICENSE.md -================ -Copyright 2022 Tiago Siebler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -================ -File: package.json -================ -{ - "name": "gateio-api", - "version": "1.3.1", - "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", - "scripts": { - "clean": "rm -rf dist/*", - "build": "rm -fr dist/* && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", - "test": "jest --passWithNoTests", - "lint": "eslint src" - }, - "main": "dist/cjs/index.js", - "module": "dist/mjs/index.js", - "types": "dist/mjs/index.d.ts", - "exports": { - ".": { - "import": "./dist/mjs/index.js", - "require": "./dist/cjs/index.js", - "types": "./dist/mjs/index.d.ts" - } - }, - "type": "module", - "files": [ - "dist/*", - "llms.txt" - ], - "author": "Tiago Siebler (https://github.com/tiagosiebler)", - "contributors": [ - "Jerko J (https://github.com/JJ-Cro)" - ], - "dependencies": { - "axios": "^1.12.2", - "isomorphic-ws": "^4.0.1", - "ws": "^8.18.3" - }, - "devDependencies": { - "@types/jest": "^29.5.12", - "@types/node": "^22.10.2", - "@types/ws": "^8.5.10", - "@typescript-eslint/eslint-plugin": "^8.18.0", - "@typescript-eslint/parser": "^8.18.0", - "eslint": "^8.29.0", - "eslint-config-prettier": "^9.1.0", - "eslint-plugin-prettier": "^5.1.3", - "eslint-plugin-require-extensions": "^0.1.3", - "eslint-plugin-simple-import-sort": "^12.1.1", - "jest": "^29.7.0", - "ts-jest": "^29.1.2", - "ts-node": "^10.9.2", - "typescript": "^5.7.3" - }, - "keywords": [ - "Gate", - "Gate.io", - "Gate.com", - "Gate api", - "Gate.io api", - "Gate.com api", - "Gate nodejs", - "Gate javascript", - "Gate javascript websocket api", - "Gate typescript", - "Gate js", - "Gate ts", - "Gate api node", - "Gate sdk javascript", - "algo trading", - "api", - "websocket", - "rest", - "rest api", - "ccxt", - "trading bots", - "nodejs", - "node", - "trading", - "cryptocurrency", - "bitcoin", - "best" - ], - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/tiagosiebler" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/tiagosiebler/gateio-api" - }, - "bugs": { - "url": "https://github.com/tiagosiebler/gateio-api/issues" - }, - "homepage": "https://github.com/tiagosiebler/gateio-api#readme" -} - -================ -File: postBuild.sh -================ -#!/bin/bash -# -# Add package.json files to cjs/mjs subtrees -# - -cat >dist/cjs/package.json <dist/mjs/package.json <( + 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: README.md @@ -11275,9 +13616,12 @@ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST AP - Strongly typed requests and responses. - Automated end-to-end tests ensuring reliability. - Actively maintained with a modern, promise-driven interface. -- Gate.com REST APIs for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures, Options & Announcements APIs. +- 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. @@ -11285,8 +13629,8 @@ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST AP - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - Automatically handle listenKey persistence and expiration/refresh. - Emit `reconnected` event when dropped connection is restored. - - Support for Gate.com Spot, Margin, Perpetual Futures, Delivery Futures & Options. -- WebSocket API for Gate.com Spot, Margin, Perpetual Futures & Delivery Futures. + - 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: @@ -11312,6 +13656,8 @@ Updated & performant JavaScript & Node.js SDK for the Gate.com (gate.io) REST AP - [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) @@ -11338,22 +13684,24 @@ Refer to the [examples](./examples) folder for implementation demos, including: -## Related projects - -Check out my related JavaScript/TypeScript/Node.js projects: - -- Try my REST API & WebSocket SDKs: - - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) +## Related Projects + +Check out our JavaScript/TypeScript/Node.js SDKs & Projects: + +- Visit our website: [https://Siebly.io](https://siebly.io/?ref=gh) +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) + - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) + - [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/tiagosiebler/awesome-crypto-examples) @@ -11369,6 +13717,9 @@ Most methods accept JS objects. These can be populated using parameters specifie - [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) @@ -11390,7 +13741,7 @@ Create API credentials on Gate.com's website: ## REST API -The SDK provides a unified `RestClient` for all Gate.com trading products including Spot, Margin, Perpetual Futures, Delivery Futures, and Options. This single client handles all REST API operations across all trading markets. +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`: @@ -11405,6 +13756,7 @@ const client = new RestClient({ apiSecret: PRIVATE_KEY, }); +// Spot Trading Example client .getSpotTicker() .then((result) => { @@ -11416,8 +13768,8 @@ client client .getSpotOrders({ - currency_pair: 'BTC_USDT', // Specify the currency pair - status: 'open', // Specify the status of the orders to fetch + currency_pair: 'BTC_USDT', + status: 'open', }) .then((result) => { console.log('getSpotOrders result: ', result); @@ -11425,6 +13777,42 @@ client .catch((err) => { console.error('getSpotOrders error: ', err); }); + +// CrossEx Trading Example - Trade across multiple exchanges +client + .getCrossExSymbols() + .then((result) => { + console.log('CrossEx symbols: ', result); + }) + .catch((err) => { + console.error('CrossEx error: ', err); + }); + +// Alpha Trading Example - Trade meme tokens and new listings +client + .getAlphaCurrencies() + .then((result) => { + console.log('Alpha currencies: ', result); + }) + .catch((err) => { + console.error('Alpha error: ', err); + }); + +// OTC Trading Example - Fiat and stablecoin trading +client + .createOTCQuote({ + side: 'BUY', + pay_coin: 'USDT', + get_coin: 'USD', + pay_amount: '1000', + create_quote_token: '1', + }) + .then((result) => { + console.log('OTC quote: ', result); + }) + .catch((err) => { + console.error('OTC error: ', err); + }); ``` See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. @@ -11681,6 +14069,18 @@ 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. @@ -11706,6 +14106,11 @@ Have my projects helped you? Share the love, there are many ways you can show yo - 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/SDK + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 @@ -11729,95 +14136,107 @@ Contributions are encouraged, I will review any incoming pull requests. See the ================ -File: tea.yaml -================ ---- -version: 1.0.0 -codeOwners: - - '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54' -quorum: 1 - -================ -File: tsconfig.cjs.json +File: package.json ================ { - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext" + "name": "gateio-api", + "version": "1.4.0", + "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", + "scripts": { + "clean": "rm -rf dist/*", + "build": "rm -fr dist/* && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", + "pack": "webpack --config webpack/webpack.config.cjs", + "test": "jest --passWithNoTests", + "lint": "eslint src" }, - "include": ["src/**/*.*"] -} - -================ -File: tsconfig.esm.json -================ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "esnext", - "outDir": "dist/mjs", - "target": "esnext" + "main": "dist/cjs/index.js", + "module": "dist/mjs/index.js", + "types": "dist/mjs/index.d.ts", + "exports": { + ".": { + "import": "./dist/mjs/index.js", + "require": "./dist/cjs/index.js", + "types": "./dist/mjs/index.d.ts" + } }, - "include": ["src/**/*.*"] -} - -================ -File: tsconfig.json -================ -{ - "compilerOptions": { - "allowSyntheticDefaultImports": true, - "baseUrl": ".", - "noEmitOnError": true, - "declaration": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": false, - "inlineSourceMap": false, - "lib": ["esnext"], - "listEmittedFiles": false, - "listFiles": false, - "moduleResolution": "node", - "noFallthroughCasesInSwitch": true, - "noImplicitAny": true, - "noUnusedParameters": true, - "pretty": true, - "removeComments": false, - "resolveJsonModule": true, - "skipLibCheck": false, - "sourceMap": true, - "strict": true, - "strictNullChecks": true, - "types": ["node", "jest"], - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext" + "type": "module", + "files": [ + "dist/*", + "llms.txt" + ], + "author": "Tiago Siebler (https://github.com/tiagosiebler)", + "contributors": [ + "Jerko J (https://github.com/JJ-Cro)" + ], + "dependencies": { + "axios": "^1.13.2", + "isomorphic-ws": "^4.0.1", + "ws": "^8.18.3" }, - "compileOnSave": true, - "exclude": ["node_modules", "dist"], - "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] -} - -================ -File: tsconfig.linting.json -================ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "outDir": "dist/cjs", - "target": "esnext", - "rootDir": "../", - "allowJs": true + "devDependencies": { + "@types/jest": "^29.5.12", + "@types/node": "^22.10.2", + "@types/ws": "^8.5.10", + "@typescript-eslint/eslint-plugin": "^8.18.0", + "@typescript-eslint/parser": "^8.18.0", + "eslint": "^8.29.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-require-extensions": "^0.1.3", + "eslint-plugin-simple-import-sort": "^12.1.1", + "jest": "^29.7.0", + "ts-jest": "^29.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.7.3" }, - "include": [ - "src/**/*.*", - "test/**/*.*", - "examples/**/*.*", - ".eslintrc.cjs", - "jest.config.ts" - ] + "optionalDependencies": { + "webpack": "^5.0.0", + "webpack-bundle-analyzer": "^5.1.1", + "webpack-cli": "^4.0.0" + }, + "keywords": [ + "Gate", + "Gate.io", + "Gate.com", + "Gate api", + "Gate.io api", + "Gate.com api", + "Gate nodejs", + "Gate javascript", + "Gate javascript websocket api", + "Gate typescript", + "Gate js", + "Gate ts", + "Gate api node", + "Gate sdk javascript", + "algo trading", + "api", + "websocket", + "rest", + "rest api", + "ccxt", + "trading bots", + "nodejs", + "node", + "trading", + "cryptocurrency", + "bitcoin", + "best", + "siebly.io" + ], + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/tiagosiebler" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tiagosiebler/gateio-api" + }, + "bugs": { + "url": "https://github.com/tiagosiebler/gateio-api/issues" + }, + "homepage": "https://github.com/tiagosiebler/gateio-api#readme" } diff --git a/package-lock.json b/package-lock.json index 8bb3047..2bd8ef3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.3.5", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.3.5", + "version": "1.4.0", "license": "MIT", "dependencies": { "axios": "^1.13.2", diff --git a/package.json b/package.json index c0d4398..a80bbae 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.3.5", + "version": "1.4.0", "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 a622a9e..b422e3d 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -7,6 +7,15 @@ import { } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { CreateStpGroupReq } from './types/request/account.js'; +import { + CreateAlphaOrderReq, + CreateAlphaQuoteReq, + GetAlphaAccountBookReq, + GetAlphaCurrenciesReq, + GetAlphaOrderReq, + GetAlphaOrdersReq, + GetAlphaTickersReq, +} from './types/request/alpha.js'; import { GetLoanCollateralRecordsReq, GetLoanOrdersReq, @@ -14,6 +23,36 @@ import { SubmitLoanOrderReq, UpdateLoanCollateralReq, } from './types/request/collateralLoan.js'; +import { + CloseCrossExPositionReq, + CreateCrossExConvertOrderReq, + CreateCrossExConvertQuoteReq, + CreateCrossExOrderReq, + CreateCrossExTransferReq, + GetCrossExAccountBookReq, + GetCrossExAccountsReq, + GetCrossExAdlRankReq, + GetCrossExCoinDiscountRateReq, + GetCrossExHistoryMarginInterestsReq, + GetCrossExHistoryMarginPositionsReq, + GetCrossExHistoryOrdersReq, + GetCrossExHistoryPositionsReq, + GetCrossExHistoryTradesReq, + GetCrossExInterestRateReq, + GetCrossExMarginPositionLeverageReq, + GetCrossExMarginPositionsReq, + GetCrossExOpenOrdersReq, + GetCrossExPositionLeverageReq, + GetCrossExPositionsReq, + GetCrossExRiskLimitsReq, + GetCrossExSymbolsReq, + GetCrossExTransferCoinsReq, + GetCrossExTransferHistoryReq, + ModifyCrossExOrderReq, + SetCrossExMarginPositionLeverageReq, + SetCrossExPositionLeverageReq, + UpdateCrossExAccountReq, +} from './types/request/crossex.js'; import { GetDeliveryAutoOrdersReq, GetDeliveryBookReq, @@ -106,6 +145,16 @@ import { OptionsMMPSettingsReq, SubmitOptionsOrderReq, } from './types/request/options.js'; +import { + CancelOTCOrderReq, + CreateOTCFiatOrderReq, + CreateOTCQuoteReq, + CreateOTCStablecoinOrderReq, + GetOTCFiatOrderDetailReq, + GetOTCFiatOrderListReq, + GetOTCStablecoinOrderListReq, + MarkOTCOrderAsPaidReq, +} from './types/request/otc.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, @@ -164,12 +213,51 @@ import { StpGroup, StpGroupUser, } from './types/response/account.js'; +import { + AlphaAccount, + AlphaAccountBook, + AlphaCurrency, + AlphaOrder, + AlphaTicker, + CreateAlphaOrderResp, + CreateAlphaQuoteResp, +} from './types/response/alpha.js'; import { LoanCollateralRatio, LoanCollateralRecord, LoanOrder, LoanRepaymentHistoryRecord, } from './types/response/collateralloan.js'; +import { + CancelCrossExOrderResp, + CloseCrossExPositionResp, + CreateCrossExConvertQuoteResp, + CreateCrossExOrderResp, + CreateCrossExTransferResp, + CrossExAccount, + CrossExAccountBook, + CrossExAdlRank, + CrossExCoinDiscountRate, + CrossExFeeRate, + CrossExHistoryMarginInterest, + CrossExHistoryMarginPosition, + CrossExHistoryPosition, + CrossExHistoryTrade, + CrossExInterestRate, + CrossExMarginPosition, + CrossExMarginPositionLeverage, + CrossExOrder, + CrossExPosition, + CrossExPositionLeverage, + CrossExRiskLimit, + CrossExSymbol, + CrossExTransferCoin, + CrossExTransferHistory, + ModifyCrossExOrderResp, + SetCrossExMarginPositionLeverageResp, + SetCrossExPositionLeverageResp, + UpdateCrossExAccountResp, +} from './types/response/crossex.js'; import { DeliveryAccount, DeliveryBook, @@ -269,6 +357,17 @@ import { OptionsUserSettlement, SubmitOptionsOrderResp, } from './types/response/options.js'; +import { + CancelOTCOrderResp, + CreateOTCFiatOrderResp, + CreateOTCQuoteResp, + CreateOTCStablecoinOrderResp, + GetOTCFiatOrderDetailResp, + GetOTCFiatOrderListResp, + GetOTCStablecoinOrderListResp, + GetOTCUserDefaultBankResp, + MarkOTCOrderAsPaidResp, +} from './types/response/otc.js'; import { AgencyCommissionHistoryRecord, AgencyTransactionHistoryRecord, @@ -4695,4 +4794,658 @@ export class RestClient extends BaseRestClient { }> { return this.getPrivate('/rebate/user/sub_relation', params); } + + /**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ + + /** + * Fiat and stablecoin quote + * + * Create fiat and stablecoin quotes, supporting both PAY and GET directions + * + * @param params Quote parameters + * @returns Promise with quote details including rate, amounts, and quote_token + */ + createOTCQuote(params: CreateOTCQuoteReq): Promise { + return this.postPrivate('/otc/quote', { body: params }); + } + + /** + * Create fiat order + * + * Create a fiat order, supporting BUY for on-ramp and SELL for off-ramp + * + * @param params Fiat order parameters + * @returns Promise with order creation confirmation + */ + createOTCFiatOrder( + params: CreateOTCFiatOrderReq, + ): Promise { + return this.postPrivate('/otc/order/create', { body: params }); + } + + /** + * Create stablecoin order + * + * Create stablecoin order + * + * @param params Stablecoin order parameters + * @returns Promise with order creation confirmation + */ + createOTCStablecoinOrder( + params: CreateOTCStablecoinOrderReq, + ): Promise { + return this.postPrivate('/otc/stable_coin/order/create', { body: params }); + } + + /** + * Get user's default bank account information + * + * Get user's default bank account information for order placement + * + * @returns Promise with default bank account details + */ + getOTCUserDefaultBank(): Promise { + return this.getPrivate('/otc/get_user_def_bank'); + } + + /** + * Mark fiat order as paid + * + * Mark fiat order as paid + * + * @param params Parameters with order_id + * @returns Promise with confirmation + */ + markOTCOrderAsPaid( + params: MarkOTCOrderAsPaidReq, + ): Promise { + return this.postPrivate('/otc/order/paid', { body: params }); + } + + /** + * Fiat order cancellation + * + * Cancel fiat order + * + * @param params Parameters with order_id + * @returns Promise with cancellation confirmation + */ + cancelOTCOrder(params: CancelOTCOrderReq): Promise { + return this.postPrivate('/otc/order/cancel', { query: params }); + } + + /** + * Fiat order list + * + * Query the fiat order list with filters such as type, currency, time range, and status + * + * @param params Filter parameters for fiat order list + * @returns Promise with paginated fiat order list + */ + getOTCFiatOrderList( + params?: GetOTCFiatOrderListReq, + ): Promise { + return this.getPrivate('/otc/order/list', params); + } + + /** + * Stablecoin order list + * + * Query stablecoin order list with filtering by currency, time range, status, etc. + * + * @param params Filter parameters for stablecoin order list + * @returns Promise with paginated stablecoin order list + */ + getOTCStablecoinOrderList( + params?: GetOTCStablecoinOrderListReq, + ): Promise { + return this.getPrivate('/otc/stable_coin/order/list', params); + } + + /** + * Fiat order details + * + * Query fiat order details + * + * @param params Parameters with order_id + * @returns Promise with fiat order details + */ + getOTCFiatOrderDetail( + params: GetOTCFiatOrderDetailReq, + ): Promise { + return this.getPrivate('/otc/order/detail', params); + } + + /**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ + + /** + * Query Trading Pair Information + * + * Query trading pair information for cross-exchange trading + * + * @param params Optional parameters to filter symbols + * @returns Promise with array of symbol information + */ + getCrossExSymbols(params?: GetCrossExSymbolsReq): Promise { + return this.get('/crossex/rule/symbols', params); + } + + /** + * Query Risk Limit Information + * + * Query risk limit information for futures/margin trading pairs + * + * @param params Parameters with required symbols + * @returns Promise with array of risk limit information + */ + getCrossExRiskLimits( + params: GetCrossExRiskLimitsReq, + ): Promise { + return this.get('/crossex/rule/risk_limits', params); + } + + /** + * Query Supported Transfer Currencies + * + * Query supported transfer currencies for cross-exchange + * + * @param params Optional currency filter + * @returns Promise with array of transfer coin information + */ + getCrossExTransferCoins( + params?: GetCrossExTransferCoinsReq, + ): Promise { + return this.get('/crossex/transfers/coin', params); + } + + /** + * Fund Transfer + * + * Transfer funds between accounts. Rate limit: 10 requests per 10 seconds + * + * @param params Transfer parameters + * @returns Promise with transfer confirmation + */ + createCrossExTransfer( + params: CreateCrossExTransferReq, + ): Promise { + return this.postPrivate('/crossex/transfers', { body: params }); + } + + /** + * Query Fund Transfer History + * + * Query fund transfer history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of transfer history records + */ + getCrossExTransferHistory( + params?: GetCrossExTransferHistoryReq, + ): Promise { + return this.getPrivate('/crossex/transfers', params); + } + + /** + * Create an order + * + * Create an order for cross-exchange trading. Rate Limit: 100 requests per 10 seconds + * + * @param params Order parameters + * @returns Promise with order creation response + */ + createCrossExOrder( + params: CreateCrossExOrderReq, + ): Promise { + return this.postPrivate('/crossex/orders', { body: params }); + } + + /** + * Cancel Order + * + * Cancel an order. Rate Limit: 100 requests per 10 seconds + * + * @param order_id Order ID or Text for Cancel Order + * @returns Promise with cancellation confirmation + */ + cancelCrossExOrder(order_id: string): Promise { + return this.deletePrivate(`/crossex/orders/${order_id}`); + } + + /** + * Modify Order + * + * Modify an existing order. Rate Limit: 100 requests per 10 seconds + * + * @param order_id Order ID or Text for Modify Order + * @param params Modification parameters + * @returns Promise with modification confirmation + */ + modifyCrossExOrder( + order_id: string, + params: ModifyCrossExOrderReq, + ): Promise { + return this.putPrivate(`/crossex/orders/${order_id}`, { body: params }); + } + + /** + * Query order details + * + * Query order details by order ID or custom text. Rate Limit: 200 requests per 10 seconds + * + * @param order_id Order ID or custom text + * @returns Promise with order details + */ + getCrossExOrder(order_id: string): Promise { + return this.getPrivate(`/crossex/orders/${order_id}`); + } + + /** + * Flash Swap Inquiry + * + * Create a flash swap quote. Rate Limit: 100 requests per day + * + * @param params Quote parameters + * @returns Promise with quote details + */ + createCrossExConvertQuote( + params: CreateCrossExConvertQuoteReq, + ): Promise { + return this.postPrivate('/crossex/convert/quote', { body: params }); + } + + /** + * Flash Swap Transaction + * + * Execute a flash swap transaction. Rate limit: 10 requests per 10 seconds + * + * @param params Parameters with quote_id + * @returns Promise with transaction confirmation + */ + createCrossExConvertOrder(params: CreateCrossExConvertOrderReq): Promise<{}> { + return this.postPrivate('/crossex/convert/orders', { body: params }); + } + + /** + * Modify Account Contract Position Mode and Account Mode + * + * Modify account settings. Rate Limit: 100 requests per 60 seconds + * + * @param params Account modification parameters + * @returns Promise with update confirmation + */ + updateCrossExAccount( + params: UpdateCrossExAccountReq, + ): Promise { + return this.putPrivate('/crossex/accounts', { body: params }); + } + + /** + * Query Account Assets + * + * Query account assets and balances. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional exchange_type filter + * @returns Promise with account information + */ + getCrossExAccounts(params?: GetCrossExAccountsReq): Promise { + return this.getPrivate('/crossex/accounts', params); + } + + /** + * Modify Contract Trading Pair Leverage Multiplier + * + * Modify leverage for contract trading pair. Rate Limit: 100 requests per 10 seconds + * + * @param params Leverage modification parameters + * @returns Promise with leverage update confirmation + */ + setCrossExPositionLeverage( + params: SetCrossExPositionLeverageReq, + ): Promise { + return this.postPrivate('/crossex/positions/leverage', { body: params }); + } + + /** + * Query Contract Trading Pair Leverage Multiplier + * + * Query leverage for contract trading pairs. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional symbols filter + * @returns Promise with array of leverage information + */ + getCrossExPositionLeverage( + params?: GetCrossExPositionLeverageReq, + ): Promise { + return this.getPrivate('/crossex/positions/leverage', params); + } + + /** + * Modify Leveraged Trading Pair Leverage Multiplier + * + * Modify leverage for margin trading pair. Rate Limit: 100 requests per 10 seconds + * + * @param params Leverage modification parameters + * @returns Promise with leverage update confirmation + */ + setCrossExMarginPositionLeverage( + params: SetCrossExMarginPositionLeverageReq, + ): Promise { + return this.postPrivate('/crossex/margin_positions/leverage', { + body: params, + }); + } + + /** + * Query Leveraged Trading Pair Leverage Multiplier + * + * Query leverage for margin trading pairs. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional symbols filter + * @returns Promise with array of leverage information + */ + getCrossExMarginPositionLeverage( + params?: GetCrossExMarginPositionLeverageReq, + ): Promise { + return this.getPrivate('/crossex/margin_positions/leverage', params); + } + + /** + * Full Close Position + * + * Fully close a position. Rate Limit: 100 requests per day + * + * @param params Position close parameters + * @returns Promise with close position confirmation + */ + closeCrossExPosition( + params: CloseCrossExPositionReq, + ): Promise { + return this.deletePrivate('/crossex/position', { body: params }); + } + + /** + * Query margin asset interest rates + * + * Query interest rates for margin assets. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of interest rates + */ + getCrossExInterestRate( + params?: GetCrossExInterestRateReq, + ): Promise { + return this.getPrivate('/crossex/interest_rate', params); + } + + /** + * Query User Fee Rates + * + * Query user fee rates. Rate Limit: 200 requests per 10 seconds + * + * @returns Promise with fee rate information + */ + getCrossExFeeRate(): Promise { + return this.getPrivate('/crossex/fee'); + } + + /** + * Query Contract Positions + * + * Query contract positions. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of positions + */ + getCrossExPositions( + params?: GetCrossExPositionsReq, + ): Promise { + return this.getPrivate('/crossex/positions', params); + } + + /** + * Query Leveraged Positions + * + * Query margin/leveraged positions. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of margin positions + */ + getCrossExMarginPositions( + params?: GetCrossExMarginPositionsReq, + ): Promise { + return this.getPrivate('/crossex/margin_positions', params); + } + + /** + * Query ADL Position Reduction Ranking + * + * Query ADL position reduction ranking. Rate Limit: 200 requests per 10 seconds + * + * @param params Parameters with required symbol + * @returns Promise with array of ADL rankings + */ + getCrossExAdlRank(params: GetCrossExAdlRankReq): Promise { + return this.getPrivate('/crossex/adl_rank', params); + } + + /** + * Query All Current Open Orders + * + * Query all current open orders. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of open orders + */ + getCrossExOpenOrders( + params?: GetCrossExOpenOrdersReq, + ): Promise { + return this.getPrivate('/crossex/open_orders', params); + } + + /** + * Query order history + * + * Query historical orders. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical orders + */ + getCrossExHistoryOrders( + params?: GetCrossExHistoryOrdersReq, + ): Promise { + return this.getPrivate('/crossex/history_orders', params); + } + + /** + * Query Contract Position History + * + * Query contract position history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical positions + */ + getCrossExHistoryPositions( + params?: GetCrossExHistoryPositionsReq, + ): Promise { + return this.getPrivate('/crossex/history_positions', params); + } + + /** + * Query Leveraged Position History + * + * Query margin position history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of historical margin positions + */ + getCrossExHistoryMarginPositions( + params?: GetCrossExHistoryMarginPositionsReq, + ): Promise { + return this.getPrivate('/crossex/history_margin_positions', params); + } + + /** + * Query Leveraged Interest Deduction History + * + * Query margin interest deduction history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of interest deduction records + */ + getCrossExHistoryMarginInterests( + params?: GetCrossExHistoryMarginInterestsReq, + ): Promise { + return this.getPrivate('/crossex/history_margin_interests', params); + } + + /** + * Query filled history + * + * Query trade execution history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of trade records + */ + getCrossExHistoryTrades( + params?: GetCrossExHistoryTradesReq, + ): Promise { + return this.getPrivate('/crossex/history_trades', params); + } + + /** + * Query Account Asset Change History + * + * Query account balance change history. Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of account book records + */ + getCrossExAccountBook( + params?: GetCrossExAccountBookReq, + ): Promise { + return this.getPrivate('/crossex/account_book', params); + } + + /** + * Query currency discount rate + * + * Query currency discount rate (for margin currency in isolated exchange mode). Rate Limit: 200 requests per 10 seconds + * + * @param params Optional filter parameters + * @returns Promise with array of coin discount rates + */ + getCrossExCoinDiscountRate( + params?: GetCrossExCoinDiscountRateReq, + ): Promise { + return this.getPrivate('/crossex/coin_discount_rate', params); + } + + /**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ + + /** + * Query position assets + * + * Query alpha account position assets + * + * @returns Promise with array of account balances + */ + getAlphaAccounts(): Promise { + return this.getPrivate('/alpha/accounts'); + } + + /** + * Query asset transactions + * + * Query alpha account transaction history + * + * @param params Parameters with required from timestamp + * @returns Promise with array of transaction records + */ + getAlphaAccountBook( + params: GetAlphaAccountBookReq, + ): Promise { + return this.getPrivate('/alpha/account_book', params); + } + + /** + * Alpha Quote API + * + * Get a quote for alpha trading. Quote is valid for 1 minute. Rate-limited at 10 requests per second per user. + * + * @param params Quote parameters + * @returns Promise with quote details + */ + createAlphaQuote(params: CreateAlphaQuoteReq): Promise { + return this.postPrivate('/alpha/quote', { body: params }); + } + + /** + * Alpha Order API + * + * Create an alpha order. Rate-limited at 5 requests per second per user. + * + * @param params Order parameters including quote_id + * @returns Promise with order details + */ + createAlphaOrder(params: CreateAlphaOrderReq): Promise { + return this.postPrivate('/alpha/orders', { body: params }); + } + + /** + * Alpha Order List API + * + * Query alpha order list with filters + * + * @param params Filter parameters + * @returns Promise with array of orders + */ + getAlphaOrders(params: GetAlphaOrdersReq): Promise { + return this.getPrivate('/alpha/orders', params); + } + + /** + * Alpha Single Order Query API + * + * Query a single alpha order by order ID + * + * @param params Parameters with order_id + * @returns Promise with order details + */ + getAlphaOrder(params: GetAlphaOrderReq): Promise { + return this.getPrivate('/alpha/order', params); + } + + /** + * Query currency information + * + * Query alpha currency information. When currency is provided, returns specific currency info; otherwise returns paginated list. + * + * @param params Optional filter parameters + * @returns Promise with array of currency information + */ + getAlphaCurrencies(params?: GetAlphaCurrenciesReq): Promise { + return this.get('/alpha/currencies', params); + } + + /** + * Query currency ticker + * + * Query alpha currency ticker. When currency is provided, returns specific ticker; otherwise returns paginated list. + * + * @param params Optional filter parameters + * @returns Promise with array of ticker information + */ + getAlphaTickers(params?: GetAlphaTickersReq): Promise { + return this.get('/alpha/tickers', params); + } } diff --git a/src/index.ts b/src/index.ts index 34224ab..fcbc4d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,9 @@ export * from './WebsocketClient.js'; // Request Types export * from './types/request/account.js'; +export * from './types/request/alpha.js'; export * from './types/request/collateralLoan.js'; +export * from './types/request/crossex.js'; export * from './types/request/delivery.js'; export * from './types/request/earn.js'; export * from './types/request/earnuni.js'; @@ -16,6 +18,7 @@ export * from './types/request/margin.js'; export * from './types/request/marginuni.js'; export * from './types/request/multicollateralLoan.js'; export * from './types/request/options.js'; +export * from './types/request/otc.js'; export * from './types/request/rebate.js'; export * from './types/request/spot.js'; export * from './types/request/subaccount.js'; @@ -25,7 +28,9 @@ export * from './types/request/withdrawal.js'; // Response Types export * from './types/response/account.js'; +export * from './types/response/alpha.js'; export * from './types/response/collateralloan.js'; +export * from './types/response/crossex.js'; export * from './types/response/delivery.js'; export * from './types/response/earn.js'; export * from './types/response/earnuni.js'; @@ -35,6 +40,7 @@ export * from './types/response/margin.js'; export * from './types/response/marginuni.js'; export * from './types/response/multicollateralLoan.js'; export * from './types/response/options.js'; +export * from './types/response/otc.js'; export * from './types/response/rebate.js'; export * from './types/response/spot.js'; export * from './types/response/subaccount.js'; diff --git a/src/types/request/alpha.ts b/src/types/request/alpha.ts new file mode 100644 index 0000000..2c469eb --- /dev/null +++ b/src/types/request/alpha.ts @@ -0,0 +1,54 @@ +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ + +export interface GetAlphaAccountBookReq { + from: number; // Start timestamp for the query + to?: number; // End timestamp for the query, defaults to current time if not specified + page?: number; // Page number + limit?: number; // Maximum 100 items per page +} + +export interface CreateAlphaQuoteReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) + gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) + slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom +} + +export interface CreateAlphaOrderReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + amount: string; // Trade Quantity (side: buy refers to quote currency USDT, side: sell refers to base currency) + gas_mode: 'speed' | 'custom'; // Trading mode (speed: Smart mode, custom: Custom mode uses slippage parameter) + slippage?: string; // Slippage tolerance (10 means 10% tolerance) - required when gas_mode is custom + quote_id: string; // Quote ID returned from quotation API +} + +export interface GetAlphaOrdersReq { + currency: string; // Trading symbol + side: 'buy' | 'sell'; // Buy or sell orders + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + from?: number; // Start time for order query + to?: number; // End time for order query, defaults to current time if not specified + limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 + page?: number; // Page number +} + +export interface GetAlphaOrderReq { + order_id: string; // Order ID +} + +export interface GetAlphaCurrenciesReq { + currency?: string; // Query currency information by currency symbol + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} + +export interface GetAlphaTickersReq { + currency?: string; // Query by specified currency name + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} diff --git a/src/types/request/crossex.ts b/src/types/request/crossex.ts new file mode 100644 index 0000000..19a7697 --- /dev/null +++ b/src/types/request/crossex.ts @@ -0,0 +1,174 @@ +/**========================================================================================================================== + * CROSSEX + * ========================================================================================================================== + */ + +export interface GetCrossExSymbolsReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} + +export interface GetCrossExRiskLimitsReq { + symbols: string; // Trading Pair List, multiple separated by commas +} + +export interface GetCrossExTransferCoinsReq { + coin?: string; // Currency +} + +export interface CreateCrossExTransferReq { + coin: string; // Currency + amount: string; // Transfer amount + from: string; // Transfer-in account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT + to: string; // Transfer-out account: CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX, SPOT + 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 +} + +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'; // Default GTC + 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 ModifyCrossExOrderReq { + qty?: string; // modify amount + price?: string; // modify price +} + +export interface CreateCrossExConvertQuoteReq { + exchange_type: string; // Exchange Type + from_coin: string; // Asset Sold + to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT) + from_amount: string; // Amount to sell +} + +export interface CreateCrossExConvertOrderReq { + 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/CROSSEX) +} + +export interface GetCrossExAccountsReq { + exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE) +} + +export interface SetCrossExPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} + +export interface GetCrossExPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} + +export interface SetCrossExMarginPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage +} + +export interface GetCrossExMarginPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas +} + +export interface CloseCrossExPositionReq { + symbol: string; // Trading Pair + position_side?: string; // Position Direction +} + +export interface GetCrossExInterestRateReq { + coin?: string; // Currency + exchange_type?: string; // Exchange +} + +export interface GetCrossExPositionsReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange +} + +export interface GetCrossExMarginPositionsReq { + symbol?: string; // Currency pair + exchange_type?: string; // Exchange +} + +export interface GetCrossExAdlRankReq { + symbol: string; // Trading Pair +} + +export interface GetCrossExOpenOrdersReq { + 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 +} + +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 +} + +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 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 +} + +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 GetCrossExCoinDiscountRateReq { + coin?: string; + exchange_type?: string; // OKX/GATE/BINANCE +} diff --git a/src/types/request/otc.ts b/src/types/request/otc.ts new file mode 100644 index 0000000..12ab623 --- /dev/null +++ b/src/types/request/otc.ts @@ -0,0 +1,68 @@ +/**========================================================================================================================== + * 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 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 + bank_id: string; // Bank card ID used for the order (retrieved via the default bank card API) +} + +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) + promotion_code?: string; // Promotion code + quote_token?: string; // Parameter returned by the quote API +} + +export interface MarkOTCOrderAsPaidReq { + order_id: string; // Order ID +} + +export interface CancelOTCOrderReq { + 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 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 GetOTCFiatOrderDetailReq { + order_id: string; // Order ID +} diff --git a/src/types/response/alpha.ts b/src/types/response/alpha.ts new file mode 100644 index 0000000..3945033 --- /dev/null +++ b/src/types/response/alpha.ts @@ -0,0 +1,78 @@ +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ + +export interface AlphaAccount { + currency: string; // Currency name + available: string; // Available Balance + locked: string; // Locked balance + token_address: string; // Token address + chain: string; // Blockchain name +} + +export interface AlphaAccountBook { + id: number; // Order ID + time: number; // Operation timestamp + currency: string; // Currency name + change: string; // Change amount + balance: string; // Balance after change +} + +export interface CreateAlphaQuoteResp { + quote_id: string; // Quote ID for order placement, valid for 1 minute + min_amount: string; // Minimum order size + max_amount: string; // Maximum order size + price: string; // Token Price (USDT-based) + slippage: string; // Slippage + estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) + order_fee: string; // Slippage tolerance (10 means 10% tolerance) + target_token_min_amount: string; // Minimum received amount + target_token_max_amount: string; // Maximum received amount + error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) +} + +export interface CreateAlphaOrderResp { + order_id: string; // Order ID + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + side: string; // Buy or sell orders (buy/sell) + gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) + create_time: number; // Creation timestamp + amount: string; // Trade Quantity + token_address: string; // Token contract address + chain: string; // Blockchain name +} + +export interface AlphaOrder { + order_id: string; // Order ID + tx_hash: string; // Transaction Hash + side: string; // Buy or sell orders (buy/sell) + usdt_amount: string; // Amount (USDT) + currency: string; // Token + currency_amount: string; // Token amount + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) + chain: string; // Blockchain + gas_fee: string; // Gas Fee (USDT-based) + transaction_fee: string; // Trading Fee (USDT-based) + failed_reason: string; // Failure reason (if applicable) + create_time: number; // Creation timestamp +} + +export interface AlphaCurrency { + currency: string; // Currency symbol + name: string; // Currency name + chain: string; // The main chain corresponding to the coin + address: string; // Contract Address + amount_precision: number; // Amount scale + precision: number; // Price scale + status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) +} + +export interface AlphaTicker { + currency: string; // Currency symbol + last: string; // Last trading price + change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) + volume: string; // 24h Trading Volume (USDT) + market_cap: string; // Current Token Market Cap +} diff --git a/src/types/response/crossex.ts b/src/types/response/crossex.ts new file mode 100644 index 0000000..a42090e --- /dev/null +++ b/src/types/response/crossex.ts @@ -0,0 +1,356 @@ +/**========================================================================================================================== + * 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; +} + +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 +} + +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 +} + +export interface CreateCrossExTransferResp { + 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, 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 interface CreateCrossExOrderResp { + order_id: number | string; + 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; // Attribute COMMON: Normal Order, LIQ: Liquidation Takeover Order, REDUCE: Liquidation Reduce Order, ADL: Auto-Reduce + 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 +} + +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/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) +} + +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[]; +} + +export interface SetCrossExPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage +} + +export interface CrossExPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; +} + +export interface SetCrossExMarginPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage +} + +export interface CrossExMarginPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; +} + +export interface CloseCrossExPositionResp { + 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 +} + +export interface CrossExSpecialFee { + symbol: string; // Currency pair + taker_fee_rate: string; // Taker fee rate + maker_fee_rate: string; // Maker fee rate +} + +export interface CrossExFeeRate { + spot_maker_fee: string; // spot Maker fee rate + spot_taker_fee: string; // spot Taker fee rate + future_maker_fee: string; // contract Maker fee rate + future_taker_fee: string; // contract Taker fee rate + special_fee_list: CrossExSpecialFee[]; +} + +export interface CrossExPosition { + user_id: string; // User ID + position_id: string; // Position ID + symbol: string; // Currency pair + position_side: string; // Position Direction + initial_margin: string; // Initial Margin + maintenance_margin: string; // Maintenance margin + position_qty: string; // Position Quantity + position_value: string; // Position Value + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + entry_price: string; // Position Average Entry Price + mark_price: string; // Mark price + leverage: string; // Position Leverage + max_leverage: string; // Maximum leverage + risk_limit: string; // Position risk limit + fee: string; // Position Fee + funding_fee: string; // Position Funding Fee + funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) + create_time: string; // Position Creation Time + update_time: string; // Position Update Time + closed_pnl: string; // Realized PnL +} + +export interface CrossExMarginPosition { + user_id: string; // User ID + position_id: string; // Leveraged Position ID + symbol: string; // Trading Pair + position_side: string; // Position Direction + initial_margin: string; // Initial position margin + maintenance_margin: string; // Position maintenance margin + asset_qty: string; // Position Asset Quantity + asset_coin: string; // Position Asset Currency + position_value: string; // Position Value + liability: string; // Debt Quantity + liability_coin: string; // Debt Currency + interest: string; // Deducted Interest + max_position_qty: string; // Max Trade Size + entry_price: string; // Position Cost Price (Average Opening Price) + index_price: string; // Index price + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + leverage: string; // Opening Leverage + max_leverage: string; // Maximum leverage + create_time: string; // Created time + update_time: string; // Update time +} + +export interface CrossExAdlRank { + user_id: string; // User ID + symbol: string; // Currency pair + crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) + exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) +} + +export interface 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 + business_type: string; // Business Type + create_time: string; // Created time + update_time: string; // Update time +} + +export interface CrossExHistoryMarginPosition { + position_id: string; // Position ID + user_id: string; // User ID + symbol: string; // Currency pair + closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) + closed_pnl: string; // Close Position P&L + closed_pnl_rate: string; // Close Position P&L Ratio + open_avg_price: string; // Average Opening Price + closed_avg_price: string; // Average Close Price + max_position_qty: string; // Max Trade Size + closed_qty: string; // Close Position Quantity + closed_value: string; // Close Position Value + liq_fee: string; // Liquidation Fee + position_side: string; // Position Direction Before Close + leverage: string; // Leverage at Close + interest: string; // Total Deducted Interest + business_type: string; // Position Business Type + create_time: string; // Created time + update_time: string; // Update time +} + +export interface 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; 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 +} + +export interface CrossExAccountBook { + id: string; // Account Change Record ID + user_id: string; // User ID + business_id: string; // Business ID + type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY + exchange_type: string; // Exchange + coin: string; // Currency + change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) + balance: string; // Balance after change + create_time: string; // Created time +} + +export interface 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 +} diff --git a/src/types/response/otc.ts b/src/types/response/otc.ts new file mode 100644 index 0000000..d8175e4 --- /dev/null +++ b/src/types/response/otc.ts @@ -0,0 +1,157 @@ +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ + +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 + validity_period?: string; + ex_rate?: string; + usdc_rate?: string; + refresh_limit?: number; + refresh_limit_msg?: string; + }; + timestamp: number; +} + +export interface CreateOTCFiatOrderResp { + code: number; + message: string; + timestamp: number; +} + +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; +} + +export interface OTCBankInfo { + 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; +} + +export interface GetOTCUserDefaultBankResp { + code: number; + message: string; + data: OTCBankInfo; + timestamp: number; +} + +export interface MarkOTCOrderAsPaidResp { + code: number; + message: string; + timestamp: number; +} + +export interface CancelOTCOrderResp { + code: number; + message: string; + timestamp: number; +} + +export interface OTCFiatOrderListItem { + time: string; // Current time + timestamp: number; // Current timestamp + order_id: string; + trade_no: string; // Trade number + type: string; // Quote direction buy/sell/all + status: string; // Order Status + 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 + 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 +} + +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 + status: string; // Status + db_status: string; + create_time: string; // Created time + memo: string; // Cancellation or rejection reason + side: string; // Quote direction + promotion_code: string; // Promotion code + trade_no: string; // Trade number +} + +export interface GetOTCFiatOrderDetailResp { + message: string; + code: number; + data: OTCFiatOrderDetail; +}