This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter). ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ examples/ deprecated/ README.md demo-trading.ts fasterHmacSign.ts README.md rest-v5-all.ts rest-v5-custom-url.ts rest-v5-next-cursor.ts rest-v5-p2p.ts rest-v5-private.ts rest-v5-proxies.ts rest-v5-proxies2.ts rest-v5-public.ts RSA-sign.md RSA-sign.ts ws-api-client.ts ws-api-raw-events.ts ws-api-raw-promises.ts ws-private-v5.ts ws-public-allLiquidations.ts ws-public-v5.ts src/ constants/ enum.ts types/ request/ account-asset.ts contract.ts copy-trading.ts index.ts inverse.ts linear.ts unified-margin.ts usdc-options.ts usdc-perp.ts usdc-shared.ts v5-account.ts v5-asset.ts v5-broker.ts v5-crypto-loan.ts v5-earn.ts v5-market.ts v5-p2p-trading.ts v5-position.ts v5-pre-upgrade.ts v5-rfq.ts v5-spot-leverage-token.ts v5-spreadtrading.ts v5-trade.ts v5-user.ts response/ account-asset.ts contract.ts index.ts shared.ts spot.ts unified-margin.ts usdt-perp.ts v5-account.ts v5-asset.ts v5-broker.ts v5-crypto-loan.ts v5-earn.ts v5-market.ts v5-p2p-trading.ts v5-position.ts v5-preupgrade.ts v5-rfq.ts v5-spot-leverage-token.ts v5-spreadtrading.ts v5-trade.ts v5-user.ts websockets/ index.ts ws-api.ts ws-confirmations.ts ws-events.ts ws-general.ts index.ts shared-v5.ts shared.ts index.ts rest-client-v5.ts spot-client-v3.ts websocket-api-client.ts websocket-client.ts webpack/ webpack.config.js .eslintrc.cjs .gitignore .jshintrc .nvmrc .prettierrc index.js jest.config.ts jsconfig.json LICENSE.md package.json README.md tea.yaml tsconfig.build.json tsconfig.examples.json tsconfig.json tsconfig.linting.json tsconfig.test.json ================================================================ Files ================================================================ ================ File: examples/deprecated/README.md ================ # Deprecated Examples The examples in this folder use old/deprecated/obsolete APIs. They should all have a modern alternative. As of December 2023, use the V5 APIs & WebSockets. ================ File: examples/demo-trading.ts ================ import { DefaultLogger, RestClientV5, WebsocketClient } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** * * * This example demonstrates how to use Bybit's demo trading functionality, both for REST and WS. * * Refer to the API docs for more information: https://bybit-exchange.github.io/docs/v5/demo * * */ ⋮---- /** * Set this to true to enable demo trading: */ ⋮---- // Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing ⋮---- // trace: (...params) => console.log('trace', ...params), ⋮---- /** * Set this to true to enable demo trading for the private account data WS * Topics: order,execution,position,wallet,greeks */ ⋮---- function setWsClientEventListeners( websocketClient: WebsocketClient, accountRef: string, ): Promise ⋮---- // console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- // Simple promise to ensure we're subscribed before trying anything else ⋮---- // Start trading ⋮---- /** Simple examples for private REST API calls with bybit's V5 REST APIs */ ⋮---- // Trade USDT linear perps ================ File: examples/README.md ================ # Examples These samples can be executed using `ts-node`: ``` ts-node ./examples/rest-spot-public.ts ``` ================ File: examples/rest-v5-all.ts ================ import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** * If you don't plan on making any private api calls, * you can instance the REST client without any parameters: * * const client = new RestClientV5(); */ ================ File: examples/rest-v5-custom-url.ts ================ import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** * The first parameter of the REST client allows you to pass any configuration parameters supported by the SDK. * * These include API keys, if you wish to use private endpoints, but also expose other features such as * setting a custom base URL (e.g. for Turkish users). * * Refer to the API documentation for a complete list of domains: https://bybit-exchange.github.io/docs/v5/guide#authentication */ ⋮---- /** * You can pass a completely custom base URL, * e.g. if you're trying to use a domain that hasn't been added yet (please let us know) */ // baseUrl: 'https://api5.bybit.com', // // /** * * There are also predefined API regions, which you can easily use with the "apiRegion" property: * */ // // // default: routes to api.bybit.com // apiRegion: 'default', // // // bytick: routes to api.bytick.com // apiRegion: 'bytick', // // // NL: routes to api.bybit.nl (for Netherland users) // apiRegion: 'NL', // // // HK: routes to api.byhkbit.com (for Hong Kong users) // apiRegion: 'HK', // // // TK: routes to api.bybit-tr.com (for Turkey users) // apiRegion: 'TK', ================ File: examples/rest-v5-next-cursor.ts ================ import { RestClientV5, UniversalTransferRecordV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- async function getAllUniversalTransfers() ⋮---- limit: 50, // Maximum page size per request cursor: nextCursor || undefined, // Only send cursor if we have one ⋮---- // Optional: Add a small delay to avoid rate limits ================ File: examples/rest-v5-proxies.ts ================ import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- // Sometimes using a proxy introduces recv timestamp errors (due to the extra latency) // If that happens, you can try increasing the recv window (which is 5000ms by default) // recv_window: 10000, ⋮---- /** * Axios has a native way of supporting http/https proxies. It works for most proxy services but not all. * If you have issues making any proxied requests this way, take a look at the rest-v5-proxies2.ts example using the https-proxy-agent. */ ⋮---- protocol: 'http', // or 'https' ⋮---- // const orders = await client.batchSubmitOrders('linear', [ // { // symbol: 'ETHUSDT', // orderType: 'Limit', // side: 'Buy', // qty: '1', // orderIv: '6', // timeInForce: 'GTC', // orderLinkId: 'option-test-001', // mmp: false, // reduceOnly: false, // }, // { // symbol: 'ETHUSDT', // orderType: 'Limit', // side: 'Sell', // qty: '2', // price: '700', // timeInForce: 'GTC', // orderLinkId: 'option-test-001', // mmp: false, // reduceOnly: false, // }, // ]); ⋮---- // console.log('orders: ', JSON.stringify(orders, null, 2)); ================ File: examples/rest-v5-proxies2.ts ================ // @ts-ignore import { HttpsProxyAgent } from 'https-proxy-agent'; ⋮---- import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** * Some proxy services don't work with the proxy configuration that axios supports. * * For these, you can try using HttpsProxyAgent or SocksProxyAgent (depending on your proxy type, HTTP or SOCKS). * * The following example uses the HttpsProxyAgent (via the npm module https-proxy-agent). */ ⋮---- // Sometimes using a proxy introduces recv timestamp errors (due to the extra latency) // If that happens, you can try increasing the recv window (which is 5000ms by default) // recv_window: 10000, ================ File: examples/rest-v5-public.ts ================ import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** * If you don't plan on making any private api calls, * you can instance the REST client without any parameters */ ⋮---- // const klineResult = await client.getKline({ // category: 'linear', // interval: '15', // symbol: 'BTCUSDT', // }); // console.log('klineResult: ', klineResult); ⋮---- // const markPriceKlineResult = await client.getMarkPriceKline({ // category: 'linear', // interval: '15', // symbol: 'BTCUSDT', // }); // console.log('markPriceKlineResult: ', markPriceKlineResult); ⋮---- // const indexPriceKline = await client.getIndexPriceKline({ // category: 'linear', // interval: '15', // symbol: 'BTCUSDT', // }); // console.log('indexPriceKline: ', indexPriceKline); ⋮---- // const openInterest = await client.getOpenInterest({ // category: 'linear', // symbol: 'BTCUSDT', // intervalTime: '5min', // }); ⋮---- // console.log( // JSON.stringify( // tickers.result.list.map((ticker) => ticker.symbol), // null, // 2, // ), // ); ⋮---- // openInterest.result.list.forEach((row) => { // console.log('int: ', { // timestamp: row.timestamp, // value: row.openInterest, // }); // }); // console.log('openInterest: ', openInterest.result.list); ================ File: examples/ws-api-client.ts ================ import { DefaultLogger, WebsocketAPIClient } from '../src'; ⋮---- // or // import { DefaultLogger, WebsocketAPIClient } from 'bybit-api'; // const { DefaultLogger, WebsocketAPIClient } = require('bybit-api'); ⋮---- // function attachEventHandlers( // wsClient: TWSClient, // ): void { // wsClient.on('update', (data) => { // console.log('raw message received ', JSON.stringify(data)); // }); // wsClient.on('open', (data) => { // console.log('ws connected', data.wsKey); // }); // wsClient.on('reconnect', ({ wsKey }) => { // console.log('ws automatically reconnecting.... ', wsKey); // }); // wsClient.on('reconnected', (data) => { // console.log('ws has reconnected ', data?.wsKey); // }); // wsClient.on('authenticated', (data) => { // console.log('ws has authenticated ', data?.wsKey); // }); // } ⋮---- async function main() ⋮---- // Optional ⋮---- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: // trace: (...params) => console.log('trace', ...params), ⋮---- // testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management ⋮---- // Whether to use the livenet demo trading environment // Note: As of Jan 2025, demo trading only supports consuming events, it does // NOT support the WS API. // demoTrading: false, ⋮---- // If you want your own event handlers instead of the default ones with logs, // disable this setting and see the `attachEventHandlers` example below: // attachEventListeners: false ⋮---- logger, // Optional: inject a custom logger ⋮---- // Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled // attachEventHandlers(wsClient.getWSClient()); ⋮---- // Optional, if you see RECV Window errors, you can use this to manage time issues. // ! However, make sure you sync your system clock first! // https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow // wsClient.setTimeOffsetMs(-5000); ⋮---- // Optional: prepare the WebSocket API connection in advance. // This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. // await wsClient.getWSClient().connectWSAPI(); ================ File: src/constants/enum.ts ================ /** Full take profit/stop loss mode (a single TP order and a single SL order can be placed, covering the entire position) */ ⋮---- /** Partial take profit/stop loss mode (multiple TP and SL orders can be placed, covering portions of the position) */ ⋮---- /** This could mean bad request, incorrect value types or even incorrect/missing values */ ⋮---- /** API key requires specific whitelisted IPs, and this IP was not in the list */ ⋮---- /** Account not unified margin, update required */ ⋮---- /** Seen when placing an order */ ⋮---- /** Seen if a conditional order is too large */ ⋮---- /** E.g. trying to change position margin while on cross */ ⋮---- /** E.g. USDC Options trading, trying to access a symbol that is no longer active */ ⋮---- /** E.g. USDC Options trading when the account hasn't been opened for USDC Options yet */ ⋮---- /** * Position idx, used to identify positions in different position modes. * Required if you are under One-Way Mode: */ export enum LinearPositionIdx { OneWayMode = 0, BuySide = 1, SellSide = 2, } ================ File: src/types/request/account-asset.ts ================ export type TransferAccountType = | 'CONTRACT' | 'SPOT' | 'INVESTMENT' | 'OPTION' | 'UNIFIED'; ⋮---- export type TransferType = 'IN' | 'OUT'; ⋮---- export type TransferStatus = 'SUCCESS' | 'PENDING' | 'FAILED'; ⋮---- export type PageDirection = 'Prev' | 'Next'; ⋮---- export interface InternalTransferRequest { transfer_id: string; coin: string; amount: string; from_account_type: TransferAccountType; to_account_type: TransferAccountType; } ⋮---- export interface InternalTransferRequestV3 { transferId: string; coin: string; amount: string; fromAccountType: string; toAccountType: string; } ⋮---- export interface QueryInternalTransfersRequestV3 { transferId?: string; coin: string; status?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface SubAccountTransferRequest { transfer_id: string; coin: string; amount: string; sub_user_id: string; type: TransferType; } ⋮---- export interface SubAccountTransferRequestV3 { transferId?: string; coin?: string; status?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface TransferQueryRequest { transfer_id?: string; coin?: string; status?: TransferStatus; start_time?: number; end_time?: number; direction?: PageDirection; limit?: number; cursor?: string; } ⋮---- export interface EnableUniversalTransferRequest { /** A comma-separated list of subaccount UIDs, for example "123,45,14,26,46" */ transferable_sub_ids?: string; } ⋮---- /** A comma-separated list of subaccount UIDs, for example "123,45,14,26,46" */ ⋮---- export interface UniversalTransferRequest { transfer_id: string; coin: string; amount: string; from_member_id: string; to_member_id: string; from_account_type: TransferAccountType; to_account_type: TransferAccountType; } export interface SupportedDepositListRequest { coin?: string; chain?: string; page_index?: number; page_size?: number; } ⋮---- export interface DepositRecordsRequest { start_time?: number; end_time?: number; coin?: string; cursor?: string; direction?: PageDirection; limit?: number; } ⋮---- export interface WithdrawalRecordsRequest { withdraw_id?: number; start_time?: number; end_time?: number; coin?: string; cursor?: string; direction?: PageDirection; limit?: number; } ⋮---- export interface AccountAssetInformationRequest { /** Account type. Default value: ACCOUNT_TYPE_SPOT */ account_type?: string; coin?: string; } ⋮---- /** Account type. Default value: ACCOUNT_TYPE_SPOT */ ⋮---- export interface WithdrawalRequest { address: string; amount: string; coin: string; chain: string; tag?: string; } ⋮---- export interface UniversalTransferRequestV3 { transferId: string; coin: string; amount: string; fromMemberId: string; toMemberId: string; fromAccountType: TransferAccountType; toAccountType: TransferAccountType; } ⋮---- export interface UniversalTransferListRequestV3 { transferId?: string; coin: string; status?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface TransferCoinListRequestV3 { fromAccountType: TransferAccountType; toAccountType: TransferAccountType; } ⋮---- export interface SingleAccountCoinBalanceRequestV3 { memberId?: string; accountType: TransferAccountType; coin: string; withBonus?: '0' | '1'; } ⋮---- export interface AccountCoinBalancesRequestV3 { memberId?: string; accountType: TransferAccountType; coin?: string; withBonus?: '0' | '1'; } ⋮---- export interface AssetInfoRequestV3 { accountType?: TransferAccountType; coin?: string; } ⋮---- export interface SupportedDepositListRequestV3 { coin?: string; chain?: string; cursor?: string; limit?: number; } ⋮---- export interface DepositRecordQueryRequestV3 { startTime?: number; endTime?: number; coin?: string; cursor?: string; limit?: number; } ⋮---- export interface SubDepositRecordQueryRequestV3 { subMemberId: number; startTime?: number; endTime?: number; coin?: string; cursor?: string; limit?: number; } ⋮---- export interface WithdrawRecordQueryRequestV3 { withdrawID?: number; startTime?: number; endTime?: number; coin?: string; withdrawType?: string; cursor?: string; limit?: number; } ⋮---- export interface WithdrawCreateRequestV3 { coin: string; chain: string; address: string; tag?: string; amount: string; timestamp: number; forceChain?: 0 | 1; } ⋮---- export interface QueryDepositAddressRequestV3 { coin?: string; chainType?: string; } ⋮---- export interface QuerySubAccountDepositAddressRequestV3 { coin?: string; chainType?: string; subMemberId: string; } ⋮---- export interface CreateSubMemberRequestV3 { username: string; memberType: 1 | 6; switch?: 0 | 1; note?: string; } ⋮---- export interface CreateSubAPIKeyRequestV3 { subuid: string; note?: string; readOnly: 0 | 1; ips?: string[]; permissions: { ContractTrade?: string[]; Spot?: string[]; Wallet?: string[]; Options?: string[]; Derivatives?: string[]; Exchange?: string[]; }; } ⋮---- export interface ModifyAPIKeyRequestV3 { readOnly: number; ips?: string[]; permissions: { ContractTrade?: string[]; Spot?: string[]; Wallet?: string[]; Options?: string[]; Derivatives?: string[]; CopyTrading?: string[]; BlockTrade?: string[]; Exchange?: string[]; NFT?: string[]; }; } ================ File: src/types/request/contract.ts ================ import { OrderSide } from '../shared'; import { UMOrderType } from './unified-margin'; import { USDCOrderFilter, USDCTimeInForce } from './usdc-shared'; ⋮---- export interface ContractOrderRequest { symbol: string; side: OrderSide; orderType: UMOrderType; qty: string; timeInForce: USDCTimeInForce; price?: string; triggerDirection?: '1' | '2'; triggerPrice?: string; triggerBy?: string; positionIdx?: '0' | '1' | '2'; orderLinkId?: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: string; slTriggerBy?: string; reduceOnly?: boolean; closeOnTrigger?: boolean; tpslMode?: 'Partial' | 'Full'; tpOrderType?: UMOrderType; slOrderType?: UMOrderType; } ⋮---- export interface ContractHistoricOrdersRequest { orderId?: string; orderLinkId?: string; symbol: string; orderStatus?: string; orderFilter?: USDCOrderFilter; limit?: number; cursor?: string; } ⋮---- export interface ContractCancelOrderRequest { symbol: string; orderId?: string; orderLinkId?: string; } ⋮---- export interface ContractModifyOrderRequest { symbol: string; orderId?: string; orderLinkId?: string; price?: string; qty?: string; triggerPrice?: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: string; slTriggerBy?: string; triggerBy?: string; tpLimitPrice?: string; slLimitPrice?: string; } ⋮---- export interface ContractActiveOrdersRequest { symbol?: string; orderId?: string; orderLinkId?: string; settleCoin?: string; orderFilter?: USDCOrderFilter; limit?: number; } ⋮---- export interface ContractPositionsRequest { symbol?: string; settleCoin?: string; dataFilter?: string; } ⋮---- export interface ContractSetAutoAddMarginRequest { symbol: string; side: 'Buy' | 'Sell'; autoAddMargin: 1 | 0; positionIdx?: 0 | 1 | 2; } ⋮---- export interface ContractSetMarginSwitchRequest { symbol: string; tradeMode: 0 | 1; buyLeverage: string; sellLeverage: string; } ⋮---- export interface ContractSetPositionModeRequest { symbol?: string; coin?: string; mode: 0 | 3; } ⋮---- export interface ContractSetTPSLRequest { symbol: string; takeProfit?: string; stopLoss?: string; tpslMode?: 'Full' | 'Partial'; tpSize?: string; slSize?: string; tpTriggerBy?: string; slTriggerBy?: string; trailingStop?: string; activePrice?: string; tpLimitPrice?: string; slLimitPrice?: string; tpOrderType?: UMOrderType; slOrderType?: UMOrderType; /** 0-one-way, 1-buy side, 2-sell side */ positionIdx?: 0 | 1 | 2; } ⋮---- /** 0-one-way, 1-buy side, 2-sell side */ ⋮---- export interface ContractUserExecutionHistoryRequest { symbol: string; orderId?: string; startTime?: number; endTime?: number; execType?: 'Trade' | 'AdlTrade' | 'Funding' | 'BustTrade'; limit?: number; cursor?: string; } ⋮---- export interface ContractClosedPNLRequest { symbol: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface ContractWalletFundRecordRequest { startTime?: string; endTime?: string; coin?: string; walletFundType?: string; limit?: string; cursor?: string; } ================ File: src/types/request/copy-trading.ts ================ import { OrderSide } from '../shared'; import { USDCOrderType } from './usdc-shared'; ⋮---- export interface CopyTradingOrderRequest { side: OrderSide; symbol: string; orderType: USDCOrderType; price: string; qty: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: string; slTriggerBy?: string; orderLinkId?: string; } ⋮---- export interface CopyTradingTradingStopRequest { symbol: string; parentOrderId: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: string; slTriggerBy?: string; parentOrderLinkId?: string; } ⋮---- export interface CopyTradingOrderListRequest { symbol?: string; orderId?: string; orderLinkId?: string; copyTradeOrderType?: string; } ⋮---- export interface CopyTradingCancelOrderRequest { symbol: string; orderId?: string; orderLinkId?: string; } ⋮---- export interface CopyTradingCloseOrderRequest { symbol: string; orderLinkId?: string; parentOrderId?: string; parentOrderLinkId?: string; } ⋮---- export interface CopyTradingTransferRequest { transferId: string; coin: string; amount: string; fromAccountType: string; toAccountType: string; } ================ File: src/types/request/inverse.ts ================ export interface InverseOrderRequest { side: string; symbol: string; order_type: string; qty: number; price?: number; time_in_force: string; take_profit?: number; stop_loss?: number; reduce_only?: boolean; tp_trigger_by?: 'LastPrice' | 'MarkPrice' | 'IndexPrice'; sl_trigger_by?: 'LastPrice' | 'MarkPrice' | 'IndexPrice'; close_on_trigger?: boolean; order_link_id?: string; } ⋮---- export interface InverseActiveOrdersRequest { symbol: string; order_status?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface InverseCancelOrderRequest { symbol: string; order_id?: string; order_link_id?: string; } ⋮---- export interface InverseReplaceOrderRequest { order_id?: string; order_link_id?: string; symbol: string; p_r_qty?: number; p_r_price?: string; take_profit?: number; stop_loss?: number; tp_trigger_by?: string; sl_trigger_by?: string; } ⋮---- export interface InverseGetOrderRequest { order_id?: string; order_link_id?: string; symbol: string; } ⋮---- export interface InverseConditionalOrderRequest { side: string; symbol: string; order_type: string; qty: string; price?: string; base_price: string; stop_px: string; time_in_force: string; trigger_by?: string; close_on_trigger?: boolean; order_link_id?: string; } ⋮---- export interface InverseActiveConditionalOrderRequest { symbol: string; stop_order_status?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface InverseCancelConditionalOrderRequest { symbol: string; stop_order_id?: string; order_link_id?: string; } ⋮---- export interface InverseReplaceConditionalOrderRequest { stop_order_id?: string; order_link_id?: string; symbol: string; p_r_qty?: number; p_r_price?: string; p_r_trigger_price?: string; } ⋮---- export interface InverseChangePositionMarginRequest { symbol: string; margin: string; } ⋮---- export interface InverseSetTradingStopRequest { symbol: string; take_profit?: number; stop_loss?: number; trailing_stop?: number; tp_trigger_by?: string; sl_trigger_by?: string; new_trailing_active?: number; } ⋮---- export interface InverseSetLeverageRequest { symbol: string; leverage: number; leverage_only?: boolean; } ⋮---- export interface InverseGetTradeRecordsRequest { order_id?: string; symbol: string; start_time?: number; page?: number; limit?: number; order?: string; } ⋮---- export interface InverseGetClosedPnlRequest { symbol: string; start_time?: number; end_time?: number; exec_type?: string; page?: number; limit?: number; } ⋮---- export interface InverseSetSlTpPositionModeRequest { symbol: string; tp_sl_mode: 'Full' | 'Partial'; } ⋮---- export interface InverseSetMarginTypeRequest { symbol: string; is_isolated: boolean; buy_leverage: number; sell_leverage: number; } ================ File: src/types/request/linear.ts ================ import { LinearPositionIdx, linearPositionModeEnum, positionTpSlModeEnum, } from '../../constants/enum'; import { OrderSide } from '../shared'; ⋮---- export interface LinearGetOrdersRequest { order_id?: string; order_link_id?: string; symbol: string; order?: string; page?: number; limit?: number; order_status?: string; } ⋮---- export interface LinearCancelOrderRequest { symbol: string; order_id?: string; order_link_id?: string; } ⋮---- export interface LinearReplaceOrderRequest { order_id?: string; order_link_id?: string; symbol: string; p_r_qty?: number; p_r_price?: number; take_profit?: number; stop_loss?: number; tp_trigger_by?: string; sl_trigger_by?: string; } ⋮---- export interface LinearGetOrderRequest { order_id?: string; order_link_id?: string; symbol: string; } ⋮---- export type LinearOrderType = 'Limit' | 'Market'; ⋮---- export type LinearTimeInForce = | 'GoodTillCancel' | 'ImmediateOrCancel' | 'FillOrKill' | 'PostOnly'; ⋮---- export interface NewLinearOrder { side: OrderSide; symbol: string; order_type: LinearOrderType; qty: number; price?: number; time_in_force: LinearTimeInForce; take_profit?: number; stop_loss?: number; tp_trigger_by?: string; sl_trigger_by?: string; reduce_only: boolean; close_on_trigger: boolean; order_link_id?: string; position_idx?: LinearPositionIdx; } ⋮---- export interface LinearConditionalOrderRequest { side: string; symbol: string; order_type: string; qty: number; price?: number; base_price: number; stop_px: number; time_in_force: string; trigger_by?: string; close_on_trigger?: boolean; order_link_id?: string; reduce_only: boolean; take_profit?: number; stop_loss?: number; tp_trigger_by?: string; sl_trigger_by?: string; } ⋮---- export interface LinearGetConditionalOrderRequest { stop_order_id?: string; order_link_id?: string; symbol: string; stop_order_status?: string; order?: string; page?: number; limit?: number; } ⋮---- export interface LinearCancelConditionalOrderRequest { symbol: string; stop_order_id?: string; order_link_id?: string; } ⋮---- export interface LinearReplaceConditionalOrderRequest { stop_order_id?: string; order_link_id?: string; symbol: string; p_r_qty?: number; p_r_price?: number; p_r_trigger_price?: number; take_profit?: number; stop_loss?: number; tp_trigger_by?: string; sl_trigger_by?: string; } ⋮---- export interface LinearQueryConditionalOrderRequest { symbol: string; stop_order_id?: string; order_link_id?: string; } ⋮---- export interface LinearSetAutoAddMarginRequest { symbol: string; side: string; auto_add_margin: boolean; } ⋮---- export interface LinearSetMarginSwitchRequest { symbol: string; is_isolated: boolean; buy_leverage: number; sell_leverage: number; } ⋮---- export interface LinearSetPositionModeRequest { symbol: string; mode: (typeof linearPositionModeEnum)[keyof typeof linearPositionModeEnum]; } ⋮---- export interface LinearSetPositionTpSlModeRequest { symbol: string; tp_sl_mode: (typeof positionTpSlModeEnum)[keyof typeof positionTpSlModeEnum]; } ⋮---- export interface LinearSetAddReduceMarginRequest { symbol: string; side: string; margin: number; } ⋮---- export interface LinearSetUserLeverageRequest { symbol: string; buy_leverage: number; sell_leverage: number; } ⋮---- export interface LinearSetTradingStopRequest { symbol: string; side: string; take_profit?: number; stop_loss?: number; trailing_stop?: number; tp_trigger_by?: string; sl_trigger_by?: string; sl_size?: number; tp_size?: number; position_idx?: 0 | 1 | 2; } ⋮---- export interface LinearGetTradeRecordsRequest { symbol: string; start_time?: number; end_time?: number; exec_type?: string; page?: number; limit?: number; } ⋮---- export interface LinearGetHistoryTradeRecordsRequest { symbol: string; start_time?: number; end_time?: number; exec_type?: string; page?: number; limit?: number; page_token?: string; } ⋮---- export interface LinearGetClosedPnlRequest { symbol: string; start_time?: number; end_time?: number; exec_type?: string; page?: number; limit?: number; } ⋮---- export interface LinearSetRiskLimitRequest { symbol: string; side: string; risk_id: number; } ================ File: src/types/request/unified-margin.ts ================ import { KlineIntervalV3, OrderSide } from '../shared'; import { USDCOrderFilter, USDCTimeInForce } from './usdc-shared'; ⋮---- export type UMCategory = 'linear' | 'inverse' | 'option'; export type UMOrderType = 'Limit' | 'Market'; export type UMDirection = 'prev' | 'next'; ⋮---- export interface UMCandlesRequest { category: UMCategory; symbol: string; interval: KlineIntervalV3; start: number; end: number; limit?: number; } ⋮---- export interface UMInstrumentInfoRequest { category: UMCategory; symbol?: string; baseCoin?: string; limit?: string; cursor?: string; } ⋮---- export interface UMFundingRateHistoryRequest { category: UMCategory; symbol: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface UMOptionDeliveryPriceRequest { category: UMCategory; symbol?: string; baseCoin?: string; direction?: UMDirection; limit?: string; cursor?: string; } ⋮---- export interface UMPublicTradesRequest { category: UMCategory; symbol: string; baseCoin?: string; optionType?: 'Call' | 'Put'; limit?: string; } ⋮---- export interface UMOpenInterestRequest { category: UMCategory; symbol: string; interval: '5min' | '15min' | '30min' | '1h' | '4h' | '1d'; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface UMOrderRequest { category: UMCategory; symbol: string; side: OrderSide; positionIdx?: '0' | '1' | '2'; orderType: UMOrderType; qty: string; price?: string; basePrice?: string; triggerPrice?: string; triggerBy?: string; iv?: string; timeInForce: USDCTimeInForce; orderLinkId?: string; takeProfit?: number; stopLoss?: number; tpTriggerBy?: string; slTriggerBy?: string; reduceOnly?: boolean; closeOnTrigger?: boolean; mmp?: boolean; } ⋮---- export interface UMModifyOrderRequest { category: UMCategory; symbol: string; orderId?: string; orderLinkId?: string; iv?: string; triggerPrice?: string; qty?: string; price?: string; takeProfit?: number; stopLoss?: number; tpTriggerBy?: string; slTriggerBy?: string; triggerBy?: string; } ⋮---- export interface UMCancelOrderRequest { category: UMCategory; symbol: string; orderId?: string; orderLinkId?: string; orderFilter?: USDCOrderFilter; } ⋮---- export interface UMActiveOrdersRequest { category: UMCategory; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderFilter?: USDCOrderFilter; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMHistoricOrdersRequest { category: UMCategory; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderStatus?: string; orderFilter?: USDCOrderFilter; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMBatchOrder { symbol: string; side: OrderSide; positionIdx?: '0'; orderType: UMOrderType; qty: string; price?: string; iv?: string; timeInForce: USDCTimeInForce; orderLinkId?: string; reduceOnly?: boolean; closeOnTrigger?: boolean; mmp?: boolean; } ⋮---- export interface UMBatchOrderReplace { symbol: string; orderId?: string; orderLinkId?: string; iv?: string; qty?: string; price?: string; } ⋮---- export interface UMBatchOrderCancel { symbol: string; orderId?: string; orderLinkId?: string; } ⋮---- export interface UMCancelAllOrdersRequest { category: UMCategory; baseCoin?: string; settleCoin?: string; symbol?: string; orderFilter?: USDCOrderFilter; } ⋮---- export interface UMPositionsRequest { category: UMCategory; symbol?: string; baseCoin?: string; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMSetTPSLRequest { category: UMCategory; symbol: string; takeProfit?: string; stopLoss?: string; trailingStop?: string; tpTriggerBy?: string; slTriggerBy?: string; activePrice?: string; slSize?: string; tpSize?: string; positionIdx?: '0'; } ⋮---- export interface UM7DayTradingHistoryRequest { category: UMCategory; symbol: string; baseCoin?: string; orderId?: string; orderLinkId?: string; startTime?: number; endTime?: number; direction?: UMDirection; limit?: number; cursor?: string; execType?: string; } ⋮---- export interface UMOptionsSettlementHistoryRequest { category: UMCategory; symbol?: string; expDate?: string; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMPerpSettlementHistoryRequest { category: UMCategory; symbol?: string; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMTransactionLogRequest { category: UMCategory; currency: string; baseCoin?: string; type?: string; startTime?: number; endTime?: number; direction?: UMDirection; limit?: number; cursor?: string; } ⋮---- export interface UMExchangeCoinsRequest { fromCoin?: string; toCoin?: string; } ⋮---- export interface UMBorrowHistoryRequest { currency: string; startTime?: number; endTime?: number; direction?: UMDirection; limit?: number; cursor?: string; } ================ File: src/types/request/usdc-options.ts ================ import { OrderSide } from '../shared'; import { USDCAPICategory, USDCOrderType, USDCTimeInForce } from './usdc-shared'; ⋮---- export interface USDCOptionsContractInfoRequest { symbol?: string; status?: 'WAITING_ONLINE' | 'ONLINE' | 'DELIVERING' | 'OFFLINE'; baseCoin?: string; direction?: string; limit?: string; cursor?: string; } ⋮---- export interface USDCOptionsDeliveryPriceRequest { symbol?: string; baseCoin?: string; direction?: string; limit?: string; cursor?: string; } ⋮---- export interface USDCOptionsRecentTradesRequest { category: USDCAPICategory; symbol?: string; baseCoin?: string; optionType?: 'Call' | 'Put'; limit?: string; } ⋮---- export interface USDCOptionsHistoricalVolatilityRequest { baseCoin?: string; period?: string; startTime?: string; endTime?: string; } ⋮---- export interface USDCOptionsOrderRequest { symbol: string; orderType: USDCOrderType; side: OrderSide; orderPrice?: string; orderQty: string; iv?: string; timeInForce?: USDCTimeInForce; orderLinkId?: string; reduceOnly?: boolean; } ⋮---- export interface USDCOptionsModifyOrderRequest { symbol: string; orderId?: string; orderLinkId?: string; orderPrice?: string; orderQty?: string; iv?: string; } ⋮---- export interface USDCOptionsCancelOrderRequest { symbol: string; orderId?: string; orderLinkId?: string; } ⋮---- export interface USDCOptionsCancelAllOrdersRequest { symbol?: string; baseCoin?: string; } ⋮---- export interface USDCOptionsActiveOrdersRealtimeRequest { orderId?: string; orderLinkId?: string; symbol?: string; baseCoin?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface USDCOptionsActiveOrdersRequest { category: 'OPTION'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface USDCOptionsHistoricOrdersRequest { category: 'OPTION'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderStatus?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface USDCOptionsOrderExecutionRequest { category: 'OPTION'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; startTime?: string; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface USDCOptionsDeliveryHistoryRequest { symbol: string; expDate?: string; direction?: string; limit?: string; cursor?: string; } ⋮---- export interface USDCOptionsPositionsInfoExpiryRequest { expDate?: string; direction?: string; limit?: string; cursor?: string; } ⋮---- export interface USDCOptionsModifyMMPRequest { currency: string; windowMs: number; frozenPeriodMs: number; qtyLimit: string; deltaLimit: string; } ================ File: src/types/request/usdc-perp.ts ================ import { OrderSide } from '../shared'; import { USDCAPICategory, USDCOrderFilter, USDCOrderType, USDCTimeInForce, } from './usdc-shared'; ⋮---- export interface USDCOpenInterestRequest { symbol: string; period: string; limit?: number; } ⋮---- export interface USDCLast500TradesRequest { category: USDCAPICategory; symbol?: string; baseCoin?: string; limit?: string; } ⋮---- export interface USDCSymbolDirectionLimit { symbol?: string; direction?: string; limit?: string; } ⋮---- export interface USDCSymbolDirectionLimitCursor { symbol?: string; direction?: string; limit?: string; cursor?: string; } ⋮---- export interface USDCPerpOrderRequest { symbol: string; orderType: USDCOrderType; orderFilter: USDCOrderFilter; side: OrderSide; orderPrice?: string; orderQty: string; timeInForce?: USDCTimeInForce; orderLinkId?: string; reduceOnly?: boolean; closeOnTrigger?: boolean; takeProfit?: string; stopLoss?: string; tptriggerby?: string; slTriggerBy?: string; basePrice?: string; triggerPrice?: string; triggerBy?: string; mmp?: boolean; } ⋮---- export interface USDCPerpModifyOrderRequest { symbol: string; orderFilter: USDCOrderFilter; orderId?: string; orderLinkId?: string; orderPrice?: string; orderQty?: string; takeProfit?: string; stopLoss?: string; tptriggerby?: string; slTriggerBy?: string; triggerPrice?: string; } ⋮---- export interface USDCPerpCancelOrderRequest { symbol: string; orderFilter: USDCOrderFilter; orderId?: string; orderLinkId?: string; } ⋮---- export interface USDCPerpActiveOrdersRequest { category: 'PERPETUAL'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderFilter?: USDCOrderFilter; direction?: string; limit?: number; cursor?: string; } ⋮---- export interface USDCPerpHistoricOrdersRequest { category: 'PERPETUAL'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderStatus?: string; orderFilter?: USDCOrderFilter; direction?: string; limit?: number; cursor?: string; } ================ File: src/types/request/usdc-shared.ts ================ export type USDCAPICategory = 'PERPETUAL' | 'OPTION'; ⋮---- export type USDCOrderType = 'Limit' | 'Market'; ⋮---- export type USDCTimeInForce = | 'GoodTillCancel' | 'ImmediateOrCancel' | 'FillOrKill' | 'PostOnly'; ⋮---- export type USDCOrderFilter = 'Order' | 'StopOrder'; ⋮---- export interface USDCKlineRequest { symbol: string; period: string; startTime: number; limit?: string; } ⋮---- export interface USDCTransactionLogRequest { type: string; baseCoin?: string; startTime?: string; endTime?: string; direction?: string; limit?: string; cursor?: string; category?: USDCAPICategory; } ⋮---- export interface USDCPositionsRequest { category: USDCAPICategory; symbol?: string; baseCoin?: string; expDate?: string; direction?: string; limit?: string; cursor?: string; } ================ File: src/types/request/v5-broker.ts ================ export interface GetExchangeBrokerEarningsParamsV5 { bizType?: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; begin?: string; end?: string; uid?: string; limit?: number; cursor?: string; } ⋮---- export interface GetBrokerSubAccountDepositsV5 { id?: string; txID?: string; subMemberId?: string; coin?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface IssueVoucherParamsV5 { accountId: string; awardId: string; specCode: string; amount: string; brokerId: string; } ⋮---- export interface GetBrokerIssuedVoucherParamsV5 { accountId: string; awardId: string; specCode: string; withUsedAmount?: boolean; } ================ File: src/types/request/v5-p2p-trading.ts ================ export interface GetP2PAccountCoinsBalanceParamsV5 { memberId?: string; accountType: string; coin?: string; withBonus?: 0 | 1; } ⋮---- export interface GetP2POnlineAdsParamsV5 { tokenId: string; currencyId: string; side: '0' | '1'; // 0: buy; 1: sell page?: string; size?: string; } ⋮---- side: '0' | '1'; // 0: buy; 1: sell ⋮---- export interface P2PTradingPreferenceSetV5 { hasUnPostAd?: 0 | 1; isKyc?: 0 | 1; isEmail?: 0 | 1; isMobile?: 0 | 1; hasRegisterTime?: 0 | 1; registerTimeThreshold?: number; orderFinishNumberDay30?: number; completeRateDay30?: string; nationalLimit?: string; hasOrderFinishNumberDay30?: 0 | 1; hasCompleteRateDay30?: 0 | 1; hasNationalLimit?: 0 | 1; } ⋮---- export interface CreateP2PAdParamsV5 { tokenId: string; currencyId: string; side: '0' | '1'; // 0: buy; 1: sell priceType: '0' | '1'; // 0: fixed rate; 1: floating rate premium: string; price: string; minAmount: string; maxAmount: string; remark: string; tradingPreferenceSet: P2PTradingPreferenceSetV5; paymentIds: string[]; quantity: string; paymentPeriod: string; itemType: 'ORIGIN' | 'BULK'; } ⋮---- side: '0' | '1'; // 0: buy; 1: sell priceType: '0' | '1'; // 0: fixed rate; 1: floating rate ⋮---- export interface UpdateP2PAdParamsV5 { id: string; priceType: '0' | '1'; // 0: fixed rate; 1: floating rate premium: string; price: string; minAmount: string; maxAmount: string; remark: string; tradingPreferenceSet: P2PTradingPreferenceSetV5; paymentIds: string[]; actionType: 'MODIFY' | 'ACTIVE'; // MODIFY: modify adv; ACTIVE: reonline adv quantity: string; paymentPeriod: string; itemType?: 'ORIGIN' | 'BULK'; subsidyAd?: boolean; securityRiskToken?: string; } ⋮---- priceType: '0' | '1'; // 0: fixed rate; 1: floating rate ⋮---- actionType: 'MODIFY' | 'ACTIVE'; // MODIFY: modify adv; ACTIVE: reonline adv ⋮---- export interface GetP2PPersonalAdsParamsV5 { itemId?: string; status?: '1' | '2'; // 1: Sold Out; 2: Available side?: '0' | '1'; // 0: buy; 1: sell tokenId?: string; page?: string; size?: string; currencyId?: string; } ⋮---- status?: '1' | '2'; // 1: Sold Out; 2: Available side?: '0' | '1'; // 0: buy; 1: sell ⋮---- export interface GetP2POrdersParamsV5 { status?: number; beginTime?: string; endTime?: string; tokenId?: string; side?: number[]; page: number; size: number; } ⋮---- export interface GetP2PPendingOrdersParamsV5 { status?: number; beginTime?: string; endTime?: string; tokenId?: string; side?: number[]; page: number; size: number; } ⋮---- export interface MarkP2POrderAsPaidParamsV5 { orderId: string; paymentType: string; paymentId: string; } ⋮---- export interface SendP2POrderMessageParamsV5 { message: string; contentType: string; orderId: string; msgUuid?: string; fileName?: string; } ⋮---- export interface GetP2POrderMessagesParamsV5 { orderId: string; currentPage?: string; size: string; } ⋮---- export interface GetP2PCounterpartyUserInfoParamsV5 { originalUid: string; orderId: string; } ================ File: src/types/request/v5-pre-upgrade.ts ================ import { ExecTypeV5 } from '../shared-v5'; ⋮---- export interface GetPreUpgradeOrderHistoryParamsV5 { category: 'linear' | 'inverse'; symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; orderFilter?: 'Order' | 'StopOrder'; orderStatus?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetPreUpgradeTradeHistoryParamsV5 { category: 'linear' | 'inverse'; symbol?: string; orderId?: string; orderLinkId?: string; baseCoin?: string; startTime?: number; endTime?: number; execType?: ExecTypeV5; limit?: number; cursor?: string; } ⋮---- export interface GetPreUpgradeClosedPnlParamsV5 { category: 'linear' | 'inverse'; symbol: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetPreUpgradeTransactionLogParamsV5 { category: 'linear' | 'option'; baseCoin?: string; type?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetPreUpgradeOptionDeliveryRecordParamsV5 { category: 'option'; symbol?: string; expDate?: string; limit?: number; cursor?: string; } ⋮---- export interface GetPreUpgradeUSDCSessionParamsV5 { category: 'linear'; symbol?: string; limit?: number; cursor?: string; } ================ File: src/types/request/v5-spreadtrading.ts ================ export interface GetSpreadInstrumentsInfoParamsV5 { symbol?: string; baseCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface SubmitSpreadOrderParamsV5 { symbol: string; side: 'Buy' | 'Sell'; orderType: 'Limit' | 'Market'; qty: string; price: string; orderLinkId: string; timeInForce: 'IOC' | 'FOK' | 'GTC' | 'PostOnly'; } ⋮---- export interface AmendSpreadOrderParamsV5 { symbol: string; orderId?: string; orderLinkId?: string; qty?: string; price?: string; } ⋮---- export interface GetSpreadOpenOrdersParamsV5 { symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; limit?: number; cursor?: string; } export interface GetSpreadOrderHistoryParamsV5 { symbol?: string; baseCoin?: string; orderId?: string; orderLinkId?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetSpreadTradeHistoryParamsV5 { symbol?: string; orderId?: string; orderLinkId?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ================ File: src/types/response/account-asset.ts ================ export interface UniversalTransferCreateResponse { transferId: string; } ⋮---- export interface UniversalTransferListResponseV3 { list: { transferId: string; coin: string; amount: string; timestamp: string; status: string; fromAccountType: string; toAccountType: string; fromMemberId: string; toMemberId: string; }[]; nextPageCursor: string; } ⋮---- export interface QueryInternalTransferSResponseV3 { list: { transferId: string; coin: string; amount: string; fromAccountType: string; toAccountType: string; timestamp: string; status: string; }[]; nextPageCursor: string; } ⋮---- export interface SubAccountTransferResponseV3 { list: { transferId: string; coin: string; amount: string; memberId: number; subMemberId: number; timestamp: string; status: string; type: 'IN' | 'OUT'; }[]; nextPageCursor: string; } ⋮---- export interface AccountCoinBalanceResponseV3 { accountType: string; bizType: number; accountId: string; memberId: string; balance: { coin: string; walletBalance: string; transferBalance: string; bonus: string; }; } ⋮---- export interface AccountCoinBalancesResponseV3 { accountType: string; memberId: string; balance: { coin: string; walletBalance: string; transferBalance: string; bonus: string; }[]; } ⋮---- export interface AssetInfoResponseV3 { spot: { status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; assets: { coin: string; frozen: string; free: string; withdraw: string; }[]; }; } ⋮---- interface SupportedDepositV3 { coin: string; chain: string; coinShowName: string; chainType: string; blockConfirmNumber: number; minDepositAmount: string; } ⋮---- export interface SupportedDepositListResponseV3 { configList: SupportedDepositV3[]; nextPageCursor: string; } ⋮---- interface DepositRecordV3 { coin: string; chain: string; amount: string; txID: string; status: number; toAddress: string; tag: string; depositFee: string; successAt: string; confirmations: string; txIndex: string; blockHash: string; } ⋮---- export interface DepositRecordQueryResponseV3 { rows: DepositRecordV3[]; nextPageCursor: string; } ⋮---- export interface WithdrawRecordsQueryResponseV3 { rows: { coin: string; chain: string; amount: string; txID: string; status: number; toAddress: string; tag: string; withdrawFee: string; createTime: string; updateTime: string; withdrawId: string; withdrawType: number; }[]; nextPageCursor: string; } ⋮---- export interface CoinInfoV3 { name: string; coin: string; remainAmount: string; chains: { chainType: string; confirmation: string; withdrawFee: string; depositMin: string; withdrawMin: string; chain: string; chainDeposit: string; chainWithdraw: string; minAccuracy: string; }[]; } ⋮---- export interface CoinInfoQueryResponseV3 { rows: CoinInfoV3[]; } ⋮---- export interface DepositAddressChainV3 { chainType: string; addressDeposit: string; tagDeposit: string; chain: string; } ⋮---- export interface DepositAddressResponseV3 { coin: string; chains: DepositAddressChainV3[]; } ⋮---- export interface CreateSubMemberResponseV3 { uid: number; username: string; memberType: 1 | 6; switch: 0 | 1; note: string; } ⋮---- export interface CreateSubAPIKeyResponseV3 { id: string; note: string; apiKey: string; readOnly: string; secret: string; permissions: { ContractTrade: string[]; Spot: string[]; Wallet: string[]; Options: string[]; Derivatives: string[]; CopyTrading: string[]; BlockTrade: string[]; Exchange: string[]; NFT: string[]; }; } ⋮---- export interface SubMemberV3 { uid: string; username: string; memberType: 1 | 6; status: 1 | 2 | 4; remark: string; } ⋮---- export interface SubMemberResponseV3 { subMembers: SubMemberV3[]; } ⋮---- export interface APIKeyInfoV3 { id: string; note: string; apiKey: string; readOnly: string; secret: string; permissions: { ContractTrade: string[]; Spot: string[]; Wallet: string[]; Options: string[]; Derivatives: string[]; CopyTrading: string[]; BlockTrade: string[]; Exchange: string[]; NFT: string[]; }; ips: string[]; type: number; deadlineDay: number; expiredAt: string; createdAt: string; unified: number; uta: number; userID: number; inviterID: number; vipLevel: string; mktMakerLevel: string; affiliateID: number; } ================ File: src/types/response/contract.ts ================ /* eslint-disable @typescript-eslint/no-explicit-any */ export interface PaginatedResult { nextPageCursor: string; list: TList[]; } export interface ContractListResult { category: string; list: TList[]; } ⋮---- export interface ContractHistoricOrder { symbol: string; orderId: string; orderLinkId: string; side: string; orderType: string; price: string; iv: string; qty: string; timeInForce: string; orderStatus: string; positionIdx: number; lastPriceOnCreated: string; createdTime: string; updatedTime: string; cancelType: string; rejectReason: string; stopOrderType: string; triggerDirection: number; triggerBy: string; triggerPrice: string; cumExecValue: string; cumExecFee: string; cumExecQty: string; leavesValue: string; leavesQty: string; takeProfit: string; stopLoss: string; tpslMode: string; tpLimitPrice: string; slLimitPrice: string; tpTriggerBy: string; slTriggerBy: string; reduceOnly: boolean; closeOnTrigger: boolean; blockTradeId: string; smpType: string; smpGroup: number; smpOrderId: string; } ⋮---- export interface ContractSymbolTicker { symbol: string; bidPrice: string; askPrice: string; lastPrice: string; lastTickDirection: string; prevPrice24h: string; price24hPcnt: string; highPrice24h: string; lowPrice24h: string; prevPrice1h: string; markPrice: string; indexPrice: string; openInterest: string; turnover24h: string; volume24h: string; fundingRate: string; nextFundingTime: string; predictedDeliveryPrice: string; basisRate: string; deliveryFeeRate: string; deliveryTime: string; } ================ File: src/types/response/shared.ts ================ export interface SymbolWalletBalance { equity: number; available_balance: number; used_margin: number; order_margin: number; position_margin: number; occ_closing_fee: number; occ_funding_fee: number; wallet_balance: number; realised_pnl: number; unrealised_pnl: number; cum_realised_pnl: number; given_cash: number; service_cash: number; } ⋮---- export interface WalletBalances { [symbol: string]: SymbolWalletBalance | undefined; } ================ File: src/types/response/spot.ts ================ export interface SpotBalance { coin: string; coinId: string; coinName: string; total: string; free: string; locked: string; } ⋮---- export interface SpotBalances { balances: SpotBalance[]; } ⋮---- export interface SpotLastPrice { symbol: string; price: string; } ================ File: src/types/response/unified-margin.ts ================ // eslint-disable-next-line @typescript-eslint/no-explicit-any export interface UMPaginatedResult { nextPageCursor: string; category: string; list: List[]; } ⋮---- export interface UMLeverageFilter { minLeverage: string; maxLeverage: string; leverageStep: string; } ⋮---- export interface UMPriceFilter { minPrice: string; maxPrice: string; tickSize: string; } ⋮---- export interface UMLotSizeFilter { maxTradingQty: string; minTradingQty: string; qtyStep: string; } ⋮---- export interface UMInstrumentInfo { symbol: string; contractType: string; status: string; baseCoin: string; quoteCoin: string; launchTime: string; deliveryTime: string; deliveryFeeRate: string; priceScale: string; leverageFilter: UMLeverageFilter; priceFilter: UMPriceFilter; lotSizeFilter: UMLotSizeFilter; } ⋮---- export interface UMHistoricOrder { symbol: string; orderType: string; orderLinkId: string; orderId: string; stopOrderType: string; orderStatus: string; takeProfit: string; cumExecValue: string; blockTradeId: string; rejectReason: string; price: string; createdTime: number; tpTriggerBy: string; timeInForce: string; basePrice: string; leavesValue: string; updatedTime: number; side: string; triggerPrice: string; cumExecFee: string; slTriggerBy: string; leavesQty: string; closeOnTrigger: boolean; cumExecQty: string; reduceOnly: boolean; qty: string; stopLoss: string; triggerBy: string; orderIM: string; } ================ File: src/types/response/usdt-perp.ts ================ export interface PerpPosition { user_id: number; symbol: string; side: string; size: number; position_value: number; entry_price: number; liq_price: number; bust_price: number; leverage: number; auto_add_margin: number; is_isolated: boolean; position_margin: number; occ_closing_fee: number; realised_pnl: number; cum_realised_pnl: number; free_qty: number; tp_sl_mode: string; unrealised_pnl: number; deleverage_indicator: number; risk_id: number; stop_loss: number; take_profit: number; trailing_stop: number; position_idx: number; mode: string; } ⋮---- export interface PerpPositionRoot { data: PerpPosition; is_valid: boolean; } ⋮---- export interface LinearOrder { order_id: string; user_id: number; symbol: string; side: string; order_type: string; price: number; qty: number; time_in_force: string; order_status: string; last_exec_price: number; cum_exec_qty: number; cum_exec_value: number; cum_exec_fee: number; reduce_only: boolean; close_on_trigger: boolean; order_link_id: string; created_time: string; updated_time: string; take_profit: number; stop_loss: number; tp_trigger_by: string; sl_trigger_by: string; position_idx: number; } ================ File: src/types/response/v5-broker.ts ================ interface EarningDetailV5 { userId: string; bizType: 'SPOT' | 'DERIVATIVES' | 'OPTIONS' | 'CONVERT'; symbol: string; coin: string; earning: string; markupEarning: string; baseFeeEarning: string; orderId: string; execTime: string; } ⋮---- interface TotalEarningCategoryV5 { coin: string; earning: string; } ⋮---- export interface ExchangeBrokerEarningResultV5 { totalEarningCat: { spot: TotalEarningCategoryV5[]; derivatives: TotalEarningCategoryV5[]; options: TotalEarningCategoryV5[]; convert: TotalEarningCategoryV5[]; total: TotalEarningCategoryV5[]; }; details: EarningDetailV5[]; nextPageCursor: string; } ⋮---- export interface ExchangeBrokerAccountInfoV5 { subAcctQty: string; maxSubAcctQty: string; baseFeeRebateRate: { spot: string; derivatives: string; }; markupFeeRebateRate: { spot: string; derivatives: string; convert: string; }; ts: string; } ⋮---- export interface ExchangeBrokerSubAccountDepositRecordV5 { id: string; subMemberId: string; coin: string; chain: string; amount: string; txID: string; status: number; toAddress: string; tag: string; depositFee: string; successAt: string; confirmations: string; txIndex: string; blockHash: string; batchReleaseLimit: string; depositType: string; } ⋮---- export interface BrokerVoucherSpecV5 { id: string; coin: string; amountUnit: 'AWARD_AMOUNT_UNIT_USD' | 'AWARD_AMOUNT_UNIT_COIN'; productLine: string; subProductLine: string; totalAmount: { [key: string]: string; }; usedAmount: string; } ⋮---- export interface BrokerIssuedVoucherV5 { accountId: string; awardId: string; specCode: string; amount: string; isClaimed: boolean; startAt: string; endAt: string; effectiveAt: string; ineffectiveAt: string; usedAmount: string; } ================ File: src/types/response/v5-p2p-trading.ts ================ import { P2PTradingPreferenceSetV5 } from '../request/v5-p2p-trading'; ⋮---- export interface P2PCoinBalanceV5 { coin: string; transferBalance: string; walletBalance: string; bonus: string; } ⋮---- export interface P2PAccountCoinsBalanceV5 { memberId: string; accountType: string; balance: P2PCoinBalanceV5[]; } ⋮---- export interface P2POnlineAdV5 { id: string; nickName: string; tokenId: string; currencyId: string; side: string; price: string; lastQuantity: string; minAmount: string; maxAmount: string; payments: string[]; recentOrderNum: number; recentExecuteRate: number; isOnline: boolean; authTag: string[]; paymentPeriod: number; accountId: number; userId: number; priceType: number; premium: string; quantity: string; frozenQuantity: string; executedQuantity: string; remark: string; status: number; createDate: string; orderNum: string; finishNum: string; fee: string; lastLogoutTime: string; blocked: string; makerContact: boolean; symbolInfo: { id: string; exchangeId: string; orgId: string; tokenId: string; currencyId: string; status: string; lowerLimitAlarm: number; upperLimitAlarm: number; itemDownRange: string; itemUpRange: string; currencyMinQuote: string; currencyMaxQuote: string; currencyLowerMaxQuote: string; tokenMinQuote: string; tokenMaxQuote: string; kycCurrencyLimit: string; itemSideLimit: string; buyFeeRate: string; sellFeeRate: string; orderAutoCancelMinute: number; orderFinishMinute: number; tradeSide: number; currency: { id: string; exchangeId: string; orgId: string; currencyId: string; scale: number; }; token: { id: string; exchangeId: string; orgId: string; tokenId: string; scale: number; sequence: number; }; buyAd: number; sellAd: number; }; tradingPreferenceSet: { hasUnPostAd: number; isKyc: number; isEmail: number; isMobile: number; hasRegisterTime: number; registerTimeThreshold: number; orderFinishNumberDay30: number; completeRateDay30: number; nationalLimit: number; hasOrderFinishNumberDay30: number; hasCompleteRateDay30: number; hasNationalLimit: number; }; version: number; authStatus: number; recommend: boolean; recommendTag: string; userType: string; itemType: string; } ⋮---- export interface P2POnlineAdsResponseV5 { count: number; items: P2POnlineAdV5[]; } ⋮---- export interface P2PCreateAdResponseV5 { itemId: string; securityRiskToken: string; riskTokenType: string; riskVersion: string; needSecurityRisk: boolean; } ⋮---- export interface P2PPaymentTermV5 { id: string; realName: string; paymentType: number; bankName: string; branchName: string; accountNo: string; qrcode: string; visible: number; payMessage: string; firstName: string; lastName: string; secondLastName: string; clabe: string; debitCardNumber: string; mobile: string; businessName: string; concept: string; paymentExt1: string; paymentExt2: string; paymentExt3: string; paymentExt4: string; paymentExt5: string; paymentExt6: string; paymentTemplateVersion: number; paymentConfig: { paymentType: number; paymentName: string; paymentDialect: string; }; realNameVerified: boolean; } ⋮---- export interface P2PAdDetailV5 { id: string; accountId: string; userId: string; nickName: string; tokenId: string; tokenName: string; currencyId: string; side: number; priceType: number; price: string; premium: string; lastQuantity: string; quantity: string; frozenQuantity: string; executedQuantity: string; minAmount: string; maxAmount: string; remark: string; status: number; createDate: string; payments: string[]; orderNum: number; finishNum: number; recentOrderNum: number; recentExecuteRate: number; fee: string; isOnline: boolean; lastLogoutTime: string; symbolInfo: { id: string; exchangeId: string; orgId: string; tokenId: string; currencyId: string; status: number; lowerLimitAlarm: number; upperLimitAlarm: number; itemDownRange: string; itemUpRange: string; currencyMinQuote: string; currencyMaxQuote: string; currencyLowerMaxQuote: string; tokenMinQuote: string; tokenMaxQuote: string; kycCurrencyLimit: string; itemSideLimit: number; buyFeeRate: string; sellFeeRate: string; orderAutoCancelMinute: number; orderFinishMinute: number; tradeSide: number; currency: { id: string; exchangeId: string; orgId: string; currencyId: string; scale: number; }; token: { id: string; exchangeId: string; orgId: string; tokenId: string; scale: number; sequence: number; }; buyAd: { paymentPeriods: number[]; }; sellAd: { paymentPeriods: number[]; }; }; tradingPreferenceSet: P2PTradingPreferenceSetV5; paymentTerms: P2PPaymentTermV5[]; version: number; updateDate: string; feeRate: string; paymentPeriod: number; itemType: string; } ⋮---- export interface P2PPersonalAdsResponseV5 { count: number; items: P2PAdDetailV5[]; hiddenFlag: boolean; } ⋮---- export interface P2POrderExtensionV5 { isDelayWithdraw: boolean; delayTime: string; startTime: string; } ⋮---- export interface P2POrderV5 { id: string; side: number; tokenId: string; orderType: string; amount: string; currencyId: string; price: string; notifyTokenQuantity?: string; notifyTokenId?: string; fee: string; targetNickName: string; targetUserId: string; status: number; selfUnreadMsgCount: string; createDate: string; transferLastSeconds: string; appealLastSeconds: string; userId: string; sellerRealName: string; buyerRealName: string; judgeInfo: { autoJudgeUnlockTime: string; dissentResult: string; preDissent: string; postDissent: string; }; unreadMsgCount: string; extension: P2POrderExtensionV5; bulkOrderFlag: boolean; } ⋮---- export interface P2POrdersResponseV5 { count: number; items: P2POrderV5[]; } ⋮---- export interface P2PPaymentConfigItemV5 { view: boolean; name: string; label: string; placeholder: string; type: string; maxLength: string; required: boolean; } ⋮---- export interface P2PPaymentConfigV5 { paymentType: string; checkType: number; sort: number; paymentName: string; addTips: string; itemTips: string; online: number; items: P2PPaymentConfigItemV5[]; } ⋮---- export interface P2PPaymentTermDetailV5 { id: string; realName: string; paymentType: number; bankName: string; branchName: string; accountNo: string; qrcode: string; visible: number; payMessage: string; firstName: string; lastName: string; secondLastName: string; clabe: string; debitCardNumber: string; mobile: string; businessName: string; concept: string; online: string; paymentExt1: string; paymentExt2: string; paymentExt3: string; paymentExt4: string; paymentExt5: string; paymentExt6: string; paymentTemplateVersion: number; paymentConfigVo: P2PPaymentConfigV5; ruPaymentPrompt: boolean; } ⋮---- export interface P2PAppraiseInfoV5 { anonymous: string; appraiseContent: string; appraiseId: string; appraiseType: string; modifyFlag: string; updateDate: string; } ⋮---- export interface P2PJudgeInfoV5 { autoJudgeUnlockTime: string; dissentResult: string; preDissent: string; postDissent: string; } ⋮---- export interface P2POrderDetailV5 { id: string; side: number; itemId: string; accountId: string; userId: string; nickName: string; makerUserId: string; targetAccountId: string; targetUserId: string; targetNickName: string; targetFirstName: string; targetSecondName: string; targetUserAuthStatus: number; targetConnectInformation: string; payerRealName: string; sellerRealName: string; buyerRealName: string; tokenId: string; tokenName: string; currencyId: string; price: string; quantity: string; amount: string; payCode: string; paymentType: number; transferDate: string; status: number; createDate: string; paymentTermList: P2PPaymentTermDetailV5[]; remark: string; transferLastSeconds: string; recentOrderNum: number; recentExecuteRate: number; appealLastSeconds: string; appealContent: string; appealType: number; appealNickName: string; canAppeal: string; totalAppealTimes: string; appealedTimes: string; paymentTermResult: P2PPaymentTermDetailV5; orderFinishMinute: number; confirmedPayTerm: P2PPaymentTermDetailV5; makerFee: string; takerFee: string; fee: string; showContact: boolean; tokenBalance: string; fiatBalance: string; unreadMsgCount: string; updateDate: string; extension: P2POrderExtensionV5; selfUnreadMsgCount: string; judgeType: string; canReport: boolean; canReportDisagree: boolean; canReportType: string[]; canReportDisagreeType: string[]; appraiseStatus: string; appraiseInfo: P2PAppraiseInfoV5; canReportDisagreeTypes: string[]; canReportTypes: string[]; orderType: string; middleToken: string; beforePrice: string; beforeQuantity: string; beforeToken: string; alternative: string; appealUserId: string; notifyTokenId: string; notifyTokenQuantity: string; cancelResponsible: string; chainType: string; chainAddress: string; tradeHashCode: string; estimatedGasFee: string; gasFeeTokenId: string; tradingFeeTokenId: string; onChainInfo: string; transactionId: string; displayRefund: string; chainWithdrawLastSeconds: string; chainTransferLastSeconds: string; orderSource: string; cancelReason: string; sellerCancelExamineRemainTime: string; needSellerExamineCancel: boolean; couponCurrencyAmount: string; totalCurrencyAmount: string; usedCoupon: boolean; couponTokenId: string; couponQuantity: string; completedOrderAppealCount: number; totalCompletedOrderAppealCount: number; realOrderStatus: number; appealVersion: number; judgeInfo: P2PJudgeInfoV5; helpType: string; appealFlowStatus: string; appealSubStatus: string; bulkOrderFlag: boolean; targetUserType: string; targetUserDisplays: string[]; appealProcessChangeFlag: boolean; appealNegotiationNode: number; } ⋮---- export interface P2POrderMessageV5 { id: string; message: string; userId: string; msgType: number; msgCode: number; createDate: string; contentType: string; orderId: string; msgUuid: string; nickName: string; fileName: string; accountId: string; isRead: number; read: number; roleType: string; onlyForCustomer: number; } ⋮---- export interface P2PUserInfoV5 { nickName: string; defaultNickName: boolean; isOnline: boolean; kycLevel: string; email: string; mobile: string; lastLogoutTime: string; recentRate: string; totalFinishCount: number; totalFinishSellCount: number; totalFinishBuyCount: number; recentFinishCount: number; averageReleaseTime: string; averageTransferTime: string; accountCreateDays: number; firstTradeDays: number; realName: string; recentTradeAmount: string; totalTradeAmount: string; registerTime: string; authStatus: number; kycCountryCode: string; blocked: string; goodAppraiseRate: string; goodAppraiseCount: number; badAppraiseCount: number; accountId: number; paymentCount: number; contactCount: number; vipLevel: number; userCancelCountLimit: number; paymentRealNameUneditable: boolean; userId: string; realNameEn: string; } ⋮---- export interface P2PCounterpartyUserInfoV5 { nickName: string; defaultNickName: boolean; whiteFlag: number; contactConfig: boolean; isOnline: boolean; email: string; mobile: string; kycLevel: number; lastLogoutTime: string; recentRate: number; totalFinishCount: number; totalFinishSellCount: number; totalFinishBuyCount: number; recentFinishCount: number; averageReleaseTime: string; averageTransferTime: string; accountCreateDays: number; firstTradeDays: number; realName: string; recentTradeAmount: string; totalTradeAmount: string; executeNum: number; orderNum: number; hasUnPostAd: number; registerTime: string; authStatus: number; kycCountryCode: string; blocked: string; goodAppraiseRate: string; goodAppraiseCount: number; badAppraiseCount: number; accountId: string; paymentCount: number; contactCount: number; realNameMask: string; vipLevel: number; vipProfit: []; userTag: []; userCancelCountLimit: number; paymentRealNameUneditable: boolean; lostRoleAffected: boolean; userCurPrivilege: string[]; userType: string; userId: string; realNameEn: string; canSubOnline: boolean; curPrivilegeInfo: []; openApiSwitch: number; } ⋮---- export interface P2PUserPaymentV5 { id: string; realName: string; paymentType: string; bankName: string; branchName: string; accountNo: string; qrcode: string; visible: number; payMessage: string; firstName: string; lastName: string; secondLastName: string; clabe: string; debitCardNumber: string; mobile: string; businessName: string; concept: string; online: string; countNo: string; paymentExt1: string; paymentExt2: string; paymentExt3: string; paymentExt4: string; paymentExt5: string; paymentExt6: string; paymentTemplateVersion: number; hasPaymentTemplateChanged: boolean; paymentConfigVo: P2PPaymentConfigV5; realNameVerified: boolean; channel: string; currencyBalance: string[]; } ================ File: src/types/response/v5-preupgrade.ts ================ export interface PreUpgradeTransaction { symbol: string; category: string; side: 'Buy' | 'Sell' | 'None'; transactionTime: string; type: string; qty: string; size: string; currency: 'USDC' | 'USDT' | 'BTC' | 'ETH'; tradePrice: string; funding: string; fee: string; cashFlow: string; change: string; cashBalance: string; feeRate: string; bonusChange: string; tradeId: string; orderId: string; orderLinkId: string; extraFees: string; } ⋮---- export interface PreUpgradeOptionsDelivery { deliveryTime: number; symbol: string; side: 'Buy' | 'Sell'; position: string; deliveryPrice: string; strike: string; fee: string; deliveryRpl: string; } ⋮---- export interface PreUpgradeUSDCSessionSettlement { symbol: string; side: 'Buy' | 'Sell'; size: string; sessionAvgPrice: string; markPrice: string; realisedPnl: string; createdTime: string; } ================ File: src/types/websockets/ws-api.ts ================ import { APIID, WS_KEY_MAP } from '../../util'; import { AmendOrderParamsV5, BatchAmendOrderParamsV5, BatchCancelOrderParamsV5, BatchOrderParamsV5, CancelOrderParamsV5, OrderParamsV5, } from '../request'; import { BatchAmendOrderResultV5, BatchCancelOrderResultV5, BatchCreateOrderResultV5, BatchOrdersRetExtInfoV5, OrderResultV5, } from '../response'; import { WsKey } from './ws-general'; ⋮---- // When new WS API operations are added, make sure to also update WS_API_Operations[] below export type WSAPIOperation = | 'order.create' | 'order.amend' | 'order.cancel' | 'order.create-batch' | 'order.amend-batch' | 'order.cancel-batch'; ⋮---- export type WsOperation = | 'subscribe' | 'unsubscribe' | 'auth' | 'ping' | 'pong'; ⋮---- export interface WsRequestOperationBybit { req_id: string; op: WsOperation; args?: (TWSTopic | string | number)[]; } ⋮---- export interface WSAPIRequest< TRequestParams = undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any TWSOperation extends WSAPIOperation = any, > { reqId: string; op: TWSOperation; header: { 'X-BAPI-TIMESTAMP': string; 'X-BAPI-RECV-WINDOW': string; Referer: typeof APIID; }; args: [TRequestParams]; } ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- export interface WSAPIResponse< TResponseData extends object = object, TOperation extends WSAPIOperation = WSAPIOperation, TResponseExtInfo = {}, // added as optional for batch calls > { wsKey: WsKey; /** Auto-generated */ reqId: string; retCode: 0 | number; retMsg: 'OK' | string; op: TOperation; data: TResponseData; retExtInfo: TResponseExtInfo; header?: { 'X-Bapi-Limit': string; 'X-Bapi-Limit-Status': string; 'X-Bapi-Limit-Reset-Timestamp': string; Traceid: string; Timenow: string; }; connId: string; } ⋮---- TResponseExtInfo = {}, // added as optional for batch calls ⋮---- /** Auto-generated */ ⋮---- export type Exact = { // This part says: if there's any key that's not in T, it's an error [K: string]: never; } & { [K in keyof T]: T[K]; }; ⋮---- // This part says: if there's any key that's not in T, it's an error ⋮---- /** * List of operations supported for this WsKey (connection) */ export interface WsAPIWsKeyTopicMap { [WS_KEY_MAP.v5PrivateTrade]: WSAPIOperation; } ⋮---- /** * Request parameters expected per operation */ export interface WsAPITopicRequestParamMap { 'order.create': OrderParamsV5; 'order.amend': AmendOrderParamsV5; 'order.cancel': CancelOrderParamsV5; 'order.create-batch': { category: 'option' | 'linear'; request: BatchOrderParamsV5[]; }; 'order.amend-batch': { category: 'option' | 'linear'; request: BatchAmendOrderParamsV5[]; }; 'order.cancel-batch': { category: 'option' | 'linear'; request: BatchCancelOrderParamsV5[]; }; } ⋮---- /** * Response structure expected for each operation */ export interface WsAPIOperationResponseMap { 'order.create': WSAPIResponse; 'order.amend': WSAPIResponse; 'order.cancel': WSAPIResponse; 'order.create-batch': WSAPIResponse< { list: BatchCreateOrderResultV5[] }, 'order.create-batch' > & { retExtInfo: BatchOrdersRetExtInfoV5; }; 'order.amend-batch': WSAPIResponse< { list: BatchAmendOrderResultV5[] }, 'order.amend-batch' > & { retExtInfo: BatchOrdersRetExtInfoV5; }; 'order.cancel-batch': WSAPIResponse< { list: BatchCancelOrderResultV5[] }, 'order.cancel-batch' > & { retExtInfo: BatchOrdersRetExtInfoV5; }; ping: { retCode: 0 | number; retMsg: 'OK' | string; op: 'pong'; data: [string]; connId: string; }; } ================ File: src/types/websockets/ws-confirmations.ts ================ export interface WebsocketTopicSubscriptionConfirmationEvent { op: 'subscribe'; req_id: string; conn_id: string; ret_msg: string; success: boolean; } ⋮---- export interface WebsocketSucceededTopicSubscriptionConfirmationEvent extends WebsocketTopicSubscriptionConfirmationEvent { success: true; } ⋮---- export interface WebsocketFailedTopicSubscriptionConfirmationEvent extends WebsocketTopicSubscriptionConfirmationEvent { success: false; } ================ File: src/types/websockets/ws-general.ts ================ import { RestClientOptions, WS_KEY_MAP } from '../../util'; ⋮---- /** For spot markets, spotV3 is recommended */ export type APIMarket = 'v5'; ⋮---- // Same as inverse futures export type WsPublicInverseTopic = | 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'klineV2'; ⋮---- export type WsPublicUSDTPerpTopic = | 'orderBookL2_25' | 'orderBookL2_200' | 'trade' | 'insurance' | 'instrument_info' | 'kline'; ⋮---- export type WsPublicSpotV1Topic = | 'trade' | 'realtimes' | 'kline' | 'depth' | 'mergedDepth' | 'diffDepth'; ⋮---- export type WsPublicSpotV2Topic = | 'depth' | 'kline' | 'trade' | 'bookTicker' | 'realtimes'; ⋮---- export type WsPublicTopics = | WsPublicInverseTopic | WsPublicUSDTPerpTopic | WsPublicSpotV1Topic | WsPublicSpotV2Topic | string; ⋮---- // Same as inverse futures export type WsPrivateInverseTopic = | 'position' | 'execution' | 'order' | 'stop_order'; ⋮---- export type WsPrivateUSDTPerpTopic = | 'position' | 'execution' | 'order' | 'stop_order' | 'wallet'; ⋮---- export type WsPrivateSpotTopic = | 'outboundAccountInfo' | 'executionReport' | 'ticketInfo'; ⋮---- export type WsPrivateTopic = | WsPrivateInverseTopic | WsPrivateUSDTPerpTopic | WsPrivateSpotTopic | string; ⋮---- export type WsTopic = WsPublicTopics | WsPrivateTopic; ⋮---- /** This is used to differentiate between each of the available websocket streams (as bybit has multiple websockets) */ export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; export type WsMarket = 'all'; ⋮---- export interface WSClientConfigurableOptions { /** Your API key */ key?: string; /** Your API secret */ secret?: string; /** * Set to `true` to connect to Bybit's testnet environment. * * Notes: * * - If demo trading, `testnet` should be set to false! * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. */ testnet?: boolean; /** * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo * * Only the "V5" "market" is supported here. */ demoTrading?: boolean; /** * The API group this client should connect to. The V5 market is currently used by default. * * Only the "V5" "market" is supported here. */ market?: APIMarket; /** 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; restOptions?: RestClientOptions; // eslint-disable-next-line @typescript-eslint/no-explicit-any requestOptions?: any; wsUrl?: string; /** * Default: false. * * When enabled, any calls to the subscribe method will return a promise. * Note: internally, subscription requests are sent in batches. This may not behave as expected when * subscribing to a large number of topics, especially if you are not yet connected when subscribing. */ promiseSubscribeRequests?: boolean; /** * 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 */ ⋮---- /** * Set to `true` to connect to Bybit's testnet environment. * * Notes: * * - If demo trading, `testnet` should be set to false! * - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions. */ ⋮---- /** * Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo * * Only the "V5" "market" is supported here. */ ⋮---- /** * The API group this client should connect to. The V5 market is currently used by default. * * Only the "V5" "market" is supported here. */ ⋮---- /** 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 */ ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- /** * Default: false. * * When enabled, any calls to the subscribe method will return a promise. * Note: internally, subscription requests are sent in batches. This may not behave as expected when * subscribing to a large number of topics, especially if you are not yet connected when subscribing. */ ⋮---- /** * 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. */ ⋮---- /** * 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 { market: APIMarket; pongTimeout: number; pingInterval: number; reconnectTimeout: number; recvWindow: number; authPrivateConnectionsOnConnect: boolean; authPrivateRequests: boolean; } ================ File: src/types/shared.ts ================ import { RestClientV5 } from '../rest-client-v5'; import { SpotClientV3 } from '../spot-client-v3'; ⋮---- export type RESTClient = SpotClientV3 | RestClientV5; ⋮---- export type numberInString = string; ⋮---- export type OrderSide = 'Buy' | 'Sell'; ⋮---- export type KlineInterval = | '1m' | '3m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d' | '1w' | '1M'; ⋮---- export type KlineIntervalV3 = | '1' | '3' | '5' | '15' | '30' | '60' | '120' | '240' | '360' | '720' | 'D' | 'W' | 'M'; ⋮---- export interface APIRateLimit { /** Remaining requests to this endpoint before the next reset */ remainingRequests: number; /** Max requests for this endpoint per rollowing window (before next reset) */ maxRequests: number; /** * Timestamp when the rate limit resets if you have exceeded your current maxRequests. * Otherwise, this is approximately your current timestamp. */ resetAtTimestamp: number; } ⋮---- /** Remaining requests to this endpoint before the next reset */ ⋮---- /** Max requests for this endpoint per rollowing window (before next reset) */ ⋮---- /** * Timestamp when the rate limit resets if you have exceeded your current maxRequests. * Otherwise, this is approximately your current timestamp. */ ⋮---- export interface APIResponseV3 { retCode: number; retMsg: 'OK' | string; result: TResult; retExtInfo: TExtInfo; /** * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. * * Note: * - this is primarily for V5 (or newer) APIs. * - these rate limits are per-endpoint per-account, so will not appear for public API calls */ rateLimitApi?: APIRateLimit; } ⋮---- /** * These are per-UID per-endpoint rate limits, automatically parsed from response headers if available. * * Note: * - this is primarily for V5 (or newer) APIs. * - these rate limits are per-endpoint per-account, so will not appear for public API calls */ ⋮---- export type APIResponseV3WithTime = APIResponseV3< TResult, TExtInfo > & { time: number }; /** * Request Parameter Types */ export interface SymbolParam { symbol: string; } ⋮---- export interface SymbolLimitParam { symbol: string; limit?: TLimit; } ⋮---- export interface SymbolPeriodLimitParam { symbol: string; period: string; limit?: TLimit; } ⋮---- export interface SymbolFromLimitParam { symbol: string; from?: number; limit?: number; } ⋮---- export interface SymbolIntervalFromLimitParam { symbol: string; interval: string; from: number; limit?: number; } ⋮---- export interface CoinParam { coin: string; } ⋮---- export interface WalletFundRecordsReq { start_date?: string; end_date?: string; currency?: string; coin?: string; wallet_fund_type?: string; page?: number; limit?: number; } ⋮---- export interface WithdrawRecordsReq { start_date?: string; end_date?: string; coin?: string; status?: string; page?: number; limit?: number; } ⋮---- export interface AssetExchangeRecordsReq { limit?: number; from?: number; direction?: string; } ⋮---- /** * Response types */ ⋮---- export interface LeverageFilter { min_leverage: numberInString; max_leverage: numberInString; leverage_step: numberInString; } export interface PriceFilter { min_price: numberInString; max_price: numberInString; tick_size: numberInString; } ⋮---- export interface LotSizeFilter { max_trading_qty: number; min_trading_qty: number; qty_step: number; } ⋮---- export interface SymbolInfo { name: string; alias: string; status: 'Trading' | string; base_currency: string; quote_currency: string; price_scale: number; taker_fee: numberInString; maker_fee: numberInString; leverage_filter: LeverageFilter; price_filter: PriceFilter; lot_size_filter: LotSizeFilter; } ================ File: src/spot-client-v3.ts ================ /* eslint-disable @typescript-eslint/no-explicit-any */ import { APIResponseV3, numberInString } from './types'; import { REST_CLIENT_TYPE_ENUM } from './util'; import BaseRestClient from './util/BaseRestClient'; ⋮---- /** * REST API client for newer Spot V3 APIs. * @deprecated WARNING * These endpoints are being switched off gradually and are expected to be completely turned off by the end of 2024. * They may stop working at any point before then. * Please update your code as soon as possible to use the V5 APIs instead. */ export class SpotClientV3 extends BaseRestClient ⋮---- getClientType() ⋮---- // Doesn't really matter here, since the only remaining endpoint does not require auth. ⋮---- async fetchServerTime(): Promise ⋮---- /** * * Market Data Endpoints * */ ⋮---- /** * Get merged orderbook for symbol * * This is the only known pre-V5 endpoint to still be online. */ getMergedOrderBook( symbol: string, scale?: number, limit?: number, ): Promise> ⋮---- /** * * API Data Endpoints * */ ⋮---- getServerTime(): Promise< ================ File: webpack/webpack.config.js ================ function generateConfig(name) ⋮---- // Add '.ts' and '.tsx' as resolvable extensions. ⋮---- // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ================ File: .jshintrc ================ { "esversion": 8, "asi": true, "laxbreak": true, "predef": [ "-Promise" ] } ================ File: .nvmrc ================ v22.11.0 ================ File: .prettierrc ================ { "tabWidth": 2, "singleQuote": true, "trailingComma": "all" } ================ File: index.js ================ ================ File: jest.config.ts ================ /** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ ⋮---- import type { Config } from 'jest'; ⋮---- // All imported modules in your tests should be mocked automatically // automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, bail: false, // enable to stop test when an error occur, ⋮---- // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- // Automatically clear mock calls, instances, contexts and results before every test ⋮---- // Indicates whether the coverage information should be collected while executing the test ⋮---- // An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- // The directory where Jest should output its coverage files ⋮---- // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // Indicates which provider should be used to instrument code for coverage ⋮---- // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], ⋮---- // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: undefined, ⋮---- // A path to a custom dependency extractor // dependencyExtractor: undefined, ⋮---- // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, ⋮---- // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false // }, ⋮---- // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], ⋮---- // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: undefined, ⋮---- // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: undefined, ⋮---- // A set of global variables that need to be available in all test environments // globals: {}, ⋮---- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. // maxWorkers: "50%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], ⋮---- // An array of file extensions your modules use // moduleFileExtensions: [ // "js", // "mjs", // "cjs", // "jsx", // "ts", // "tsx", // "json", // "node" // ], ⋮---- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module // moduleNameMapper: {}, ⋮---- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], ⋮---- // Activates notifications for test results // notify: false, ⋮---- // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", ⋮---- // A preset that is used as a base for Jest's configuration // preset: undefined, ⋮---- // Run tests from one or more projects // projects: undefined, ⋮---- // Use this configuration option to add custom reporters to Jest // reporters: undefined, ⋮---- // Automatically reset mock state before every test // resetMocks: false, ⋮---- // Reset the module registry before running each individual test // resetModules: false, ⋮---- // A path to a custom resolver // resolver: undefined, ⋮---- // Automatically restore mock state and implementation before every test // restoreMocks: false, ⋮---- // The root directory that Jest should scan for tests and modules within // rootDir: undefined, ⋮---- // A list of paths to directories that Jest should use to search for files in // roots: [ // "" // ], ⋮---- // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", ⋮---- // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], ⋮---- // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], ⋮---- // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, ⋮---- // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], ⋮---- // The test environment that will be used for testing // testEnvironment: "jest-environment-node", ⋮---- // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, ⋮---- // Adds a location field to test results // testLocationInResults: false, ⋮---- // The glob patterns Jest uses to detect test files ⋮---- // "**/__tests__/**/*.[jt]s?(x)", ⋮---- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], ⋮---- // This option allows the use of a custom results processor // testResultsProcessor: undefined, ⋮---- // This option allows use of a custom test runner // testRunner: "jest-circus/runner", ⋮---- // A map from regular expressions to paths to transformers // transform: undefined, ⋮---- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/", // "\\.pnp\\.[^\\/]+$" // ], ⋮---- // Prevents import esm module error from v1 axios release, issue #5026 ⋮---- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, ⋮---- // Indicates whether each individual test should be reported during the run // verbose: undefined, verbose: true, // report individual test ⋮---- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], ⋮---- // Whether to use watchman for file crawling // watchman: true, ================ File: jsconfig.json ================ { "compilerOptions": { "target": "ES6", "module": "commonjs" }, "exclude": [ "node_modules", "**/node_modules/*", "coverage", "doc", "examples/ignored/*" ] } ================ File: LICENSE.md ================ Copyright 2024 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: tea.yaml ================ --- version: 1.0.0 codeOwners: - '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54' quorum: 1 ================ File: tsconfig.build.json ================ { "extends": "./tsconfig.json", "exclude": [ "node_modules", "test", "dist", "**/*spec.ts", "**/*test.ts", "jest.config.ts" ] } ================ File: tsconfig.examples.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "distExamples", "allowJs": true }, "include": ["examples/**/*.ts", "examples/**/*.js"] } ================ File: tsconfig.json ================ { "compileOnSave": true, "compilerOptions": { "allowJs": true, "target": "es6", "module": "commonjs", "moduleResolution": "node", "declaration": true, "removeComments": false, "noEmitOnError": true, "noImplicitAny": false, "strictNullChecks": true, "skipLibCheck": true, "sourceMap": true, "esModuleInterop": true, "lib": ["es2017", "dom"], "baseUrl": ".", "outDir": "./lib" }, "include": ["src/**/*"], "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"] } ================ File: tsconfig.linting.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "target": "esnext", "rootDir": "../", "allowJs": true }, "include": [ "src/**/*.*", "test/**/*.*", "examples/**/*.*", ".eslintrc.cjs", "jest.config.ts" ] } ================ File: tsconfig.test.json ================ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./distTest", "allowJs": true }, "include": ["test/**/*.ts", "test/**/*.js"] } ================ File: examples/fasterHmacSign.ts ================ import { createHmac } from 'crypto'; ⋮---- import { DefaultLogger, RestClientV5, WebsocketClient } from '../src/index'; ⋮---- // or // import { createHmac } from 'crypto'; // import { DefaultLogger, RestClientV5, WebsocketClient } from 'bybit-api'; ⋮---- /** * Injecting a custom signMessage function. * * As of version 4.0.0 of the bybit-api Node.js/TypeScript/JavaScript * SDK for Bybit, the SDK uses the Web Crypto API for signing requests. * While it is compatible with Node and Browser environments, it is * slightly slower than using Node's native crypto module (only * available in backend Node environments). * * For latency sensitive users, you can inject the previous node crypto sign * method (or your own even faster-implementation), if this change affects you. * * This example demonstrates how to inject a custom sign function, to achieve * the same peformance as seen before the Web Crypto API was introduced. * * For context on standard usage, the "signMessage" function is used: * - During every single API call * - After opening a new private WebSocket connection * */ ⋮---- /** * Set this to true to enable demo trading: */ ⋮---- /** * Overkill in almost every case, but if you need any optimisation available, * you can inject a faster sign mechanism such as node's native createHmac: */ ⋮---- // Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing ⋮---- // trace: (...params) => console.log('trace', ...params), ⋮---- /** * Set this to true to enable demo trading for the private account data WS * Topics: order,execution,position,wallet,greeks */ ⋮---- /** * Overkill in almost every case, but if you need any optimisation available, * you can inject a faster sign mechanism such as node's native createHmac: */ ⋮---- function setWsClientEventListeners( websocketClient: WebsocketClient, accountRef: string, ): Promise ⋮---- // console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- // Simple promise to ensure we're subscribed before trying anything else ⋮---- // Start trading ⋮---- /** Simple examples for private REST API calls with bybit's V5 REST APIs */ ⋮---- // Trade USDT linear perps ================ File: examples/rest-v5-private.ts ================ import { RestClientV5 } from '../src/index'; ⋮---- // or // import { RestClientV5 } from 'bybit-api'; ⋮---- /** Simple examples for private REST API calls with bybit's V5 REST APIs */ ⋮---- // Trade USDT linear perps ================ File: examples/ws-api-raw-events.ts ================ import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../src'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; ⋮---- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: // trace: (...params) => console.log('trace', ...params), ⋮---- // testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management // demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API ⋮---- logger, // Optional: inject a custom logger ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- async function main() ⋮---- /** * * This SDK's WebSocket API integration is event-driven at its core. You can treat the sentWSAPIRquest(...) method as * a fire-and-forget method, to submit commands (create/amend/cancel order) via a WebSocket Connection. * * Replies to commands will show in the `response` event from the WebsocketClient's EventEmitter. Exceptions, however, * will show in the `error` event from the WebsocketClient's EventEmitter. * * - Fire-and-forget a command. * - Handle command results in the `response` event handler asynchronously as desired. * - Handle any exceptions in a catch block. * * This is a more "raw" workflow in how WebSockets behave. For a more convenient & REST-like approach, using the * promise-driven interface is recommended. See the `ws-api-raw-promises.ts` and `ws-api-client.ts` examples for a * demonstration you can compare. * * Note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent * any unnecessary "unhandled promise rejection" exceptions. * */ ⋮---- // To make it easier to watch, wait a few seconds before sending the amend order ⋮---- // Then wait a few more before sending the cancel order ⋮---- // Exceptions including rejected commands will show here (as well as the catch handler used below) ⋮---- // Replies to commands will show here ⋮---- /** * * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send * your first command. That connection will then be reused for every command you send, unless the connection drops - then * it will automatically be replaced with a healthy connection. * * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. * * Repeated note: even without using promises, you should still tie on a .catch handler to each sendWSAPIRequest call, to prevent * any unnecessary "unhandled promise rejection" exceptions. * */ ⋮---- // Optional, see above. Can be used to prepare a connection before sending commands ⋮---- // Fire and forget the create.order command // Even without using promises, you should still "catch" exceptions (although no need to await anything you send) ⋮---- // ⋮---- // Fire and forget the order.amend command // For simplicity, the orderId is hardcoded here (and will probably not work) ⋮---- // ⋮---- // Fire and forget the order.cancel command // For simplicity, the orderId is hardcoded here (and will probably not work) ⋮---- // Start executing the example workflow ================ File: examples/ws-api-raw-promises.ts ================ import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../src'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; ⋮---- // For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line: // trace: (...params) => console.log('trace', ...params), ⋮---- // testnet: true, // Whether to use the testnet environment: https://testnet.bybit.com/app/user/api-management // demoTrading: false, // note: As of Jan 2025, demo trading does NOT support the WS API ⋮---- logger, // Optional: inject a custom logger ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- async function main() ⋮---- /** * * This SDK's WebSocket API integration can connect WS API responses to the request that caused them. Each call * to the `sendWSAPIRequest(...)` method returns a promise. * * This promise will resolve when the matching response is detected, and reject if an exception for that request * is detected. This allows using Bybit's Websocket API in the same way that a REST API normally works. * * Send a command and immediately await the result. Handle any exceptions in a catch block. * * TypeScript users can benefit from smart type flowing for increased type safety & convenience: * - Request parameters are fully typed, depending on the operation in the second parameter to the call. E.g. * the `order.create` operation will automatically require the params to match the `OrderParamsV5` interface. * * - Response parameters are fully typed, depending on the operation in the second parameter. E.g the `order.create` * operation will automatically map the returned value to `WSAPIResponse`. * */ ⋮---- // To make it easier to watch, wait a few seconds before sending the amend order ⋮---- // Then wait a few more before sending the cancel order ⋮---- /** * * If you haven't connected yet, the WebsocketClient will automatically connect and authenticate you as soon as you send * your first command. That connection will then be reused for every command you send, unless the connection drops - then * it will automatically be replaced with a healthy connection. * * This "not connected yet" scenario can add an initial delay to your first command. If you want to prepare a connection * in advance, you can ask the WebsocketClient to prepare it before you start submitting commands. This is optional. * */ ⋮---- // Optional, see above. Can be used to prepare a connection before sending commands ⋮---- /** * Create a new order */ ⋮---- // The type for `wsAPISubmitOrderResult` is automatically resolved to `WSAPIResponse` ⋮---- // Save the orderId for the next call ⋮---- // The type for `wsAPIAmendOrderResult` is automatically resolved to `WSAPIResponse` ⋮---- // Save the orderId for the next call ⋮---- // The type for `wsAPICancelOrderResult` is automatically resolved to `WSAPIResponse` ⋮---- // Start executing the example workflow ================ File: examples/ws-private-v5.ts ================ /* eslint-disable @typescript-eslint/no-empty-function */ import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../src'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; ⋮---- // Create & inject a custom logger to enable the trace logging level (empty function) ⋮---- // trace: (...params) => console.log('trace', ...params), ⋮---- /** * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: * - Connections are opened when you subscribe to topics * - If key & secret are provided, authentication is handled automatically * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), * subscription events are automatically routed to the different ws endpoints on bybit's side * - Heartbeats/ping/pong/reconnects are all handled automatically. * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. */ ⋮---- // testnet: false, // demoTrading: false, // set testnet to false, if you plan on using demo trading ⋮---- // console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- // wsClient.on('exception', (data) => { // console.error('ws exception: ', data); // }); ⋮---- /** * For private V5 topics, us the subscribeV5() method on the ws client or use the original subscribe() method. * * Note: for private endpoints the "category" field is ignored since there is only one private endpoint * (compared to one public one per category). * The "category" is only needed for public topics since bybit has one endpoint for public events per category. */ ⋮---- // wsClient.subscribeV5('execution.fast', 'linear'); // wsClient.subscribeV5('execution.fast.linear', 'linear'); ⋮---- /** * The following has the same effect as above, since there's only one private endpoint for V5 account topics: */ // wsClient.subscribe('position'); // wsClient.subscribe('execution'); // wsClient.subscribe(['order', 'wallet', 'greek']); ⋮---- // To unsubscribe from topics (after a 5 second delay, in this example): // setTimeout(() => { // console.log('unsubscribing'); // wsClient.unsubscribeV5('execution', 'linear'); // }, 5 * 1000); ⋮---- // Topics are tracked per websocket type // Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) ================ File: examples/ws-public-allLiquidations.ts ================ import { isWsAllLiquidationEvent, RestClientV5, WebsocketClient } from '../src'; ⋮---- // or // import { // RestClientV5, // WebsocketClient, // isWsAllLiquidationEvent, // } from 'bybit-api'; ⋮---- function onAllLiquidationEvent(event) ⋮---- /** * * If you want to receive data for all available symbols, this websocket topic * requires you to subscribe to each symbol individually. * * This can be easily automated by fetching a list of symbols via the REST client, * generating a list of topics (one per symbol), before simply passing an * array of topics to the websocket client per product group (linear & inverse perps). * */ async function start() ⋮---- // Make an array of topics ready for submission ⋮---- // subscribe to all linear symbols ⋮---- // subscribe to all inverse symbols ================ File: examples/ws-public-v5.ts ================ import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../src'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; ⋮---- /** * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: * - Connections are opened when you subscribe to topics * - If key & secret are provided, authentication is handled automatically * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), * subscription events are automatically routed to the different ws endpoints on bybit's side * - Heartbeats/ping/pong/reconnects are all handled automatically. * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. */ ⋮---- /** * For public V5 topics, use the subscribeV5 method and include the API category this topic is for. * Category is required, since each category has a different websocket endpoint. */ ⋮---- // Linear v5 // -> Just one topic per call // wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear'); ⋮---- // -> Or multiple topics in one call // wsClient.subscribeV5( // ['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], // 'linear' // ); ⋮---- // Inverse v5 // wsClient.subscribeV5('orderbook.50.BTCUSD', 'inverse'); ⋮---- // Spot v5 // wsClient.subscribeV5('orderbook.50.BTCUSDT', 'spot'); ⋮---- // Option v5 // wsClient.subscribeV5('publicTrade.BTC', 'option'); ⋮---- // Use the subscribeV5() call for most subscribe calls with v5 websockets ⋮---- // Alternatively, you can also use objects in the wsClient.subscribe() call // wsClient.subscribe({ // topic: 'orderook.50.BTCUSDT', // category: 'spot', // }); ⋮---- /** * For private V5 topics, just call the same subscribeV5() method on the ws client or use the original subscribe() method. * * Note: for private endpoints the "category" field is ignored since there is only one private endpoint * (compared to one public one per category) */ ⋮---- // wsClient.subscribeV5('position', 'linear'); // wsClient.subscribeV5('execution', 'linear'); // wsClient.subscribeV5(['order', 'wallet', 'greek'], 'linear'); ⋮---- // To unsubscribe from topics (after a 5 second delay, in this example): ⋮---- // Topics are tracked per websocket type // Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) ================ File: src/types/request/index.ts ================ ================ File: src/types/request/v5-position.ts ================ import { CategoryV5, ExecTypeV5, OrderTriggerByV5, OrderTypeV5, PositionIdx, TPSLModeV5, } from '../shared-v5'; ⋮---- export interface PositionInfoParamsV5 { category: CategoryV5; symbol?: string; baseCoin?: string; settleCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface SetLeverageParamsV5 { category: 'linear' | 'inverse'; symbol: string; buyLeverage: string; sellLeverage: string; } ⋮---- export interface SwitchIsolatedMarginParamsV5 { category: 'linear' | 'inverse'; symbol: string; tradeMode: 0 | 1; buyLeverage: string; sellLeverage: string; } ⋮---- export interface SetTPSLModeParamsV5 { category: 'linear' | 'inverse'; symbol: string; tpSlMode: TPSLModeV5; } ⋮---- export interface SwitchPositionModeParamsV5 { category: 'linear' | 'inverse'; symbol?: string; coin?: string; mode: 0 | 3; } ⋮---- export interface SetRiskLimitParamsV5 { category: 'linear' | 'inverse'; symbol: string; riskId: number; positionIdx?: PositionIdx; } ⋮---- export interface SetTradingStopParamsV5 { category: CategoryV5; symbol: string; takeProfit?: string; stopLoss?: string; trailingStop?: string; tpTriggerBy?: OrderTriggerByV5; slTriggerBy?: OrderTriggerByV5; activePrice?: string; tpslMode?: TPSLModeV5; tpSize?: string; slSize?: string; tpLimitPrice?: string; slLimitPrice?: string; tpOrderType?: OrderTypeV5; slOrderType?: OrderTypeV5; positionIdx: PositionIdx; } ⋮---- export interface SetAutoAddMarginParamsV5 { category: 'linear'; symbol: string; autoAddMargin: 0 | 1; positionIdx?: PositionIdx; } ⋮---- export interface AddOrReduceMarginParamsV5 { category: 'linear' | 'inverse'; symbol: string; margin: string; positionIDex?: PositionIdx; } ⋮---- export interface GetExecutionListParamsV5 { category: CategoryV5; symbol?: string; orderId?: string; orderLinkId?: string; baseCoin?: string; startTime?: number; endTime?: number; execType?: ExecTypeV5; limit?: number; cursor?: string; } ⋮---- export interface GetClosedPnLParamsV5 { category: CategoryV5; symbol?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface MovePositionParamsV5 { fromUid: string; toUid: string; list: { category: 'linear' | 'spot' | 'option' | 'inverse'; symbol: string; price: string; side: 'Buy' | 'Sell'; qty: string; }[]; } ⋮---- export interface GetMovePositionHistoryParamsV5 { category?: 'linear' | 'spot' | 'option'; symbol?: string; startTime?: number; endTime?: number; status?: 'Processing' | 'Filled' | 'Rejected'; blockTradeId?: string; limit?: string; cursor?: string; } ⋮---- export interface ConfirmNewRiskLimitParamsV5 { category: 'linear' | 'inverse'; symbol: string; } ⋮---- export interface GetClosedOptionsPositionsParamsV5 { category: 'option'; symbol?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ================ File: src/types/request/v5-rfq.ts ================ export interface RFQTransactionV5 { category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type symbol: string; // Name of the trading contract side: 'buy' | 'sell'; // Inquiry transaction direction qty: string; // Transaction quantity isLeverage?: boolean; // For spot lending, default false } ⋮---- category: 'spot' | 'linear' | 'inverse' | 'option'; // Product type symbol: string; // Name of the trading contract side: 'buy' | 'sell'; // Inquiry transaction direction qty: string; // Transaction quantity isLeverage?: boolean; // For spot lending, default false ⋮---- export interface CreateRFQParamsV5 { counterparties: string[]; // Array of deskCode rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters anonymous?: boolean; // Whether it is anonymous inquiry, default false strategyType?: string; // Inquiry label, max 36 characters list: RFQTransactionV5[]; // Transaction list, up to 10 sets } ⋮---- counterparties: string[]; // Array of deskCode rfqLinkId?: string; // Custom ID for inquiry form, 1-32 characters anonymous?: boolean; // Whether it is anonymous inquiry, default false strategyType?: string; // Inquiry label, max 36 characters list: RFQTransactionV5[]; // Transaction list, up to 10 sets ⋮---- export interface CancelRFQParamsV5 { rfqId?: string; // Inquiry ID rfqLinkId?: string; // Inquiry Custom ID } ⋮---- rfqId?: string; // Inquiry ID rfqLinkId?: string; // Inquiry Custom ID ⋮---- export interface RFQQuoteV5 { category: 'spot' | 'linear' | 'option'; // Product type symbol: string; // Name of the trading contract price: string; // Quote price isLeverage?: boolean; // For spot lending, default false } ⋮---- category: 'spot' | 'linear' | 'option'; // Product type symbol: string; // Name of the trading contract price: string; // Quote price isLeverage?: boolean; // For spot lending, default false ⋮---- export interface CreateRFQQuoteParamsV5 { rfqId: string; // Inquiry ID quoteLinkId?: string; // Quotation custom ID, 1-32 characters anonymous?: boolean; // Whether it is anonymous quotation, default false expiresIn?: number; // Validity period in seconds, default 60 quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction quoteSellList?: RFQQuoteV5[]; // Quotation sell direction } ⋮---- rfqId: string; // Inquiry ID quoteLinkId?: string; // Quotation custom ID, 1-32 characters anonymous?: boolean; // Whether it is anonymous quotation, default false expiresIn?: number; // Validity period in seconds, default 60 quoteBuyList?: RFQQuoteV5[]; // Quotation buy direction quoteSellList?: RFQQuoteV5[]; // Quotation sell direction ⋮---- export interface ExecuteRFQQuoteParamsV5 { rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteSide: 'buy' | 'sell'; // The direction of the quote } ⋮---- rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteSide: 'buy' | 'sell'; // The direction of the quote ⋮---- export interface CancelRFQQuoteParamsV5 { quoteId?: string; // Quotation ID rfqId?: string; // Inquiry ID quoteLinkId?: string; // Quotation Custom ID } ⋮---- quoteId?: string; // Quotation ID rfqId?: string; // Inquiry ID quoteLinkId?: string; // Quotation Custom ID ⋮---- export interface GetRFQRealtimeParamsV5 { rfqId?: string; // Inquiry ID rfqLinkId?: string; // Inquiry Custom ID traderType?: 'quote' | 'request'; // Trader type, default 'request' } ⋮---- rfqId?: string; // Inquiry ID rfqLinkId?: string; // Inquiry Custom ID traderType?: 'quote' | 'request'; // Trader type, default 'request' ⋮---- export interface GetRFQListParamsV5 { rfqId?: string; // Inquiry ID rfqLinkId?: string; // Custom ID for inquiry form traderType?: 'quoter' | 'request'; // Trader type, default 'request' status?: | 'Active' | 'Canceled' | 'PendingFill' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark } ⋮---- rfqId?: string; // Inquiry ID rfqLinkId?: string; // Custom ID for inquiry form traderType?: 'quoter' | 'request'; // Trader type, default 'request' ⋮---- | 'Failed'; // Status of the inquiry form limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark ⋮---- export interface GetRFQQuoteRealtimeParamsV5 { rfqId?: string; // Inquiry ID quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation Custom ID traderType?: 'quote' | 'request'; // Trader type, default 'quote' } ⋮---- rfqId?: string; // Inquiry ID quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation Custom ID traderType?: 'quote' | 'request'; // Trader type, default 'quote' ⋮---- export interface GetRFQHistoryParamsV5 { rfqId?: string; // Inquiry ID quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation custom ID, can only check last 3 months traderType?: 'quote' | 'request'; // Trader type, default 'quote' status?: | 'Active' | 'Canceled' | 'PendingFill' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark } ⋮---- rfqId?: string; // Inquiry ID quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation custom ID, can only check last 3 months traderType?: 'quote' | 'request'; // Trader type, default 'quote' ⋮---- | 'Failed'; // Status of quotation limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark ⋮---- export interface GetRFQTradeListParamsV5 { rfqId?: string; // Inquiry ID rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation custom ID, can only check last 3 months status?: 'Filled' | 'Rejected'; // Status limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark } ⋮---- rfqId?: string; // Inquiry ID rfqLinkId?: string; // Custom ID for inquiry form, can only check last 3 months quoteId?: string; // Quotation ID quoteLinkId?: string; // Quotation custom ID, can only check last 3 months status?: 'Filled' | 'Rejected'; // Status limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark ⋮---- export interface GetRFQPublicTradesParamsV5 { startTime?: number; // Timestamp in milliseconds, time range is 7 days endTime?: number; // Timestamp in milliseconds, time range is 7 days limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark } ⋮---- startTime?: number; // Timestamp in milliseconds, time range is 7 days endTime?: number; // Timestamp in milliseconds, time range is 7 days limit?: number; // Return number of items, max 100, default 50 cursor?: string; // Page turning mark ================ File: src/types/request/v5-spot-leverage-token.ts ================ import { LTOrderTypeV5 } from '../shared-v5'; ⋮---- export interface PurchaseSpotLeveragedTokenParamsV5 { ltCoin: string; amount: string; serialNo?: string; } ⋮---- export interface RedeemSpotLeveragedTokenParamsV5 { ltCoin: string; quantity: string; serialNo?: string; } ⋮---- export interface GetSpotLeveragedTokenOrderHistoryParamsV5 { ltCoin?: string; orderId?: string; startTime?: number; endTime?: number; limit?: number; ltOrderType?: LTOrderTypeV5; serialNo?: string; } ⋮---- export interface GetVIPMarginDataParamsV5 { vipLevel?: string; currency?: string; } ⋮---- // Spot Margin Trade (UTA) endpoints export interface ManualBorrowParamsV5 { coin: string; amount: string; } ⋮---- export interface GetMaxBorrowableAmountParamsV5 { currency: string; } ⋮---- export interface GetPositionTiersParamsV5 { currency?: string; } ⋮---- export interface GetCoinStateParamsV5 { currency?: string; } ⋮---- export interface GetAvailableAmountToRepayParamsV5 { currency: string; } ⋮---- export interface SetSpotMarginLeverageParamsV5 { leverage: string; currency?: string; } ⋮---- export interface ManualRepayWithoutConversionParamsV5 { coin: string; amount?: string; } ================ File: src/types/request/v5-user.ts ================ import { PermissionsV5 } from '../shared-v5'; ⋮---- export interface CreateSubMemberParamsV5 { username: string; password?: string; /** * 1: normal, 6: custodial */ memberType: 1 | 6; /** * 0: quick login disabled (default), 1: quick login enabled */ switch?: 0 | 1; isUta?: boolean; note?: string; } ⋮---- /** * 1: normal, 6: custodial */ ⋮---- /** * 0: quick login disabled (default), 1: quick login enabled */ ⋮---- export interface CreateSubApiKeyParamsV5 { subuid: number; note?: string; readOnly: 0 | 1; ips?: string; permissions: PermissionsV5; } ⋮---- export interface UpdateApiKeyParamsV5 { apikey?: string; readOnly?: 0 | 1; ips?: string[]; permissions: PermissionsV5; } ⋮---- export interface UpdateSubApiKeyUpdateParamsV5 { readOnly?: number; ips?: string[]; permissions: PermissionsV5; } ⋮---- export interface DeleteSubMemberParamsV5 { subMemberId: string; } ⋮---- export interface GetSubAccountAllApiKeysParamsV5 { subMemberId: string; limit?: number; cursor?: string; } ⋮---- export interface GetAffiliateUserListParamsV5 { size?: number; cursor?: string; needDeposit?: boolean; need30?: boolean; need365?: boolean; startDate?: string; endDate?: string; } ================ File: src/types/response/v5-asset.ts ================ import { AccountTypeV5, OrderSideV5, WithdrawalTypeV5 } from '../shared-v5'; ⋮---- export interface CoinExchangeRecordV5 { fromCoin: string; fromAmount: string; toCoin: string; toAmount: string; exchangeRate: string; createdTime: string; exchangeTxId: string; } ⋮---- export interface DeliveryRecordV5 { deliveryTime: number; symbol: string; side: OrderSideV5; position: string; deliveryPrice: string; strike: string; fee: string; deliveryRpl: string; entryPrice: string; } ⋮---- export interface SettlementRecordV5 { symbol: string; side: string; size: number; sessionAvgPrice: string; markPrice: string; realisedPnl: string; createdTime: string; } ⋮---- export interface AssetInfoAssetV5 { coin: string; frozen: string; free: string; withdraw: string; } ⋮---- export interface AssetInfoV5 { status: 'ACCOUNT_STATUS_NORMAL' | 'ACCOUNT_STATUS_UNSPECIFIED'; assets: AssetInfoAssetV5[]; } ⋮---- export interface CoinBalanceV5 { coin: string; walletBalance: string; transferBalance: string; bonus?: string; } ⋮---- export interface AllCoinsBalanceV5 { accountType: AccountTypeV5; memberId?: string; balance: CoinBalanceV5[]; } ⋮---- export interface AccountCoinBalanceV5 { accountType: AccountTypeV5; bizType: number; accountId: string; memberId: string; balance: { coin: string; walletBalance: string; transferBalance: string; bonus: string; transferSafeAmount: string; ltvTransferSafeAmount: string; }; } ⋮---- export interface InternalTransferRecordV5 { transferId: string; coin: string; amount: string; fromAccountType: AccountTypeV5; toAccountType: AccountTypeV5; timestamp: string; status: string; } ⋮---- export interface UniversalTransferRecordV5 { transferId: string; coin: string; amount: string; fromMemberId: string; toMemberId: string; fromAccountType: AccountTypeV5; toAccountType: AccountTypeV5; timestamp: string; status: string; } ⋮---- export interface AllowedDepositCoinInfoV5 { coin: string; chain: string; coinShowName: string; chainType: string; blockConfirmNumber: number; minDepositAmount: string; } ⋮---- export interface DepositRecordV5 { id: string; coin: string; chain: string; amount: string; txID: string; status: number; toAddress: string; tag: string; depositFee: string; successAt: string; confirmations: string; txIndex: string; blockHash: string; batchReleaseLimit: string; depositType: string; fromAddress: string; } ⋮---- export interface InternalDepositRecordV5 { id: string; type: 1; coin: string; amount: string; status: 1 | 2 | 3; address: string; createdTime: string; txID: string; } ⋮---- export interface DepositAddressChainV5 { chainType: string; addressDeposit: string; tagDeposit: string; chain: string; batchReleaseLimit: string; contractAddress: string; } ⋮---- export interface DepositAddressResultV5 { coin: string; chains: DepositAddressChainV5[]; } ⋮---- export interface CoinInfoV5 { name: string; coin: string; remainAmount: string; chains: { chain: string; chainType: string; confirmation: string; withdrawFee: string; depositMin: string; withdrawMin: string; minAccuracy: string; chainDeposit: string; chainWithdraw: string; withdrawPercentageFee: string; contractAddress: string; safeConfirmNumber: string; }[]; } ⋮---- export interface WithdrawalRecordV5 { withdrawId: string; txID: string; withdrawType: WithdrawalTypeV5; coin: string; chain: string; amount: string; withdrawFee: string; status: string; toAddress: string; tag: string; createTime: string; updateTime: string; } ⋮---- export interface WithdrawalAddressV5 { coin: string; chain: string; address: string; tag: string; remark: string; status: number; addressType: number; verified: number; createdAt: string; } ⋮---- export interface WithdrawableAmountV5 { limitAmountUsd: string; withdrawableAmount: { SPOT: { coin: string; withdrawableAmount: string; availableBalance: string; }; FUND: { coin: string; withdrawableAmount: string; availableBalance: string; }; }; } ⋮---- export interface VaspEntityV5 { vaspEntityId: string; vaspName: string; } ⋮---- export interface ConvertCoinSpecV5 { coin: string; fullName: string; icon: string; iconNight: string; accuracyLength: number; coinType: string; balance: string; uBalance: string; singleFromMinLimit: string; singleFromMaxLimit: string; disableFrom: boolean; disableTo: boolean; timePeriod: number; singleToMinLimit: string; singleToMaxLimit: string; dailyFromMinLimit: string; dailyFromMaxLimit: string; dailyToMinLimit: string; dailyToMaxLimit: string; } ⋮---- export interface ConvertQuoteV5 { quoteTxId: string; exchangeRate: string; fromCoin: string; fromCoinType: string; toCoin: string; toCoinType: string; fromAmount: string; toAmount: string; expiredTime: string; requestId: string; extTaxAndFee: string[]; } ⋮---- export interface ConvertStatusV5 { accountType: string; exchangeTxId: string; userId: string; fromCoin: string; fromCoinType: string; toCoin: string; toCoinType: string; fromAmount: string; toAmount: string; exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; extInfo: { paramType: string; paramValue: string }; convertRate: string; createdAt: string; } ⋮---- export interface ConvertHistoryRecordV5 { accountType: string; exchangeTxId: string; userId: string; fromCoin: string; fromCoinType: string; toCoin: string; toCoinType: string; fromAmount: string; toAmount: string; exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; extInfo: { paramType: string; paramValue: string }; convertRate: string; createdAt: string; } ================ File: src/types/response/v5-earn.ts ================ export interface EarnProductV5 { category: string; estimateApr: string; coin: string; minStakeAmount: string; maxStakeAmount: string; precision: string; productId: string; status: 'Available' | 'NotAvailable'; } ⋮---- export interface EarnOrderHistoryV5 { coin: string; orderValue: string; orderType: 'Redeem' | 'Stake'; orderId: string; orderLinkId: string; status: 'Success' | 'Fail' | 'Pending'; createdAt: string; productId: string; updatedAt: string; swapOrderValue: string; estimateRedeemTime: string; estimateStakeTime: string; } ⋮---- export interface EarnPositionV5 { coin: string; productId: string; amount: string; totalPnl: string; claimableYield: string; } ⋮---- export interface EarnYieldHistoryV5 { productId: string; coin: string; id: string; amount: string; yieldType: string; distributionMode: string; effectiveStakingAmount: string; orderId: string; status: 'Pending' | 'Success' | 'Fail'; createdAt: string; } ⋮---- export interface EarnHourlyYieldHistoryV5 { productId: string; coin: string; id: string; amount: string; effectiveStakingAmount: string; status: 'Pending' | 'Success' | 'Fail'; hourlyDate: string; createdAt: string; } ================ File: src/types/response/v5-position.ts ================ import { CategoryV5, ExecTypeV5, OrderSideV5, OrderTypeV5, PositionIdx, PositionSideV5, PositionStatusV5, StopOrderTypeV5, TPSLModeV5, TradeModeV5, } from '../shared-v5'; ⋮---- export interface PositionV5 { positionIdx: PositionIdx; riskId: number; riskLimitValue: string; symbol: string; side: PositionSideV5; size: string; avgPrice: string; positionValue: string; tradeMode: TradeModeV5; autoAddMargin?: number; positionStatus: PositionStatusV5; leverage?: string; markPrice: string; liqPrice: string | ''; bustPrice?: string; positionIM?: string; positionMM?: string; positionBalance?: string; tpslMode?: TPSLModeV5; takeProfit?: string; stopLoss?: string; trailingStop?: string; sessionAvgPrice: string | ''; delta?: string; gamma?: string; vega?: string; theta?: string; unrealisedPnl: string; curRealisedPnl: string; cumRealisedPnl: string; adlRankIndicator: number; isReduceOnly: boolean; mmrSysUpdatedTime: string | ''; leverageSysUpdatedTime: string | ''; createdTime: string; updatedTime: string; positionIMByMp: string; positionMMByMp: string; seq: number; } ⋮---- export interface SetRiskLimitResultV5 { category: CategoryV5; riskId: number; riskLimitValue: string; } ⋮---- export interface AddOrReduceMarginResultV5 { category: CategoryV5; symbol: string; positionIdx: PositionIdx; riskId: number; riskLimitValue: string; size: string; avgPrice: string; liqPrice: string; bustPrice: string; markPrice: string; positionValue: string; leverage: string; autoAddMargin: 0 | 1; positionStatus: PositionStatusV5; positionIM: string; positionMM: string; takeProfit: string; stopLoss: string; trailingStop: string; unrealisedPnl: string; cumRealisedPnl: string; createdTime: string; updatedTime: string; } ⋮---- export interface ExecutionV5 { symbol: string; orderId: string; orderLinkId: string; side: OrderSideV5; orderPrice: string; orderQty: string; leavesQty: string; orderType: OrderTypeV5; stopOrderType?: StopOrderTypeV5; execFee: string; execFeeV2: string; feeCurrency: string; // Trading fee currency execId: string; execPrice: string; execQty: string; execType: ExecTypeV5; execValue: string; execTime: string; isMaker: boolean; feeRate: string; tradeIv?: string; markIv?: string; markPrice: string; indexPrice: string; underlyingPrice?: string; blockTradeId?: string; closedSize?: string; seq: number; extraFees: string; } ⋮---- feeCurrency: string; // Trading fee currency ⋮---- export interface ClosedPnLV5 { symbol: string; orderId: string; side: string; qty: string; orderPrice: string; orderType: OrderTypeV5; execType: ExecTypeV5; closedSize: string; openFee: string; closeFee: string; cumEntryValue: string; avgEntryPrice: string; cumExitValue: string; avgExitPrice: string; closedPnl: string; fillCount: string; leverage: string; createdTime: string; updatedTime: string; } ⋮---- export interface MovePositionResultV5 { blockTradeId: string; status: 'Processing' | 'Rejected'; rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; } ⋮---- export interface MovePositionHistoryV5 { blockTradeId: string; category: 'linear' | 'spot' | 'option'; orderId: string; userId: number; symbol: string; side: 'Buy' | 'Sell'; price: string; qty: string; execFee: string; status: 'Processing' | 'Filled' | 'Rejected'; execId: string; resultCode: number; resultMessage: string; createdAt: number; updatedAt: number; rejectParty: '' | 'Taker' | 'Maker' | 'bybit'; } ⋮---- export interface ClosedOptionsPositionV5 { symbol: string; side: 'Buy' | 'Sell'; totalOpenFee: string; deliveryFee: string; totalCloseFee: string; qty: string; closeTime: number; avgExitPrice: string; deliveryPrice: string; openTime: number; avgEntryPrice: string; totalPnl: string; } ================ File: src/types/response/v5-trade.ts ================ import { CategoryV5, OrderCancelTypeV5, OrderCreateTypeV5, OrderRejectReasonV5, OrderSideV5, OrderStatusV5, OrderTimeInForceV5, OrderTriggerByV5, OrderTypeV5, PositionIdx, StopOrderTypeV5, } from '../shared-v5'; ⋮---- export interface OrderResultV5 { orderId: string; orderLinkId: string; } ⋮---- export interface AccountOrderV5 { orderId: string; orderLinkId: string; blockTradeId: string; symbol: string; price: string; qty: string; side: OrderSideV5; isLeverage: '0' | '1'; positionIdx: PositionIdx; orderStatus: OrderStatusV5; createType: OrderCreateTypeV5; cancelType: OrderCancelTypeV5; rejectReason: OrderRejectReasonV5; avgPrice: string; leavesQty: string; leavesValue: string; cumExecQty: string; cumExecValue: string; cumExecFee: string; timeInForce: OrderTimeInForceV5; orderType: OrderTypeV5; stopOrderType: StopOrderTypeV5; orderIv: string; marketUnit: 'baseCoin' | 'quoteCoin'; slippageToleranceType: string; slippageTolerance: string; triggerPrice: string; takeProfit: string; stopLoss: string; tpslMode: 'Full' | 'Partial' | ''; ocoTriggerType: | 'OcoTriggerByUnknown' | 'OcoTriggerTp' | 'OcoTriggerBySl' | ''; tpLimitPrice: string; slLimitPrice: string; tpTriggerBy: OrderTriggerByV5; slTriggerBy: OrderTriggerByV5; triggerDirection: 1 | 2; triggerBy: OrderTriggerByV5; lastPriceOnCreated: string; reduceOnly: boolean; closeOnTrigger: boolean; placeType: 'iv' | 'price' | ''; smpType: string; smpGroup: number; smpOrderId: string; createdTime: string; updatedTime: string; extraFees: string; cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee } ⋮---- cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee ⋮---- export interface BatchCreateOrderResultV5 { category: CategoryV5; symbol: string; orderId: string; orderLinkId: string; createAt?: string; } ⋮---- export interface BatchOrdersRetExtInfoV5 { list: { code: number; msg: string; }[]; } ⋮---- export interface BatchAmendOrderResultV5 { category: CategoryV5; symbol: string; orderId: string; orderLinkId: string; } ⋮---- export interface BatchCancelOrderResultV5 { category: CategoryV5; symbol: string; orderId: string; orderLinkId: string; } ⋮---- export interface SpotBorrowCheckResultV5 { symbol: string; side: OrderSideV5; maxTradeQty: string; maxTradeAmount: string; spotMaxTradeQty: string; spotMaxTradeAmount: string; borrowCoin: string; } ⋮---- export interface PreCheckOrderResultV5 { orderId: string; orderLinkId: string; preImrE4: number; // Initial margin rate before checking (in basis points) preMmrE4: number; // Maintenance margin rate before checking (in basis points) postImrE4: number; // Initial margin rate after checking (in basis points) postMmrE4: number; // Maintenance margin rate after checking (in basis points) } ⋮---- preImrE4: number; // Initial margin rate before checking (in basis points) preMmrE4: number; // Maintenance margin rate before checking (in basis points) postImrE4: number; // Initial margin rate after checking (in basis points) postMmrE4: number; // Maintenance margin rate after checking (in basis points) ================ File: src/types/response/v5-user.ts ================ import { PermissionsV5 } from '../shared-v5'; ⋮---- export interface CreateSubMemberResultV5 { uid: string; username: string; memberType: number; status: number; remark: string; } ⋮---- export interface CreateSubApiKeyResultV5 { id: string; note: string; apiKey: string; readOnly: number; secret: string; permissions: PermissionsV5; } ⋮---- export interface SubMemberV5 { uid: string; username: string; memberType: number; status: number; accountMode: number; remark: string; } export type ApiKeyType = 1 | 2; ⋮---- export interface ApiKeyPermissionsV5 { ContractTrade: string[]; Spot: string[]; Wallet: string[]; Options: string[]; Derivatives: string[]; CopyTrading: string[]; BlockTrade: string[]; Exchange: string[]; NFT: string[]; Affiliate: string[]; } ⋮---- export interface ApiKeyInfoV5 { id: string; note: string; apiKey: string; readOnly: 0 | 1; secret: string; permissions: ApiKeyPermissionsV5; ips: string[]; type: 1 | 2; // 1: personal, 2: connected to third-party app deadlineDay: number; expiredAt: string; createdAt: string; /** @deprecated */ unified: number; uta: 0 | 1; // 0: regular account, 1: unified trade account userID: number; inviterID: number; vipLevel: string; mktMakerLevel: string; affiliateID: number; rsaPublicKey: string; isMaster: boolean; parentUid: string; kycLevel: 'LEVEL_DEFAULT' | 'LEVEL_1' | 'LEVEL_2'; kycRegion: string; } ⋮---- type: 1 | 2; // 1: personal, 2: connected to third-party app ⋮---- /** @deprecated */ ⋮---- uta: 0 | 1; // 0: regular account, 1: unified trade account ⋮---- export interface UpdateApiKeyResultV5 { id: string; note: string; apiKey: string; readOnly: 0 | 1; secret: string; permissions: PermissionsV5; ips: string[]; } ⋮---- export interface SubAccountAllApiKeysResultV5 { result: { id: string; ips?: string[]; apiKey: string; note: string; status: number; expiredAt?: string; createdAt: string; type: ApiKeyType; permissions: PermissionsV5; secret: string; readOnly: 0 | 1; deadlineDay?: number; flag: string; }[]; nextPageCursor: string; } ⋮---- export interface AffiliateUserListItemV5 { userId: string; registerTime: string; source: string; remarks: string; isKyc: boolean; takerVol30Day: string; makerVol30Day: string; tradeVol30Day: string; depositAmount30Day: string; takerVol365Day: string; makerVol365Day: string; tradeVol365Day: string; depositAmount365Day: string; takerVol: string; makerVol: string; tradeVol: string; startDate: string; endDate: string; } ⋮---- export interface AffiliateUserInfoV5 { uid: string; vipLevel: string; takerVol30Day: string; makerVol30Day: string; tradeVol30Day: string; depositAmount30Day: string; takerVol365Day: string; makerVol365Day: string; tradeVol365Day: string; depositAmount365Day: string; totalWalletBalance: '1' | '2' | '3' | '4'; depositUpdateTime: string; volUpdateTime: string; KycLevel: 0 | 1 | 2; } ================ File: src/types/websockets/index.ts ================ ================ File: src/types/index.ts ================ ================ File: src/index.ts ================ ================ File: src/websocket-api-client.ts ================ import { AmendOrderParamsV5, BatchAmendOrderParamsV5, BatchAmendOrderResultV5, BatchCancelOrderParamsV5, BatchCancelOrderResultV5, BatchCreateOrderResultV5, BatchOrderParamsV5, BatchOrdersRetExtInfoV5, CancelOrderParamsV5, OrderParamsV5, OrderResultV5, } from './types'; import { WSAPIResponse } from './types/websockets/ws-api'; import { WSClientConfigurableOptions } from './types/websockets/ws-general'; import { DefaultLogger } from './util'; import { WS_KEY_MAP } from './util/websockets/websocket-util'; import { WebsocketClient } from './websocket-client'; ⋮---- /** * 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/bybit-api/blob/master/examples/ws-api-raw-promises.ts */ export class WebsocketAPIClient ⋮---- constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, ) ⋮---- public getWSClient(): WebsocketClient ⋮---- public setTimeOffsetMs(newOffset: number): void ⋮---- /* * Bybit WebSocket API Methods * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline */ ⋮---- /** * Submit a new order * * @param params * @returns */ submitNewOrder( params: OrderParamsV5, ): Promise> ⋮---- /** * Amend an order * * @param params * @returns */ amendOrder( params: AmendOrderParamsV5, ): Promise> ⋮---- /** * Cancel an order * * @param params * @returns */ cancelOrder( params: CancelOrderParamsV5, ): Promise> ⋮---- /** * Batch submit orders * * @param params * @returns */ batchSubmitOrders( category: 'option' | 'linear', orders: BatchOrderParamsV5[], ): Promise< WSAPIResponse< { list: BatchCreateOrderResultV5[]; }, 'order.create-batch', BatchOrdersRetExtInfoV5 > > { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.v5PrivateTrade, 'order.create-batch', { category, request: orders, }, ); ⋮---- /** * Batch amend orders * * @param params * @returns */ batchAmendOrder( category: 'option' | 'linear', orders: BatchAmendOrderParamsV5[], ): Promise< WSAPIResponse< { list: BatchAmendOrderResultV5[]; }, 'order.amend-batch', BatchOrdersRetExtInfoV5 > > { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.v5PrivateTrade, 'order.amend-batch', { category, request: orders, }, ); ⋮---- /** * Batch cancel orders * * @param params * @returns */ batchCancelOrder( category: 'option' | 'linear', orders: BatchCancelOrderParamsV5[], ): Promise< WSAPIResponse< { list: BatchCancelOrderResultV5[]; }, 'order.cancel-batch', BatchOrdersRetExtInfoV5 > > { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.v5PrivateTrade, 'order.cancel-batch', { category, request: orders, }, ); ⋮---- /** * * * * * * * * Private methods for handling some of the convenience/automation provided by the WS API Client * * * * * * * */ ⋮---- private setupDefaultEventListeners() ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // Blind JSON.stringify can fail on circular references ⋮---- // JSON.stringify({ ...data, target: 'WebSocket' }), ================ File: examples/rest-v5-p2p.ts ================ import fs from 'fs'; import path from 'path'; ⋮---- import { RestClientV5 } from '../src'; ⋮---- // ENDPOINT: /v5/p2p/oss/upload_file // METHOD: POST // PUBLIC: NO // NOTE: Node.js only (Buffer required) ⋮---- async function uploadP2PChatFile() ⋮---- // You must read the file yourself and pass the Buffer + filename ⋮---- /** * * * * * * */ ⋮---- // Test basic P2P API connectivity ⋮---- // Example 1: Upload from file path ⋮---- fileName: path.basename(filePath), // Extract filename from path ⋮---- // Example 2: Upload with custom filename // You control the filename sent to Bybit ⋮---- fileName: 'custom-name.png', // Use any filename you want ⋮---- // Example 3: Upload different file ⋮---- // Supported file types (determined by filename extension): // - Images: jpg, jpeg, png // - Documents: pdf // - Videos: mp4 ================ File: src/types/request/v5-account.ts ================ import { AccountTypeV5, CategoryV5, TransactionTypeV5 } from '../shared-v5'; ⋮---- export interface GetWalletBalanceParamsV5 { accountType: AccountTypeV5; coin?: string; } ⋮---- export interface GetBorrowHistoryParamsV5 { currency?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetFeeRateParamsV5 { category: CategoryV5; symbol?: string; baseCoin?: string; } ⋮---- export interface GetTransactionLogParamsV5 { accountType?: AccountTypeV5; category?: CategoryV5; currency?: string; baseCoin?: string; type?: TransactionTypeV5; /** * Transaction sub type, "movePosition", used to filter trans logs of Move Position only */ transSubType?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- /** * Transaction sub type, "movePosition", used to filter trans logs of Move Position only */ ⋮---- export interface MMPModifyParamsV5 { baseCoin: string; window: string; frozenPeriod: string; qtyLimit: string; deltaLimit: string; } ⋮---- export interface RepayLiabilityParamsV5 { coin?: string; } ⋮---- export interface SetCollateralCoinParamsV5 { coin: string; collateralSwitch: 'ON' | 'OFF'; } ⋮---- export interface GetClassicTransactionLogsParamsV5 { currency?: string; baseCoin?: string; type?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface SetLimitPriceActionParamsV5 { category: CategoryV5; modifyEnable: boolean; } ⋮---- export interface GetAccountInstrumentsInfoParamsV5 { category: 'spot' | 'linear' | 'inverse'; symbol?: string; limit?: number; cursor?: string; } ⋮---- export interface ManualRepayParamsV5 { coin?: string; amount?: string; } ================ File: src/types/request/v5-asset.ts ================ import { AccountTypeV5, CategoryV5 } from '../shared-v5'; ⋮---- export interface GetCoinExchangeRecordParamsV5 { fromCoin?: string; toCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface GetDeliveryRecordParamsV5 { category: CategoryV5; symbol?: string; startTime?: number; endTime?: number; expDate?: string; limit?: number; cursor?: string; } ⋮---- export interface GetSettlementRecordParamsV5 { category: CategoryV5; symbol?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetAssetInfoParamsV5 { accountType: AccountTypeV5; coin?: string; } ⋮---- export interface GetAllCoinsBalanceParamsV5 { memberId?: string; accountType: AccountTypeV5; coin?: string; withBonus?: number; } ⋮---- export interface GetAccountCoinBalanceParamsV5 { memberId?: string; toMemberId?: string; accountType: AccountTypeV5; coin: string; toAccountType?: AccountTypeV5; withBonus?: number; withTransferSafeAmount?: 0 | 1; withLtvTransferSafeAmount?: 0 | 1; } ⋮---- export interface GetInternalTransferParamsV5 { transferId?: string; coin?: string; status?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface UniversalTransferParamsV5 { transferId: string; coin: string; amount: string; fromMemberId: number; toMemberId: number; fromAccountType: AccountTypeV5; toAccountType: AccountTypeV5; } ⋮---- export interface GetUniversalTransferRecordsParamsV5 { transferId?: string; coin?: string; status?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetAllowedDepositCoinInfoParamsV5 { coin?: string; chain?: string; limit?: number; cursor?: string; } ⋮---- export interface GetDepositRecordParamsV5 { id?: string; txID?: string; coin?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetSubAccountDepositRecordParamsV5 { id?: string; txID?: string; subMemberId: string; coin?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetInternalDepositRecordParamsV5 { txID?: string; startTime?: number; endTime?: number; coin?: string; cursor?: string; limit?: number; } ⋮---- export interface GetWithdrawalRecordsParamsV5 { withdrawID?: string; txID?: string; coin?: string; withdrawType?: number; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetWithdrawalAddressListParamsV5 { coin?: string; chain?: string; addressType?: 0 | 1 | 2; limit?: number; cursor?: string; } ⋮---- export interface WithdrawParamsV5 { coin: string; chain: string; address: string; tag?: string; amount: string; timestamp: number; forceChain?: number; accountType: 'SPOT' | 'FUND'; feeType?: 0 | 1; requestId?: string; beneficiary?: { vaspEntityId?: string; beneficiaryName?: string; beneficiaryLegalType?: string; beneficiaryWalletType?: string; beneficiaryUnhostedWalletType?: string; beneficiaryPoiNumber?: string; beneficiaryPoiType?: string; beneficiaryPoiIssuingCountry?: string; beneficiaryPoiExpiredDate?: string; }; } ⋮---- export interface ConvertCoinsParamsV5 { coin?: string; side?: number; accountType: | 'eb_convert_funding' | 'eb_convert_uta' | 'eb_convert_spot' | 'eb_convert_contract' | 'eb_convert_inverse'; } ⋮---- export interface RequestConvertQuoteParamsV5 { fromCoin: string; toCoin: string; fromCoinType?: string; toCoinType?: string; requestCoin: string; requestAmount: string; accountType: | 'eb_convert_funding' | 'eb_convert_uta' | 'eb_convert_spot' | 'eb_convert_contract' | 'eb_convert_inverse'; requestId?: string; } ⋮---- export interface GetConvertHistoryParamsV5 { accountType?: string; index?: number; limit?: number; } ================ File: src/types/request/v5-earn.ts ================ export interface SubmitStakeRedeemParamsV5 { category: string; orderType: 'Stake' | 'Redeem'; accountType: 'FUND' | 'UNIFIED'; amount: string; coin: string; productId: string; orderLinkId: string; toAccountType?: 'FUND' | 'UNIFIED'; } ⋮---- export interface GetEarnOrderHistoryParamsV5 { category: string; orderId?: string; orderLinkId?: string; productId?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetEarnPositionParamsV5 { category: string; productId?: string; coin?: string; } ⋮---- export interface GetEarnYieldHistoryParamsV5 { category: string; productId?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetEarnHourlyYieldHistoryParamsV5 { category: string; productId?: string; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ================ File: src/types/request/v5-market.ts ================ import { KlineIntervalV3 } from '../shared'; import { CategoryV5, InstrumentStatusV5, OptionTypeV5 } from '../shared-v5'; ⋮---- export interface GetKlineParamsV5 { category: 'spot' | 'linear' | 'inverse'; symbol: string; interval: KlineIntervalV3; start?: number; end?: number; limit?: number; } ⋮---- export interface GetMarkPriceKlineParamsV5 { category: 'linear' | 'inverse'; symbol: string; interval: KlineIntervalV3; start?: number; end?: number; limit?: number; } ⋮---- export interface GetIndexPriceKlineParamsV5 { category: 'linear' | 'inverse'; symbol: string; interval: KlineIntervalV3; start?: number; end?: number; limit?: number; } ⋮---- export interface GetPremiumIndexPriceKlineParamsV5 { category: 'linear'; symbol: string; interval: KlineIntervalV3; start?: number; end?: number; limit?: number; } ⋮---- export interface GetInstrumentsInfoParamsV5 { category: CategoryV5; symbol?: string; symbolType?: string; status?: InstrumentStatusV5; baseCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface GetOrderbookParamsV5 { category: CategoryV5; symbol: string; limit?: number; } ⋮---- export interface GetRPIOrderbookParamsV5 { category?: 'spot' | 'linear' | 'inverse'; symbol: string; limit: number; // Required for RPI orderbook, [1, 50] } ⋮---- limit: number; // Required for RPI orderbook, [1, 50] ⋮---- export interface GetIndexPriceComponentsParamsV5 { indexName: string; // Index name, like BTCUSDT } ⋮---- indexName: string; // Index name, like BTCUSDT ⋮---- export interface GetADLAlertParamsV5 { symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only } ⋮---- symbol?: string; // Contract name, e.g. BTCUSDT. Uppercase only ⋮---- export interface GetFeeGroupStructureParamsV5 { productType: string; // Product type. contract only for now groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 } ⋮---- productType: string; // Product type. contract only for now groupId?: string; // Group ID. 1, 2, 3, 4, 5, 6, 7 ⋮---- export interface GetTickersParamsV5 { category: TCategory; symbol?: string; baseCoin?: string; expDate?: string; } ⋮---- export interface GetFundingRateHistoryParamsV5 { category: 'linear' | 'inverse'; symbol: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- export interface GetPublicTradingHistoryParamsV5 { category: CategoryV5; symbol: string; baseCoin?: string; optionType?: OptionTypeV5; limit?: number; } ⋮---- export type OpenInterestIntervalV5 = | '5min' | '15min' | '30min' | '1h' | '4h' | '1d'; ⋮---- export interface GetOpenInterestParamsV5 { category: 'linear' | 'inverse'; symbol: string; intervalTime: OpenInterestIntervalV5; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface GetHistoricalVolatilityParamsV5 { category: 'option'; baseCoin?: string; period?: 7 | 14 | 21 | 30 | 60 | 90 | 180 | 270; startTime?: number; endTime?: number; } ⋮---- export interface GetInsuranceParamsV5 { coin?: string; } ⋮---- export interface GetRiskLimitParamsV5 { category?: 'linear' | 'inverse'; symbol?: string; cursor?: string; } ⋮---- export interface GetOptionDeliveryPriceParamsV5 { category: 'option'; symbol?: string; baseCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface GetDeliveryPriceParamsV5 { category: 'linear' | 'inverse' | 'option'; symbol?: string; baseCoin?: string; settleCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface GetLongShortRatioParamsV5 { category: 'linear' | 'inverse'; symbol: string; period: OpenInterestIntervalV5; startTime?: string; endTime?: string; limit?: number; cursor?: string; } ================ File: src/types/request/v5-trade.ts ================ import { CategoryV5, OrderFilterV5, OrderSideV5, OrderSMPTypeV5, OrderStatusV5, OrderTimeInForceV5, OrderTriggerByV5, OrderTypeV5, PositionIdx, StopOrderTypeV5, } from '../shared-v5'; ⋮---- export interface OrderParamsV5 { category: CategoryV5; symbol: string; isLeverage?: 0 | 1; side: OrderSideV5; orderType: OrderTypeV5; qty: string; marketUnit?: 'baseCoin' | 'quoteCoin'; slippageToleranceType?: string; slippageTolerance?: string; price?: string; triggerDirection?: 1 | 2; orderFilter?: OrderFilterV5; triggerPrice?: string; triggerBy?: OrderTriggerByV5; orderIv?: string; timeInForce?: OrderTimeInForceV5; positionIdx?: PositionIdx; orderLinkId?: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: OrderTriggerByV5; slTriggerBy?: OrderTriggerByV5; reduceOnly?: boolean; closeOnTrigger?: boolean; smpType?: OrderSMPTypeV5; mmp?: boolean; tpslMode?: 'Full' | 'Partial'; tpLimitPrice?: string; slLimitPrice?: string; tpOrderType?: OrderTypeV5; slOrderType?: OrderTypeV5; bboSideType?: 'Queue' | 'Counterparty'; bboLevel?: '1' | '2' | '3' | '4' | '5'; } ⋮---- export interface AmendOrderParamsV5 { category: CategoryV5; symbol: string; orderId?: string; orderLinkId?: string; orderIv?: string; triggerPrice?: string; qty?: string; price?: string; tpslMode?: 'Full' | 'Partial'; takeProfit?: string; stopLoss?: string; tpTriggerBy?: OrderTriggerByV5; slTriggerBy?: OrderTriggerByV5; triggerBy?: OrderTriggerByV5; tpLimitPrice?: string; slLimitPrice?: string; } ⋮---- export interface CancelOrderParamsV5 { category: CategoryV5; symbol: string; orderId?: string; orderLinkId?: string; orderFilter?: OrderFilterV5; } ⋮---- export interface GetAccountOrdersParamsV5 { category: CategoryV5; symbol?: string; baseCoin?: string; settleCoin?: string; orderId?: string; orderLinkId?: string; openOnly?: 0 | 1 | 2; orderFilter?: OrderFilterV5; orderStatus?: OrderStatusV5; limit?: number; cursor?: string; } ⋮---- export interface GetAccountHistoricOrdersParamsV5 { category: CategoryV5; symbol?: string; baseCoin?: string; settleCoin?: string; orderId?: string; orderLinkId?: string; orderFilter?: OrderFilterV5; orderStatus?: OrderStatusV5; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- export interface CancelAllOrdersParamsV5 { category: CategoryV5; symbol?: string; baseCoin?: string; settleCoin?: string; orderFilter?: OrderFilterV5; stopOrderType?: StopOrderTypeV5; } ⋮---- export interface BatchOrderParamsV5 { symbol: string; side: OrderSideV5; isLeverage?: 0 | 1; orderType: OrderTypeV5; qty: string; price?: string; triggerDirection?: 1 | 2; triggerBy?: OrderTriggerByV5; orderIv?: string; timeInForce?: OrderTimeInForceV5; positionIdx?: PositionIdx; orderLinkId?: string; takeProfit?: string; stopLoss?: string; tpTriggerBy?: OrderTriggerByV5; slTriggerBy?: OrderTriggerByV5; reduceOnly?: boolean; closeOnTrigger?: boolean; smpType?: OrderSMPTypeV5; mmp?: boolean; tpslMode?: 'Full' | 'Partial'; tpLimitPrice?: string; slLimitPrice?: string; tpOrderType?: OrderTypeV5; slOrderType?: OrderTypeV5; } ⋮---- export interface BatchAmendOrderParamsV5 { symbol: string; orderId?: string; orderLinkId?: string; orderIv?: string; triggerPrice?: string; qty?: string; price?: string; tpslMode?: 'Full' | 'Partial'; takeProfit?: string; stopLoss?: string; tpTriggerBy?: OrderTriggerByV5; slTriggerBy?: OrderTriggerByV5; triggerBy?: OrderTriggerByV5; tpLimitPrice?: string; slLimitPrice?: string; } ⋮---- export interface BatchCancelOrderParamsV5 { symbol: string; orderId?: string; orderLinkId?: string; } ================ File: src/types/response/index.ts ================ ================ File: src/types/response/v5-rfq.ts ================ export interface RFQConfigV5 { deskCode: string; // Own deskCode, unique identification code maxLegs: number; // Maximum number of legs maxLP: number; // Maximum number of LPs selected in inquiry form maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier minLimitQtyOptionOrder: number; // Option minimum order multiplier strategyTypes: { strategyName: string; // Policy name }[]; counterparties: { strategyName: string; // Policy name }[]; } ⋮---- deskCode: string; // Own deskCode, unique identification code maxLegs: number; // Maximum number of legs maxLP: number; // Maximum number of LPs selected in inquiry form maxActiveRfq: number; // Maximum number of unfinished inquiry orders allowed minLimitQtySpotOrder: number; // Spot minimum order quantity multiplier minLimitQtyContractOrder: number; // Contract minimum order quantity multiplier minLimitQtyOptionOrder: number; // Option minimum order multiplier ⋮---- strategyName: string; // Policy name ⋮---- strategyName: string; // Policy name ⋮---- export interface RFQCounterpartyV5 { traderName: string; // Name of the bidder deskCode: string; // Unique identification code of the quotation party type: string | null; // Quoter type. LP is automated market maker, null means normal quote party } ⋮---- traderName: string; // Name of the bidder deskCode: string; // Unique identification code of the quotation party type: string | null; // Quoter type. LP is automated market maker, null means normal quote party ⋮---- export interface CreateRFQResultV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Inquiry party unique identification code } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of the inquiry form expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Inquiry party unique identification code ⋮---- export interface CancelRFQResultV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID ⋮---- export interface CancelRFQItemV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID code: number; // Cancel success or failure, 0 means success msg: string; // Cancellation failure reason } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID code: number; // Cancel success or failure, 0 means success msg: string; // Cancellation failure reason ⋮---- export interface CancelAllRFQResultV5 { data: CancelRFQItemV5[]; // Array of cancellation results } ⋮---- data: CancelRFQItemV5[]; // Array of cancellation results ⋮---- export interface CreateRFQQuoteResultV5 { rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Quoter's unique identification code status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation } ⋮---- rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Quoter's unique identification code status: 'Active' | 'Canceled' | 'Filled' | 'Expired' | 'Failed'; // Status of quotation ⋮---- export interface ExecuteRFQQuoteResultV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID quoteId: string; // Quotation ID status: 'Processing' | 'Rejected'; // Order status rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Inquiry Custom ID quoteId: string; // Quotation ID status: 'Processing' | 'Rejected'; // Order status rejectParty: string; // Empty means passed, "Taker", "Maker", "Bybit" when rejected ⋮---- export interface CancelRFQQuoteResultV5 { rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID } ⋮---- rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID ⋮---- export interface CancelRFQQuoteItemV5 { rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID code: number; // Cancel success or failure, 0 means success msg: string; // Cancellation failure reason } ⋮---- rfqId: string; // Inquiry ID quoteId: string; // Quotation ID quoteLinkId: string; // Quotation Custom ID code: number; // Cancel success or failure, 0 means success msg: string; // Cancellation failure reason ⋮---- export interface RFQLegV5 { category: 'linear' | 'option' | 'spot'; // Product category symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Inquiry direction qty: string; // Order quantity of the instrument isLeverage?: boolean; // For spot lending } ⋮---- category: 'linear' | 'option' | 'spot'; // Product category symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Inquiry direction qty: string; // Order quantity of the instrument isLeverage?: boolean; // For spot lending ⋮---- export interface RFQItemV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Custom ID for inquiry form counterparties: string[]; // List of bidders expiresAt: string; // Expiration time in milliseconds Unix timestamp strategyType: string; // Inquiry label status: | 'Active' | 'Canceled' | 'PendingFill' | 'Filled' | 'Expired' | 'Failed'; // Status deskCode: string; // Unique identification code of the inquiry party createdAt: number; // Time when the trade is created in epoch updatedAt: number; // Time when the trade is updated in epoch legs: RFQLegV5[]; // Combination transaction } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Custom ID for inquiry form counterparties: string[]; // List of bidders expiresAt: string; // Expiration time in milliseconds Unix timestamp strategyType: string; // Inquiry label ⋮---- | 'Failed'; // Status deskCode: string; // Unique identification code of the inquiry party createdAt: number; // Time when the trade is created in epoch updatedAt: number; // Time when the trade is updated in epoch legs: RFQLegV5[]; // Combination transaction ⋮---- export interface GetRFQRealtimeResultV5 { list: RFQItemV5[]; // Array of RFQ items } ⋮---- list: RFQItemV5[]; // Array of RFQ items ⋮---- export interface RFQHistory { cursor: string; // Page turning mark list: RFQItemV5[]; // Array of RFQ items } ⋮---- cursor: string; // Page turning mark list: RFQItemV5[]; // Array of RFQ items ⋮---- export interface QuoteLegV5 { category: 'spot' | 'linear' | 'option'; // Product type symbol: string; // The unique instrument ID or name of trading contract price: string; // Order price or quote price qty?: string; // Order quantity isLeverage?: boolean; // For spot lending } ⋮---- category: 'spot' | 'linear' | 'option'; // Product type symbol: string; // The unique instrument ID or name of trading contract price: string; // Order price or quote price qty?: string; // Order quantity isLeverage?: boolean; // For spot lending ⋮---- export interface RFQQuoteItemV5 { rfqId: string; // Inquiry ID rfqLinkId: string; // Custom ID for inquiry form quoteId: string; // Quotation ID quoteLinkId: string; // Quotation custom ID expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Unique identification code of quotation party status: | 'Active' | 'Canceled' | 'PendingFill' | 'Filled' | 'Expired' | 'Failed'; // Status execQuoteSide: string; // Execute quote direction, buy or sell createdAt: number; // Time when the trade is created in epoch updatedAt: number; // Time when the trade is updated in epoch quoteBuyList: QuoteLegV5[]; // Quotation buy direction quoteSellList: QuoteLegV5[]; // Quotation sell direction } ⋮---- rfqId: string; // Inquiry ID rfqLinkId: string; // Custom ID for inquiry form quoteId: string; // Quotation ID quoteLinkId: string; // Quotation custom ID expiresAt: string; // Expiration time in milliseconds Unix timestamp deskCode: string; // Unique identification code of quotation party ⋮---- | 'Failed'; // Status execQuoteSide: string; // Execute quote direction, buy or sell createdAt: number; // Time when the trade is created in epoch updatedAt: number; // Time when the trade is updated in epoch quoteBuyList: QuoteLegV5[]; // Quotation buy direction quoteSellList: QuoteLegV5[]; // Quotation sell direction ⋮---- export interface RFQTradeLegV5 { category: 'linear' | 'option' | 'spot'; // Product category orderId: string; // Bybit order ID symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Direction price: string; // Execution price qty: string; // Number of executions isLeverage?: boolean; // For spot lending markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot execFee: string; // Fee for taker or maker in base currency execId: string; // Unique exec(trade) ID from exchange resultCode: number; // Status code, 0 means success resultMessage: string; // Error message about resultCode rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected } ⋮---- category: 'linear' | 'option' | 'spot'; // Product category orderId: string; // Bybit order ID symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Direction price: string; // Execution price qty: string; // Number of executions isLeverage?: boolean; // For spot lending markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot execFee: string; // Fee for taker or maker in base currency execId: string; // Unique exec(trade) ID from exchange resultCode: number; // Status code, 0 means success resultMessage: string; // Error message about resultCode rejectParty: string; // Empty if Filled, "Taker"/"Maker"/"bybit" if Rejected ⋮---- export interface RFQTradeV5 { rfqId: string; // Inquiry ID quoteId: string; // Completed inquiry form and executed quotation ID quoteSide: 'buy' | 'sell'; // Executed quotation direction strategyType: string; // Inquiry label status: 'Filled' | 'Rejected'; // Status rfqDeskCode: string; // Unique identification code of inquiry party quoteDestCode: string; // Unique identification code of quotation party createdAt: number; // Time when trade is created in epoch updatedAt: number; // Time when trade is updated in epoch legs: RFQTradeLegV5[]; // Combination transaction } ⋮---- rfqId: string; // Inquiry ID quoteId: string; // Completed inquiry form and executed quotation ID quoteSide: 'buy' | 'sell'; // Executed quotation direction strategyType: string; // Inquiry label status: 'Filled' | 'Rejected'; // Status rfqDeskCode: string; // Unique identification code of inquiry party quoteDestCode: string; // Unique identification code of quotation party createdAt: number; // Time when trade is created in epoch updatedAt: number; // Time when trade is updated in epoch legs: RFQTradeLegV5[]; // Combination transaction ⋮---- export interface RFQPublicTradeLegV5 { category: 'linear' | 'option' | 'spot'; // Product category symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Inquiry direction price: string; // Execution price qty: string; // Number of executions markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot } ⋮---- category: 'linear' | 'option' | 'spot'; // Product category symbol: string; // The unique instrument ID side: 'buy' | 'sell'; // Inquiry direction price: string; // Execution price qty: string; // Number of executions markPrice: string; // MarkPrice (contract) at transaction time, indexPrice for spot ⋮---- export interface RFQPublicTradeV5 { rfqId: string; // Inquiry ID strategyType: string; // Inquiry label createdAt: number; // Time when trade is created in epoch updatedAt: number; // Time when trade is updated in epoch legs: RFQPublicTradeLegV5[]; // Combination transaction } ⋮---- rfqId: string; // Inquiry ID strategyType: string; // Inquiry label createdAt: number; // Time when trade is created in epoch updatedAt: number; // Time when trade is updated in epoch legs: RFQPublicTradeLegV5[]; // Combination transaction ================ File: src/types/response/v5-spot-leverage-token.ts ================ import { LeverageTokenStatusV5, LTOrderStatusV5, LTOrderTypeV5, } from '../shared-v5'; ⋮---- export interface LeverageTokenInfoV5 { ltCoin: string; ltName: string; maxPurchase: string; minPurchase: string; maxPurchaseDaily: string; maxRedeem: string; minRedeem: string; maxRedeemDaily: string; purchaseFeeRate: string; redeemFeeRate: string; ltStatus: LeverageTokenStatusV5; fundFee: string; fundFeeTime: string; manageFeeRate: string; manageFeeTime: string; value: string; netValue: string; total: string; } ⋮---- export interface LeveragedTokenMarketResultV5 { ltCoin: string; nav: string; navTime: string; circulation: string; basket: string; leverage: string; } ⋮---- export interface PurchaseSpotLeveragedTokenResultV5 { ltCoin: string; ltOrderStatus: LTOrderStatusV5; execQty: string; execAmt: string; amount: string; purchaseId: string; serialNo: string; valueCoin: string; } export interface RedeemSpotLeveragedTokenResultV5 { ltCoin: string; ltOrderStatus: LTOrderStatusV5; quantity: string; execQty: string; execAmt: string; redeemId: string; serialNo: string; valueCoin: string; } ⋮---- export interface SpotLeveragedTokenOrderHistoryV5 { ltCoin: string; orderId: string; ltOrderType: LTOrderTypeV5; orderTime: number; updateTime: number; ltOrderStatus: LTOrderStatusV5; fee: string; amount: string; value: string; valueCoin: string; serialNo: string; } ⋮---- export interface VIPMarginDataV5 { vipCoinList: { list: { borrowable: boolean; collateralRatio: string; currency: string; hourlyBorrowRate: string; liquidationOrder: string; marginCollateral: boolean; maxBorrowingAmount: string; }[]; vipLevel: string; }[]; } ⋮---- export interface SpotMarginStateV5 { spotLeverage: string; spotMarginMode: '1' | '0'; effectiveLeverage: string; } ⋮---- // Spot Margin Trade (UTA) response types export interface ManualBorrowResultV5 { coin: string; amount: string; } ⋮---- export interface MaxBorrowableAmountV5 { currency: string; maxLoan: string; } ⋮---- export interface PositionTierV5 { tier: string; borrowLimit: string; positionMMR: string; positionIMR: string; maxLeverage: string; } ⋮---- export interface CurrencyPositionTiersV5 { currency: string; positionTiersRatioList: PositionTierV5[]; } ⋮---- export interface CoinStateV5 { currency: string; spotLeverage: string; } ⋮---- export interface AvailableAmountToRepayV5 { currency: string; lossLessRepaymentAmount: string; } ⋮---- export interface ManualRepayWithoutConversionResultV5 { /** * Result status: * - P: Processing * - SU: Success * - FA: Failed */ resultStatus: 'P' | 'SU' | 'FA'; } ⋮---- /** * Result status: * - P: Processing * - SU: Success * - FA: Failed */ ================ File: src/types/response/v5-spreadtrading.ts ================ export interface SpreadInstrumentInfoV5 { symbol: string; contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; status: 'Trading' | 'Settling'; baseCoin: string; quoteCoin: string; settleCoin: string; tickSize: string; minPrice: string; maxPrice: string; lotSize: string; minSize: string; maxSize: string; launchTime: string; deliveryTime: string; legs: { symbol: string; contractType: 'LinearPerpetual' | 'LinearFutures' | 'Spot'; }[]; } ⋮---- export interface SpreadOrderbookResponseV5 { s: string; // Symbol b: [string, string][]; // Bids array [price, size] a: [string, string][]; // Asks array [price, size] u: number; // Update ID ts: number; // Timestamp seq: number; // Sequence cts: number; // Cross timestamp } ⋮---- s: string; // Symbol b: [string, string][]; // Bids array [price, size] a: [string, string][]; // Asks array [price, size] u: number; // Update ID ts: number; // Timestamp seq: number; // Sequence cts: number; // Cross timestamp ⋮---- export interface SpreadTickerV5 { symbol: string; // Spread combination symbol name bidPrice: string; // Bid 1 price bidSize: string; // Bid 1 size askPrice: string; // Ask 1 price askSize: string; // Ask 1 size lastPrice: string; // Last trade price highPrice24h: string; // The highest price in the last 24 hours lowPrice24h: string; // The lowest price in the last 24 hours prevPrice24h: string; // Price 24 hours ago volume24h: string; // Volume for 24h } ⋮---- symbol: string; // Spread combination symbol name bidPrice: string; // Bid 1 price bidSize: string; // Bid 1 size askPrice: string; // Ask 1 price askSize: string; // Ask 1 size lastPrice: string; // Last trade price highPrice24h: string; // The highest price in the last 24 hours lowPrice24h: string; // The lowest price in the last 24 hours prevPrice24h: string; // Price 24 hours ago volume24h: string; // Volume for 24h ⋮---- export interface SpreadRecentTradeV5 { execId: string; // Execution ID symbol: string; // Spread combination symbol name price: string; // Trade price size: string; // Trade size side: 'Buy' | 'Sell'; // Side of taker time: string; // Trade time (ms) seq?: string; } ⋮---- execId: string; // Execution ID symbol: string; // Spread combination symbol name price: string; // Trade price size: string; // Trade size side: 'Buy' | 'Sell'; // Side of taker time: string; // Trade time (ms) ⋮---- export interface SpreadOpenOrderV5 { symbol: string; baseCoin: string; orderType: 'Market' | 'Limit'; orderLinkId: string; side: 'Buy' | 'Sell'; timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; orderId: string; leavesQty: string; orderStatus: 'New' | 'PartiallyFilled'; cumExecQty: string; price: string; qty: string; createdTime: string; updatedTime: string; } ⋮---- export interface SpreadOrderHistoryV5 { symbol: string; orderType: 'Market' | 'Limit'; orderLinkId: string; orderId: string; contractType: 'FundingRateArb' | 'CarryTrade' | 'FutureSpread' | 'PerpBasis'; orderStatus: 'Rejected' | 'Cancelled' | 'Filled'; price: string; orderQty: string; timeInForce: 'GTC' | 'FOK' | 'IOC' | 'PostOnly'; baseCoin: string; createdAt: string; updatedAt: string; side: 'Buy' | 'Sell'; leavesQty: string; settleCoin: string; cumExecQty: string; qty: string; leg1Symbol: string; leg1ProdType: 'Futures' | 'Spot'; leg1OrderId: string; leg1Side: string; leg2ProdType: 'Futures' | 'Spot'; leg2OrderId: string; leg2Symbol: string; leg2Side: string; cxlRejReason: string; cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee } ⋮---- cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee ⋮---- export interface SpreadTradeLegV5 { symbol: string; side: 'Buy' | 'Sell'; execPrice: string; execTime: string; execValue: string; execType: string; category: 'linear' | 'spot'; execQty: string; execFee: string; feeCurrency: string; // Trading fee currency execId: string; } ⋮---- feeCurrency: string; // Trading fee currency ⋮---- export interface SpreadTradeV5 { symbol: string; orderLinkId: string; side: 'Buy' | 'Sell'; orderId: string; execPrice: string; execTime: string; execType: 'Trade'; execQty: string; execId: string; legs: SpreadTradeLegV5[]; extraFees: string; } ================ File: .eslintrc.cjs ================ // 'require-extensions', // only once moved to ESM ⋮---- // 'plugin:require-extensions/recommended', // only once moved to ESM ⋮---- // 'no-unused-vars': ['warn'], ================ File: src/types/response/v5-account.ts ================ import { AccountMarginModeV5, AccountTypeV5, CategoryV5, TransactionTypeV5, UnifiedUpdateStatusV5, } from '../shared-v5'; ⋮---- export interface WalletBalanceV5Coin { coin: string; equity: string; usdValue: string; walletBalance: string; free: string; // spot only locked: string; // spot only borrowAmount: string; availableToBorrow: string; // deprecated field availableToWithdraw: string; accruedInterest: string; totalOrderIM: string; totalPositionIM: string; totalPositionMM: string; unrealisedPnl: string; cumRealisedPnl: string; bonus: string; marginCollateral: boolean; collateralSwitch: boolean; spotBorrow: string; } ⋮---- free: string; // spot only locked: string; // spot only ⋮---- availableToBorrow: string; // deprecated field ⋮---- export interface WalletBalanceV5 { accountType: AccountTypeV5; accountLTV: string; accountIMRate: string; accountMMRate: string; accountIMRateByMp: string; accountMMRateByMp: string; totalInitialMarginByMp: string; totalMaintenanceMarginByMp: string; totalEquity: string; totalWalletBalance: string; totalMarginBalance: string; totalAvailableBalance: string; totalPerpUPL: string; totalInitialMargin: string; totalMaintenanceMargin: string; coin: WalletBalanceV5Coin[]; } ⋮---- export interface UnifiedAccountUpgradeResultV5 { unifiedUpdateStatus: UnifiedUpdateStatusV5; unifiedUpdateMsg: { msg: string[] | null; }; } ⋮---- export interface BorrowHistoryRecordV5 { currency: string; createdTime: number; borrowCost: string; hourlyBorrowRate: string; InterestBearingBorrowSize: string; costExemption: string; borrowAmount: string; unrealisedLoss: string; freeBorrowedAmount: string; } ⋮---- export interface CollateralInfoV5 { currency: string; hourlyBorrowRate: string; maxBorrowingAmount: string; freeBorrowAmount: string; freeBorrowingLimit: string; borrowAmount: string; availableToBorrow: string; borrowable: boolean; borrowUsageRate: string; marginCollateral: boolean; collateralSwitch: boolean; collateralRatio: string; } ⋮---- export interface CoinGreeksV5 { baseCoin: string; totalDelta: string; totalGamma: string; totalVega: string; totalTheta: string; } ⋮---- export interface FeeRateV5 { symbol: string; baseCoin: string; takerFeeRate: string; makerFeeRate: string; } ⋮---- export interface AccountInfoV5 { unifiedMarginStatus: number; marginMode: AccountMarginModeV5; isMasterTrader: boolean; spotHedgingStatus: string; updatedTime: string; } ⋮---- export interface TransactionLogV5 { symbol: string; category: CategoryV5; side: string; transactionTime: string; type: TransactionTypeV5; qty: string; size: string; currency: string; tradePrice: string; funding: string; fee: string; cashFlow: string; change: string; cashBalance: string; feeRate: string; bonusChange: string; tradeId: string; orderId: string; orderLinkId: string; extraFees: string; transSubType: string; } ⋮---- export interface MMPStateV5 { baseCoin: string; mmpEnabled: boolean; window: string; frozenPeriod: string; qtyLimit: string; deltaLimit: string; mmpFrozenUntil: string; mmpFrozen: boolean; } ⋮---- export interface RepayLiabilityResultV5 { coin: string; repaymentQty: string; } ⋮---- export interface DCPInfoV5 { product: 'SPOT' | 'DERIVATIVES' | 'OPTIONS'; dcpStatus: 'ON'; timeWindow: string; } ⋮---- export interface ManualRepayResultV5 { resultStatus: 'P' | 'SU' | 'FA'; } ================ File: src/types/response/v5-market.ts ================ import { CategoryCursorListV5, CategoryV5, ContractTypeV5, CopyTradingV5, InstrumentStatusV5, MarginTradingV5, OptionTypeV5, OrderSideV5, } from '../shared-v5'; ⋮---- /** * OHLCVT candle used by v5 APIs * * - list[0]: startTime string Start time of the candle (ms) * - list[1]: openPrice string Open price * - list[2]: highPrice string Highest price * - list[3]: lowPrice string Lowest price * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed * - list[5]: volume string Trade volume. Unit of contract: pieces of contract. Unit of spot: quantity of coins * - list[6]: turnover string Turnover. Unit of figure: quantity of quota coin */ export type OHLCVKlineV5 = [ string, string, string, string, string, string, string, ]; ⋮---- /** * OHLC candle used by v5 APIs * * - list[0]: startTime string Start time of the candle (ms) * - list[1]: openPrice string Open price * - list[2]: highPrice string Highest price * - list[3]: lowPrice string Lowest price * - list[4]: closePrice string Close price. Is the last traded price when the candle is not closed */ export type OHLCKlineV5 = [string, string, string, string, string]; ⋮---- export interface LinearInverseInstrumentInfoV5 { symbol: string; contractType: ContractTypeV5; status: InstrumentStatusV5; baseCoin: string; quoteCoin: string; symbolType: string; // The region to which the trading pair belongs launchTime: string; deliveryTime?: string; deliveryFeeRate?: string; priceScale: string; leverageFilter: { minLeverage: string; maxLeverage: string; leverageStep: string; }; priceFilter: { minPrice: string; maxPrice: string; tickSize: string; }; lotSizeFilter: { maxOrderQty: string; maxMktOrderQty: string; minOrderQty: string; qtyStep: string; postOnlyMaxOrderQty?: string; minNotionalValue?: string; }; unifiedMarginTrade: boolean; fundingInterval: number; settleCoin: string; copyTrading: CopyTradingV5; upperFundingRate: string; lowerFundingRate: string; riskParameters: { priceLimitRatioX: string; priceLimitRatioY: string; }; isPreListing: boolean; preListingInfo: { curAuctionPhase: string; phases: { phase: string; startTime: string; endTime: string; }[]; auctionFeeInfo: { auctionFeeRate: string; takerFeeRate: string; makerFeeRate: string; }; } | null; skipCallAuction?: boolean; // For USDT pre-market contract displayName: string; } ⋮---- symbolType: string; // The region to which the trading pair belongs ⋮---- skipCallAuction?: boolean; // For USDT pre-market contract ⋮---- export interface OptionInstrumentInfoV5 { symbol: string; optionsType: OptionTypeV5; status: InstrumentStatusV5; baseCoin: string; quoteCoin: string; settleCoin: string; symbolType: string; // The region to which the trading pair belongs launchTime: string; deliveryTime: string; deliveryFeeRate: string; priceFilter: { minPrice: string; maxPrice: string; tickSize: string; }; lotSizeFilter: { maxOrderQty: string; minOrderQty: string; qtyStep: string; }; displayName: string; } ⋮---- symbolType: string; // The region to which the trading pair belongs ⋮---- export interface SpotInstrumentInfoV5 { symbol: string; baseCoin: string; quoteCoin: string; symbolType: string; // The region to which the trading pair belongs innovation: '0' | '1'; // Deprecated, always 0 status: InstrumentStatusV5; marginTrading: MarginTradingV5; stTag: '0' | '1'; lotSizeFilter: { basePrecision: string; quotePrecision: string; minOrderQty: string; maxOrderQty: string; minOrderAmt: string; maxOrderAmt: string; maxLimitOrderQty: string; maxMarketOrderQty: string; postOnlyMaxLimitOrderSize: string; }; priceFilter: { tickSize: string; }; riskParameters: { priceLimitRatioX: string; priceLimitRatioY: string; }; forbidUplWithdrawal: boolean; } ⋮---- symbolType: string; // The region to which the trading pair belongs innovation: '0' | '1'; // Deprecated, always 0 ⋮---- type InstrumentInfoV5Mapping = { linear: LinearInverseInstrumentInfoV5[]; inverse: LinearInverseInstrumentInfoV5[]; option: OptionInstrumentInfoV5[]; spot: SpotInstrumentInfoV5[]; }; ⋮---- export type InstrumentInfoResponseV5 = CategoryCursorListV5; ⋮---- // Account Instruments Info (includes RPI permissions) export interface AccountSpotInstrumentInfoV5 extends SpotInstrumentInfoV5 { isPublicRpi: boolean; myRpiPermission: boolean; } ⋮---- export interface AccountLinearInverseInstrumentInfoV5 extends LinearInverseInstrumentInfoV5 { isPublicRpi: boolean; myRpiPermission: boolean; } ⋮---- type AccountInstrumentInfoV5Mapping = { linear: AccountLinearInverseInstrumentInfoV5[]; inverse: AccountLinearInverseInstrumentInfoV5[]; spot: AccountSpotInstrumentInfoV5[]; }; ⋮---- export type AccountInstrumentInfoResponseV5< C extends 'spot' | 'linear' | 'inverse', > = CategoryCursorListV5; ⋮---- /** * [price, size] */ export type OrderbookLevelV5 = [string, string]; ⋮---- export interface OrderbookResponseV5 { s: string; b: OrderbookLevelV5[]; a: OrderbookLevelV5[]; ts: number; u: number; seq: number; cts: number; } ⋮---- /** * RPI Orderbook level: [price, nonRpiSize, rpiSize] */ export type RPIOrderbookLevelV5 = [string, string, string]; ⋮---- export interface RPIOrderbookResponseV5 { s: string; // Symbol name b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order ts: number; // The timestamp (ms) that the system generates the data u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream seq: number; // Cross sequence cts: number; // The timestamp from the matching engine when this orderbook data is produced } ⋮---- s: string; // Symbol name b: RPIOrderbookLevelV5[]; // Bids. Sorted by price in descending order a: RPIOrderbookLevelV5[]; // Asks. Sorted by price in ascending order ts: number; // The timestamp (ms) that the system generates the data u: number; // Update ID, is always in sequence corresponds to u in the 50-level WebSocket RPI orderbook stream seq: number; // Cross sequence cts: number; // The timestamp from the matching engine when this orderbook data is produced ⋮---- export interface TickerLinearInverseV5 { symbol: string; lastPrice: string; indexPrice: string; markPrice: string; prevPrice24h: string; price24hPcnt: string; highPrice24h: string; lowPrice24h: string; prevPrice1h: string; openInterest: string; openInterestValue: string; turnover24h: string; volume24h: string; fundingRate: string; nextFundingTime: string; predictedDeliveryPrice: string; basisRate: string; basisRateYear: string; fundingIntervalHour: string; fundingCap: string; deliveryFeeRate: string; deliveryTime: string; ask1Size: string; bid1Price: string; ask1Price: string; bid1Size: string; preOpenPrice: string; preQty: string; curPreListingPhase: string; basis: string; } ⋮---- export interface TickerOptionV5 { symbol: string; bid1Price: string; bid1Size: string; bid1Iv: string; ask1Price: string; ask1Size: string; ask1Iv: string; lastPrice: string; highPrice24h: string; lowPrice24h: string; markPrice: string; indexPrice: string; markIv: string; underlyingPrice: string; openInterest: string; turnover24h: string; volume24h: string; totalVolume: string; totalTurnover: string; delta: string; gamma: string; vega: string; theta: string; predictedDeliveryPrice: string; change24h: string; } ⋮---- export interface TickerSpotV5 { symbol: string; bid1Price: string; bid1Size: string; ask1Price: string; ask1Size: string; lastPrice: string; prevPrice24h: string; price24hPcnt: string; highPrice24h: string; lowPrice24h: string; turnover24h: string; volume24h: string; usdIndexPrice: string; } ⋮---- export interface FundingRateHistoryResponseV5 { symbol: string; fundingRate: string; fundingRateTimestamp: string; } ⋮---- export interface PublicTradeV5 { execId: string; symbol: string; price: string; size: string; side: OrderSideV5; time: string; isBlockTrade: boolean; isRPITrade: boolean; mP?: string; iP?: string; mIv?: string; iv?: string; seq?: string; } ⋮---- /** * * - openInterest string Open interest * - timestamp string The timestamp (ms) */ export type OpenInterestV5 = { openInterest: string; timestamp: string; }; ⋮---- export interface OpenInterestResponseV5 { category: 'linear' | 'inverse'; symbol: string; list: OpenInterestV5[]; nextPageCursor?: string; } ⋮---- export interface HistoricalVolatilityV5 { period: number; value: string; time: string; } ⋮---- export interface InsuranceDataV5 { coin: string; symbols: string; balance: string; value: string; } ⋮---- export interface InsuranceResponseV5 { updatedTime: string; list: InsuranceDataV5[]; } ⋮---- export interface RiskLimitV5 { id: number; symbol: string; riskLimitValue: string; maintenanceMargin: number; initialMargin: number; // eslint-disable-next-line @typescript-eslint/no-explicit-any section: any; isLowestRisk: 0 | 1; maxLeverage: string; mmDeduction: string; nextPageCursor?: string; } ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- /** @deprecated use DeliveryPriceV5 instead */ export interface OptionDeliveryPriceV5 { symbol: string; deliveryPrice: string; deliveryTime: string; } ⋮---- export interface DeliveryPriceV5 { symbol: string; deliveryPrice: string; deliveryTime: string; } ⋮---- export interface LongShortRatioV5 { symbol: string; buyRatio: string; sellRatio: string; timestamp: string; } ⋮---- export interface OrderPriceLimitV5 { symbol: string; buyLmt: string; sellLmt: string; ts: string; } ⋮---- export interface IndexPriceComponentV5 { exchange: string; // Name of the exchange spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) equivalentPrice: string; // Equivalent price multiplier: string; // Multiplier used for the component price price: string; // Actual price weight: string; // Weight in the index calculation } ⋮---- exchange: string; // Name of the exchange spotPair: string; // Spot trading pair on the exchange (e.g., BTCUSDT) equivalentPrice: string; // Equivalent price multiplier: string; // Multiplier used for the component price price: string; // Actual price weight: string; // Weight in the index calculation ⋮---- export interface IndexPriceComponentsResponseV5 { indexName: string; // Name of the index (e.g., BTCUSDT) lastPrice: string; // Last price of the index updateTime: string; // Timestamp of the last update in milliseconds components: IndexPriceComponentV5[]; // List of components contributing to the index price } ⋮---- indexName: string; // Name of the index (e.g., BTCUSDT) lastPrice: string; // Last price of the index updateTime: string; // Timestamp of the last update in milliseconds components: IndexPriceComponentV5[]; // List of components contributing to the index price ⋮---- export interface ADLAlertItemV5 { coin: string; // Token of the insurance pool symbol: string; // Trading pair name balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL } ⋮---- coin: string; // Token of the insurance pool symbol: string; // Trading pair name balance: string; // Balance of the insurance fund. Used to determine if ADL is triggered maxBalance: string; // Maximum balance of the insurance pool in the last 8 hours insurancePnlRatio: string; // PnL ratio threshold for triggering contract PnL drawdown ADL pnlRatio: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped adlTriggerThreshold: string; // Trigger threshold for contract PnL drawdown ADL adlStopRatio: string; // Stop ratio threshold for contract PnL drawdown ADL ⋮---- export interface ADLAlertResponseV5 { updateTime: string; // Latest data update timestamp (ms) list: ADLAlertItemV5[]; // List of ADL alert items } ⋮---- updateTime: string; // Latest data update timestamp (ms) list: ADLAlertItemV5[]; // List of ADL alert items ⋮---- export interface FeeGroupLevelV5 { level: string; // Pro level name or Market Maker level name takerFeeRate: string; // Taker fee rate makerFeeRate: string; // Maker fee rate makerRebate: string; // Maker rebate fee rate } ⋮---- level: string; // Pro level name or Market Maker level name takerFeeRate: string; // Taker fee rate makerFeeRate: string; // Maker fee rate makerRebate: string; // Maker rebate fee rate ⋮---- export interface FeeGroupRatesV5 { pro: FeeGroupLevelV5[]; // Pro-level fee structures marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures } ⋮---- pro: FeeGroupLevelV5[]; // Pro-level fee structures marketMaker: FeeGroupLevelV5[]; // Market Maker-level fee structures ⋮---- export interface FeeGroupItemV5 { groupName: string; // Fee group name weightingFactor: number; // Group weighting factor symbolsNumbers: number; // Symbols number symbols: string[]; // Symbol names feeRates: FeeGroupRatesV5; // Fee rate details for different categories updateTime: string; // Latest data update timestamp (ms) } ⋮---- groupName: string; // Fee group name weightingFactor: number; // Group weighting factor symbolsNumbers: number; // Symbols number symbols: string[]; // Symbol names feeRates: FeeGroupRatesV5; // Fee rate details for different categories updateTime: string; // Latest data update timestamp (ms) ⋮---- export interface FeeGroupStructureResponseV5 { list: FeeGroupItemV5[]; // List of fee group objects } ⋮---- list: FeeGroupItemV5[]; // List of fee group objects ================ File: src/types/shared-v5.ts ================ export type CategoryV5 = 'spot' | 'linear' | 'inverse' | 'option'; export type ContractTypeV5 = | 'InversePerpetual' | 'LinearPerpetual' | 'InverseFutures'; export type CopyTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalOnly'; ⋮---- export type InstrumentStatusV5 = | 'PreLaunch' | 'Trading' | 'Settling' | 'Delivering' | 'Closed'; ⋮---- export type MarginTradingV5 = 'none' | 'both' | 'utaOnly' | 'normalSpotOnly'; ⋮---- export type OrderFilterV5 = 'Order' | 'tpslOrder' | 'StopOrder'; export type OrderSideV5 = 'Buy' | 'Sell'; export type OrderTypeV5 = 'Market' | 'Limit'; export type OrderTimeInForceV5 = 'GTC' | 'IOC' | 'FOK' | 'PostOnly' | 'RPI'; export type OrderTriggerByV5 = 'LastPrice' | 'IndexPrice' | 'MarkPrice'; export type OCOTriggerTypeV5 = | 'OcoTriggerByUnknown' | 'OcoTriggerTp' | 'OcoTriggerBySl'; ⋮---- export type OrderSMPTypeV5 = | 'None' | 'CancelMaker' | 'CancelTaker' | 'CancelBoth'; ⋮---- export type OrderStatusV5 = | 'Created' | 'New' | 'Rejected' | 'PartiallyFilled' | 'PartiallyFilledCanceled' | 'Filled' | 'Cancelled' | 'Untriggered' | 'Triggered' | 'Deactivated' | 'Active'; ⋮---- /** * Defines the types of order creation mechanisms. */ export type OrderCreateTypeV5 = /** Represents an order created by a user. */ | 'CreateByUser' /** Represents an order created by an admin closing. */ | 'CreateByAdminClosing' /** Futures conditional order. */ | 'CreateByStopOrder' /** Futures take profit order. */ | 'CreateByTakeProfit' /** Futures partial take profit order. */ | 'CreateByPartialTakeProfit' /** Futures stop loss order. */ | 'CreateByStopLoss' /** Futures partial stop loss order. */ | 'CreateByPartialStopLoss' /** Futures trailing stop order. */ | 'CreateByTrailingStop' /** Laddered liquidation to reduce the required maintenance margin. */ | 'CreateByLiq' /** * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. */ | 'CreateByTakeOver_PassThrough' /** Auto-Deleveraging(ADL) */ | 'CreateByAdl_PassThrough' /** Order placed via Paradigm. */ | 'CreateByBlock_PassThrough' /** Order created by move position. */ | 'CreateByBlockTradeMovePosition_PassThrough' /** The close order placed via web or app position area - web/app. */ | 'CreateByClosing' /** Order created via grid bot - web/app. */ | 'CreateByFGridBot' /** Order closed via grid bot - web/app. */ | 'CloseByFGridBot' /** Order created by TWAP - web/app. */ | 'CreateByTWAP' /** Order created by TV webhook - web/app. */ | 'CreateByTVSignal' /** Order created by Mm rate close function - web/app. */ | 'CreateByMmRateClose' /** Order created by Martingale bot - web/app. */ | 'CreateByMartingaleBot' /** Order closed by Martingale bot - web/app. */ | 'CloseByMartingaleBot' /** Order created by Ice berg strategy - web/app. */ | 'CreateByIceBerg' /** Order created by arbitrage - web/app. */ | 'CreateByArbitrage' /** Option dynamic delta hedge order - web/app */ | 'CreateByDdh' /** BBO Order - Best Bid/Offer order */ | 'CreateByBboOrder'; ⋮---- /** Represents an order created by a user. */ ⋮---- /** Represents an order created by an admin closing. */ ⋮---- /** Futures conditional order. */ ⋮---- /** Futures take profit order. */ ⋮---- /** Futures partial take profit order. */ ⋮---- /** Futures stop loss order. */ ⋮---- /** Futures partial stop loss order. */ ⋮---- /** Futures trailing stop order. */ ⋮---- /** Laddered liquidation to reduce the required maintenance margin. */ ⋮---- /** * If the position is still subject to liquidation (i.e., does not meet the required maintenance margin level), * the position shall be taken over by the liquidation engine and closed at the bankruptcy price. */ ⋮---- /** Auto-Deleveraging(ADL) */ ⋮---- /** Order placed via Paradigm. */ ⋮---- /** Order created by move position. */ ⋮---- /** The close order placed via web or app position area - web/app. */ ⋮---- /** Order created via grid bot - web/app. */ ⋮---- /** Order closed via grid bot - web/app. */ ⋮---- /** Order created by TWAP - web/app. */ ⋮---- /** Order created by TV webhook - web/app. */ ⋮---- /** Order created by Mm rate close function - web/app. */ ⋮---- /** Order created by Martingale bot - web/app. */ ⋮---- /** Order closed by Martingale bot - web/app. */ ⋮---- /** Order created by Ice berg strategy - web/app. */ ⋮---- /** Order created by arbitrage - web/app. */ ⋮---- /** Option dynamic delta hedge order - web/app */ ⋮---- /** BBO Order - Best Bid/Offer order */ ⋮---- export type OrderCancelTypeV5 = | 'CancelByUser' | 'CancelByReduceOnly' | 'CancelByPrepareLiq' | 'CancelAllBeforeLiq' | 'CancelByPrepareAdl' | 'CancelAllBeforeAdl' | 'CancelByAdmin' | 'CancelByTpSlTsClear' | 'CancelByPzSideCh' | 'UNKNOWN'; ⋮---- export type OrderRejectReasonV5 = | 'EC_NoError' | 'EC_Others' | 'EC_UnknownMessageType' | 'EC_MissingClOrdID' | 'EC_MissingOrigClOrdID' | 'EC_ClOrdIDOrigClOrdIDAreTheSame' | 'EC_DuplicatedClOrdID' | 'EC_OrigClOrdIDDoesNotExist' | 'EC_TooLateToCancel' | 'EC_UnknownOrderType' | 'EC_UnknownSide' | 'EC_UnknownTimeInForce' | 'EC_WronglyRouted' | 'EC_MarketOrderPriceIsNotZero' | 'EC_LimitOrderInvalidPrice' | 'EC_NoEnoughQtyToFill' | 'EC_NoImmediateQtyToFill' | 'EC_PerCancelRequest' | 'EC_MarketOrderCannotBePostOnly' | 'EC_PostOnlyWillTakeLiquidity' | 'EC_CancelReplaceOrder' | 'EC_InvalidSymbolStatus'; ⋮---- export type StopOrderTypeV5 = | 'TakeProfit' | 'StopLoss' | 'TrailingStop' | 'Stop' | 'PartialTakeProfit' | 'PartialStopLoss' | 'tpslOrder' | 'OcoOrder' | 'MmRateClose' | 'BidirectionalTpslOrder'; ⋮---- /** * Position index. Used to identify positions in different position modes. * * - 0 one-way mode position * - 1 Buy side of hedge-mode position * - 2 Sell side of hedge-mode position */ export type PositionIdx = 0 | 1 | 2; ⋮---- /** * Position status. * * - 'Normal' * - 'Liq' in the liquidation progress * - 'Adl' in the auto-deleverage progress */ export type PositionStatusV5 = 'Normal' | 'Liq' | 'Adl'; export type PositionSideV5 = 'Buy' | 'Sell' | 'None' | ''; ⋮---- export type OptionTypeV5 = 'Call' | 'Put'; ⋮---- /** * Trade mode. * * - 0 cross-margin, * - 1 isolated margin */ export type TradeModeV5 = 0 | 1; ⋮---- export type TPSLModeV5 = 'Full' | 'Partial'; export type AccountMarginModeV5 = | 'ISOLATED_MARGIN' | 'REGULAR_MARGIN' | 'PORTFOLIO_MARGIN'; export type UnifiedUpdateStatusV5 = 'FAIL' | 'PROCESS' | 'SUCCESS'; ⋮---- export type AccountTypeV5 = | 'CONTRACT' | 'SPOT' | 'INVESTMENT' | 'OPTION' | 'UNIFIED' | 'FUND'; ⋮---- export type TransactionTypeV5 = | 'TRANSFER_IN' | 'TRANSFER_OUT' | 'TRADE' | 'SETTLEMENT' | 'DELIVERY' | 'LIQUIDATION' | 'ADL' | 'AIRDROP' | 'BONUS_RECOLLECT' | 'BONUS_RECOLLECT' | 'FEE_REFUND' | 'INTEREST' | 'CURRENCY_BUY' | 'CURRENCY_SELL' | 'BORROWED_AMOUNT_INS_LOAN' | 'PRINCIPLE_REPAYMENT_INS_LOAN' | 'INTEREST_REPAYMENT_INS_LOAN' | 'AUTO_SOLD_COLLATERAL_INS_LOAN' | 'AUTO_BUY_LIABILITY_INS_LOAN' | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' | 'TRANSFER_IN_INS_LOAN' | 'TRANSFER_OUT_INS_LOAN' | 'SPOT_REPAYMENT_SELL' | 'SPOT_REPAYMENT_BUY' | 'TOKENS_SUBSCRIPTION' | 'TOKENS_REDEMPTION' | 'AUTO_DEDUCTION' | 'FLEXIBLE_STAKING_SUBSCRIPTION' | 'FLEXIBLE_STAKING_REDEMPTION' | 'FIXED_STAKING_SUBSCRIPTION' | 'BORROWED_AMOUNT_INS_LOAN' | 'PRINCIPLE_REPAYMENT_INS_LOAN' | 'INTEREST_REPAYMENT_INS_LOAN' | 'AUTO_SOLD_COLLATERAL_INS_LOAN' | 'AUTO_BUY_LIABILITY_INS_LOAN' | 'AUTO_PRINCIPLE_REPAYMENT_INS_LOAN' | 'AUTO_INTEREST_REPAYMENT_INS_LOAN' | 'TRANSFER_IN_INS_LOAN' | 'TRANSFER_OUT_INS_LOAN' | 'SPOT_REPAYMENT_SELL' | 'SPOT_REPAYMENT_BUY' | 'TOKENS_SUBSCRIPTION' | 'TOKENS_REDEMPTION' | 'AUTO_DEDUCTION' | 'FLEXIBLE_STAKING_SUBSCRIPTION' | 'FLEXIBLE_STAKING_REDEMPTION' | 'FIXED_STAKING_SUBSCRIPTION' | 'FLEXIBLE_STAKING_REFUND' | 'FIXED_STAKING_REFUND' | 'PREMARKET_TRANSFER_OUT' | 'PREMARKET_DELIVERY_SELL_NEW_COIN' | 'PREMARKET_DELIVERY_BUY_NEW_COIN' | 'PREMARKET_DELIVERY_PLEDGE_PAY_SELLER' | 'PREMARKET_DELIVERY_PLEDGE_BACK' | 'PREMARKET_ROLLBACK_PLEDGE_BACK' | 'PREMARKET_ROLLBACK_PLEDGE_PENALTY_TO_BUYER' | 'CUSTODY_NETWORK_FEE' | 'CUSTODY_SETTLE_FEE' | 'CUSTODY_LOCK' | 'CUSTODY_UNLOCK' | 'CUSTODY_UNLOCK_REFUND' | 'LOANS_BORROW_FUNDS' | 'LOANS_PLEDGE_ASSET' | 'BONUS_TRANSFER_IN' | 'BONUS_TRANSFER_OUT' | 'PEF_TRANSFER_IN' | 'PEF_TRANSFER_OUT' | 'PEF_PROFIT_SHARE' | 'ONCHAINEARN_SUBSCRIPTION' | 'ONCHAINEARN_REDEMPTION' | 'ONCHAINEARN_REFUND' | 'STRUCTURE_PRODUCT_SUBSCRIPTION' | 'STRUCTURE_PRODUCT_REFUND' | 'CLASSIC_WEALTH_MANAGEMENT_SUBSCRIPTION' | 'PREMIMUM_WEALTH_MANAGEMENT_SUBSCRIPTION' | 'PREMIMUM_WEALTH_MANAGEMENT_REFUND' | 'LIQUIDITY_MINING_SUBSCRIPTION' | 'LIQUIDITY_MINING_REFUND' | 'PWM_SUBSCRIPTION' | 'PWM_REFUND' | 'DEFI_INVESTMENT_SUBSCRIPTION' | 'DEFI_INVESTMENT_REFUND' | 'DEFI_INVESTMENT_REDEMPTION' | 'INSTITUTION_LOAN_IN' | 'INSTITUTION_PAYBACK_PRINCIPAL_OUT' | 'INSTITUTION_PAYBACK_INTEREST_OUT' | 'INSTITUTION_EXCHANGE_SELL' | 'INSTITUTION_EXCHANGE_BUY' | 'INSTITUTION_LIQ_PRINCIPAL_OUT' | 'INSTITUTION_LIQ_INTEREST_OUT' | 'INSTITUTION_LOAN_TRANSFER_IN' | 'INSTITUTION_LOAN_TRANSFER_OUT' | 'INSTITUTION_LOAN_WITHOUT_WITHDRAW' | 'INSTITUTION_LOAN_RESERVE_IN' | 'INSTITUTION_LOAN_RESERVE_OUT' | 'PLATFORM_TOKEN_MNT_LIQRECALLEDMMNT' | 'PLATFORM_TOKEN_MNT_LIQRETURNEDMNT'; ⋮---- export type PermissionTypeV5 = | 'ContractTrade' | 'Spot' | 'Wallet' | 'Options' | 'Derivatives' | 'Exchange' | 'NFT'; ⋮---- /** * Leveraged token status: * * - '1' LT can be purchased and redeemed * - '2' LT can be purchased, but not redeemed * - '3' LT can be redeemed, but not purchased * - '4' LT cannot be purchased nor redeemed * - '5' Adjusting position */ export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5'; ⋮---- /** * Leveraged token order type: '1': purchase, '2': redeem */ export type LTOrderTypeV5 = '1' | '2'; ⋮---- /** * Leveraged token order status: '1': completed, '2': in progress, '3': failed */ export type LTOrderStatusV5 = '1' | '2' | '3'; ⋮---- export type ExecTypeV5 = | 'Trade' | 'AdlTrade' | 'Funding' | 'BustTrade' | 'Settle' | 'BlockTrade' | 'MovePosition' | 'UNKNOWN'; ⋮---- /** * Withdraw type. 0(default): on chain. 1: off chain. 2: all. */ export type WithdrawalTypeV5 = '0' | '1' | '2'; ⋮---- export interface PermissionsV5 { ContractTrade?: string[]; Spot?: string[]; Wallet?: string[]; Options?: string[]; Derivatives?: string[]; CopyTrading?: string[]; BlockTrade?: string[]; Exchange?: string[]; /** @deprecated , always returns []*/ NFT?: string[]; } ⋮---- /** @deprecated , always returns []*/ ⋮---- export interface CategoryCursorListV5< T extends unknown[], TCategory extends CategoryV5 = CategoryV5, > { category: TCategory; list: T; nextPageCursor?: string; } ⋮---- /** * Next page cursor does not exist for spot! */ export interface CursorListV5 { nextPageCursor: string; list: T; } ⋮---- /** * A wrapper type for any responses that have a "nextPageCursor" property, and a "rows" property with an array of elements * * ```{ nextPageCursor: "something", rows: someData[] }``` */ export interface CursorRowsV5 { nextPageCursor: string; rows: T; } ⋮---- export interface CategoryListV5< T extends unknown[], TCategory extends CategoryV5, > { category: TCategory; list: T; } ⋮---- export interface CategorySymbolListV5< T extends unknown[], TCategory extends CategoryV5, > { category: TCategory; symbol: string; list: T; } ⋮---- export interface GetSystemStatusParamsV5 { id?: string; state?: string; } ⋮---- export interface SystemStatusItemV5 { id: string; title: string; state: string; begin: string; end: string; href: string; serviceTypes: number[]; product: number[]; uidSuffix: number[]; maintainType: string; env: string; } ================ 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 lib bundleReport.html .history/ rawReq.ts localtest.sh localtest.ts privaterepotracker restClientRegex.ts repomix.sh examples/ignored examples/ts-testnet-private.ts examples/ts-testnet-trade.ts examples/ts-testnet.ts ================ File: src/types/websockets/ws-events.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { RFQItemV5, RFQPublicTradeV5, RFQQuoteItemV5, RFQTradeV5, } from '../response/v5-rfq'; import { CategoryV5, ExecTypeV5, OCOTriggerTypeV5, OrderCancelTypeV5, OrderCreateTypeV5, OrderRejectReasonV5, OrderSideV5, OrderSMPTypeV5, OrderStatusV5, OrderTimeInForceV5, OrderTriggerByV5, OrderTypeV5, PositionIdx, PositionSideV5, PositionStatusV5, StopOrderTypeV5, SystemStatusItemV5, TPSLModeV5, TradeModeV5, } from '../shared-v5'; import { WsKey } from './ws-general'; ⋮---- export interface MessageEventLike { target: WebSocket; type: 'message'; data: string; } ⋮---- export function isMessageEvent(msg: unknown): msg is MessageEventLike ⋮---- export interface WSPublicTopicEventV5 { id?: string; topic: TTopic; type: TType; /** Cross sequence */ cs?: number; /** Event timestamp */ ts: number; data: TData; /** * matching engine timestamp (correlated with T from public trade channel) */ cts: number; /** * Internal reference, can be used to determine if this is spot/linear/inverse/etc */ wsKey: WsKey; } ⋮---- /** Cross sequence */ ⋮---- /** Event timestamp */ ⋮---- /** * matching engine timestamp (correlated with T from public trade channel) */ ⋮---- /** * Internal reference, can be used to determine if this is spot/linear/inverse/etc */ ⋮---- export interface WSPrivateTopicEventV5 { id?: string; topic: TTopic; creationTime: number; data: TData; wsKey: WsKey; } ⋮---- export interface WSOrderbookV5 { /** Symbol */ s: string; /** [price, qty][] */ b: [string, string][]; /** [price, qty][] */ a: [string, string][]; /** Update ID */ u: number; /** Cross sequence */ seq: number; } ⋮---- /** Symbol */ ⋮---- /** [price, qty][] */ ⋮---- /** [price, qty][] */ ⋮---- /** Update ID */ ⋮---- /** Cross sequence */ ⋮---- export type WSOrderbookEventV5 = WSPublicTopicEventV5< string, 'delta' | 'snapshot', WSOrderbookV5 >; ⋮---- export interface WSTradeV5 { T: number; s: string; S: OrderSideV5; v: string; p: string; L?: string; i: string; BT: boolean; RPI?: boolean; mP?: string; iP?: string; mIv?: string; iv?: string; } ⋮---- export type WSTradeEventV5 = WSPublicTopicEventV5< string, 'snapshot', WSTradeV5[] >; ⋮---- /** * WSTickerV5 is the data structure for the "linear" ticker channel * */ export interface WSTickerV5 { symbol: string; tickDirection: string; price24hPcnt: string; lastPrice: string; prevPrice24h: string; highPrice24h: string; lowPrice24h: string; prevPrice1h: string; markPrice: string; indexPrice: string; openInterest: string; openInterestValue: string; turnover24h: string; volume24h: string; nextFundingTime: string; fundingRate: string; bid1Price: string; bid1Size: string; ask1Price: string; ask1Size: string; deliveryTime?: string; basisRate?: string; deliveryFeeRate?: string; predictedDeliveryPrice?: string; preOpenPrice?: string; preQty?: string; curPreListingPhase?: string; } ⋮---- export interface WSTickerOptionV5 { symbol: string; bidPrice: string; bidSize: string; bidIv: string; askPrice: string; askSize: string; askIv: string; lastPrice: string; highPrice24h: string; lowPrice24h: string; markPrice: string; indexPrice: string; markPriceIv: string; underlyingPrice: string; openInterest: string; turnover24h: string; volume24h: string; totalVolume: string; totalTurnover: string; delta: string; gamma: string; vega: string; theta: string; predictedDeliveryPrice: string; change24h: string; } ⋮---- export interface WSTickerSpotV5 { symbol: string; lastPrice: string; highPrice24h: string; lowPrice24h: string; prevPrice24h: string; volume24h: string; turnover24h: string; price24hPcnt: string; usdIndexPrice: string; } ⋮---- export type WSTickerEventV5 = WSPublicTopicEventV5< string, 'snapshot' | 'delta', WSTickerV5 | WSTickerOptionV5 | WSTickerSpotV5 >; ⋮---- export interface WSKlineV5 { start: number; end: number; interval: string; open: string; close: string; high: string; low: string; volume: string; turnover: string; confirm: boolean; timestamp: number; } ⋮---- export type WSKlineEventV5 = WSPublicTopicEventV5< string, 'snapshot', WSKlineV5[] >; ⋮---- export interface WSLiquidationV5 { T: number; s: string; S: OrderSideV5; v: string; p: string; } ⋮---- export type WSLiquidationEventV5 = WSPublicTopicEventV5< string, 'snapshot', WSLiquidationV5[] >; ⋮---- export interface WSPositionV5 { category: string; symbol: string; side: PositionSideV5; size: string; positionIdx: PositionIdx; tradeMode: TradeModeV5; positionValue: string; riskId: number; riskLimitValue: string; entryPrice: string; markPrice: string; leverage: string; positionBalance: string; autoAddMargin: number; positionMM: string; positionIM: string; positionIMByMp: string; positionMMByMp: string; liqPrice: string; bustPrice: string; tpslMode: string; takeProfit: string; stopLoss: string; trailingStop: string; unrealisedPnl: string; curRealisedPnl: string; sessionAvgPrice: string; delta: string; gamma: string; vega: string; theta: string; cumRealisedPnl: string; positionStatus: PositionStatusV5; adlRankIndicator: number; isReduceOnly: boolean; mmrSysUpdatedTime: string; leverageSysUpdatedTime: string; createdTime: string; updatedTime: string; seq: number; } ⋮---- export type WSPositionEventV5 = WSPrivateTopicEventV5< 'position', WSPositionV5[] >; ⋮---- export interface WSAccountOrderV5 { category: CategoryV5; orderId: string; orderLinkId: string; isLeverage: string; blockTradeId: string; symbol: string; price: string; qty: string; side: OrderSideV5; positionIdx: PositionIdx; orderStatus: OrderStatusV5; createType: OrderCreateTypeV5; cancelType: OrderCancelTypeV5; rejectReason?: OrderRejectReasonV5; avgPrice?: string; leavesQty?: string; leavesValue?: string; cumExecQty: string; cumExecValue: string; cumExecFee: string; closedPnl: string; feeCurrency: string; timeInForce: OrderTimeInForceV5; orderType: OrderTypeV5; stopOrderType: StopOrderTypeV5; ocoTriggerType?: OCOTriggerTypeV5; orderIv: string; marketUnit?: 'baseCoin' | 'quoteCoin'; triggerPrice: string; takeProfit: string; stopLoss: string; tpslMode?: TPSLModeV5; tpLimitPrice?: string; slLimitPrice?: string; tpTriggerBy: string; slTriggerBy: string; triggerDirection: number; triggerBy: OrderTriggerByV5; lastPriceOnCreated: string; reduceOnly: boolean; closeOnTrigger: boolean; placeType: string; smpType: OrderSMPTypeV5; smpGroup: number; smpOrderId: string; createdTime: string; updatedTime: string; cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency } ⋮---- cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency ⋮---- export type WSAccountOrderEventV5 = WSPrivateTopicEventV5< 'order', WSAccountOrderV5[] >; ⋮---- export interface WSExecutionV5 { category: CategoryV5; symbol: string; isLeverage: string; orderId: string; orderLinkId: string; side: OrderSideV5; orderPrice: string; orderQty: string; leavesQty: string; createType: OrderCreateTypeV5; orderType: OrderTypeV5; stopOrderType: StopOrderTypeV5; execFee: string; feeCurrency: string; // Trading fee currency execId: string; execPrice: string; execQty: string; execPnl: string; execType: ExecTypeV5; execValue: string; execTime: string; isMaker: boolean; feeRate: string; tradeIv: string; markIv: string; markPrice: string; indexPrice: string; underlyingPrice: string; blockTradeId: string; closedSize: string; extraFees: string; seq: number; marketUnit: string; } ⋮---- feeCurrency: string; // Trading fee currency ⋮---- export type WSExecutionEventV5 = WSPrivateTopicEventV5< 'execution', WSExecutionV5[] >; ⋮---- export interface WSExecutionFastV5 { category: CategoryV5; symbol: string; execId: string; execPrice: string; execQty: string; orderId: string; isMaker: boolean; orderLinkId: string; side: OrderSideV5; execTime: string; seq: number; } ⋮---- export type WSExecutionFastEventV5 = WSPrivateTopicEventV5< 'execution.fast', WSExecutionFastV5[] >; ⋮---- export interface WSCoinV5 { coin: string; equity: string; usdValue: string; walletBalance: string; free?: string; locked: string; spotHedgingQty: string; borrowAmount: string; availableToBorrow: string; availableToWithdraw: string; accruedInterest: string; totalOrderIM: string; totalPositionIM: string; totalPositionMM: string; unrealisedPnl: string; cumRealisedPnl: string; bonus: string; collateralSwitch: boolean; marginCollateral: boolean; spotBorrow: string; } ⋮---- export interface WSWalletV5 { accountType: string; accountLTV: string; accountIMRate: string; accountMMRate: string; accountIMRateByMp: string; accountMMRateByMp: string; totalInitialMarginByMp: string; totalMaintenanceMarginByMp: string; totalEquity: string; totalWalletBalance: string; totalMarginBalance: string; totalAvailableBalance: string; totalPerpUPL: string; totalInitialMargin: string; totalMaintenanceMargin: string; coin: WSCoinV5[]; } ⋮---- export type WSWalletEventV5 = WSPrivateTopicEventV5<'wallet', WSWalletV5[]>; ⋮---- export interface WSGreeksV5 { baseCoin: string; totalDelta: string; totalGamma: string; totalVega: string; totalTheta: string; } ⋮---- export type WSGreeksEventV5 = WSPrivateTopicEventV5<'greeks', WSGreeksV5[]>; ⋮---- export interface WSSpreadOrderV5 { category: 'combination' | 'spot_leg' | 'future_leg'; symbol: string; parentOrderId: string; orderId: string; orderLinkId: string; side: OrderSideV5; orderStatus: OrderStatusV5; cancelType: OrderCancelTypeV5; rejectReason: OrderRejectReasonV5; timeInForce: OrderTimeInForceV5; price: string; qty: string; avgPrice: string; leavesQty: string; leavesValue: string; cumExecQty: string; cumExecValue: string; cumExecFee: string; orderType: OrderTypeV5; isLeverage: string; createdTime: string; updatedTime: string; feeCurrency: string; createType: OrderCreateTypeV5; closedPnl: string; cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency } ⋮---- cumFeeDetail?: Record; // Cumulative trading fee details instead of cumExecFee and feeCurrency ⋮---- export type WSSpreadOrderEventV5 = WSPrivateTopicEventV5< 'spread.order', WSSpreadOrderV5[] >; ⋮---- export interface WSSpreadExecutionV5 { category: 'combination' | 'spot_leg' | 'future_leg'; symbol: string; isLeverage: string; orderId: string; orderLinkId: string; side: OrderSideV5; orderPrice: string; orderQty: string; leavesQty: string; createType: OrderCreateTypeV5; orderType: OrderTypeV5; execFee: string; execFeeV2: string; feeCurrency: string; // Trading fee currency parentExecId: string; execId: string; execPrice: string; execQty: string; execPnl: string; execType: ExecTypeV5; execValue: string; execTime: string; isMaker: boolean; feeRate: string; markPrice: string; closedSize: string; seq: number; } ⋮---- feeCurrency: string; // Trading fee currency ⋮---- export type WSSpreadExecutionEventV5 = WSPrivateTopicEventV5< 'spread.execution', WSSpreadExecutionV5[] >; ⋮---- export interface WSInsuranceV5 { coin: string; symbols: string; balance: string; updateTime: string; } ⋮---- export type WSInsuranceEventV5 = WSPublicTopicEventV5< 'insurance.USDT' | 'insurance.USDC' | 'insurance.inverse', 'snapshot' | 'delta', WSInsuranceV5[] >; ⋮---- export interface WSPriceLimitV5 { symbol: string; buyLmt: string; sellLmt: string; } ⋮---- export type WSPriceLimitEventV5 = WSPublicTopicEventV5< string, 'snapshot', WSPriceLimitV5 >; ⋮---- export interface WSADLAlertV5 { c: string; // Token of the insurance pool s: string; // Trading pair name b: string; // Balance of the insurance fund. Used to determine if ADL is triggered mb: string; // Maximum balance of the insurance pool in the last 8 hours i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped adl_tt: string; // Trigger threshold for contract PnL drawdown ADL adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL } ⋮---- c: string; // Token of the insurance pool s: string; // Trading pair name b: string; // Balance of the insurance fund. Used to determine if ADL is triggered mb: string; // Maximum balance of the insurance pool in the last 8 hours i_pr: string; // PnL ratio threshold for triggering contract PnL drawdown ADL pr: string; // Symbol's PnL drawdown ratio in the last 8 hours. Used to determine whether ADL is triggered or stopped adl_tt: string; // Trigger threshold for contract PnL drawdown ADL adl_sr: string; // Stop ratio threshold for contract PnL drawdown ADL ⋮---- export type WSADLAlertEventV5 = WSPublicTopicEventV5< 'adlAlert.USDT' | 'adlAlert.USDC' | 'adlAlert.inverse', 'snapshot', WSADLAlertV5[] >; ⋮---- export type WSSystemStatusEventV5 = WSPublicTopicEventV5< 'system.status', 'snapshot', SystemStatusItemV5[] >; ⋮---- /** * RFQ WebSocket Events */ ⋮---- /** * RFQ Inquiry Channel * Private push for RFQ inquiries sent or received by the user * Topics: rfq.open.rfqs, rfq.site.rfqs */ export type WSRFQInquiryEventV5 = WSPrivateTopicEventV5< 'rfq.open.rfqs' | 'rfq.site.rfqs', RFQItemV5[] >; ⋮---- /** * RFQ Quote Channel * Private push for quotes sent or received by the user * Topics: rfq.open.quotes, rfq.site.quotes */ export type WSRFQQuoteEventV5 = WSPrivateTopicEventV5< 'rfq.open.quotes' | 'rfq.site.quotes', RFQQuoteItemV5[] >; ⋮---- /** * RFQ Trade Channel * Private push for block trades executed by the user * Topics: rfq.open.trades, rfq.site.trades */ export type WSRFQTradeEventV5 = WSPrivateTopicEventV5< 'rfq.open.trades' | 'rfq.site.trades', RFQTradeV5[] >; ⋮---- /** * RFQ Public Trade Channel * Public push for all block trades * Topics: rfq.open.public.trades, rfq.site.public.trades */ export type WSRFQPublicTradeEventV5 = WSPublicTopicEventV5< 'rfq.open.public.trades' | 'rfq.site.public.trades', 'snapshot', RFQPublicTradeV5[] >; ================ File: src/websocket-client.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- import { CategoryV5, MessageEventLike, WsKey, WsMarket, WsTopic, } from './types'; import { Exact, WSAPIOperation, WsAPIOperationResponseMap, WSAPIRequest, WsAPITopicRequestParamMap, WsAPIWsKeyTopicMap, WsOperation, WsRequestOperationBybit, } from './types/websockets/ws-api'; import { APIID, getMaxTopicsPerSubscribeEvent, getNormalisedTopicRequests, getPromiseRefForWSAPIRequest, getTopicsPerWSKey, getWsKeyForTopic, getWsUrl, isPrivateWsTopic, isTopicSubscriptionConfirmation, isTopicSubscriptionSuccess, isWSAPIResponse, isWsPong, neverGuard, WS_AUTH_ON_CONNECT_KEYS, WS_KEY_MAP, WS_LOGGER_CATEGORY, WSConnectedResult, WsTopicRequest, } from './util'; import { BaseWebsocketClient, EmittableEvent, MidflightWsRequestEvent, } from './util/BaseWSClient'; import { SignAlgorithm, signMessage } from './util/webCryptoAPI'; ⋮---- export class WebsocketClient extends BaseWebsocketClient< ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting * for automatic connection by SDK. */ public connectAll(): Promise[] ⋮---- /** * Ensures the WS API connection is active and ready. * * You do not need to call this, but if you call this before making any WS API requests, * it can accelerate the first request (by preparing the connection in advance). */ public connectWSAPI(): Promise ⋮---- /** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- public connectPublic(): Promise[] ⋮---- public connectPrivate(): Promise ⋮---- /** * Subscribe to V5 topics & track/persist them. * @param wsTopics - topic or list of topics * @param category - the API category this topic is for (e.g. "linear"). * The value is only important when connecting to public topics and will be ignored for private topics. * @param isPrivateTopic - optional - the library will try to detect private topics, you can use this * to mark a topic as private (if the topic isn't recognised yet) */ public subscribeV5( wsTopics: WsTopic[] | WsTopic, category: CategoryV5, isPrivateTopic?: boolean, ): Promise[] ⋮---- // Sort into per-WsKey batches, in case there is a mix of topics here ⋮---- // Prevent duplicate requests to the same topic ⋮---- // Batch sub topics per ws key ⋮---- // Return promise to resolve midflight WS request (only works if already connected before request) ⋮---- /** * Unsubscribe from V5 topics & remove them from memory. They won't be re-subscribed to if the * connection reconnects. * * @param wsTopics - topic or list of topics * @param category - the API category this topic is for (e.g. "linear"). The value is only * important when connecting to public topics and will be ignored for private topics. * @param isPrivateTopic - optional - the library will try to detect private topics, you can * use this to mark a topic as private (if the topic isn't recognised yet) */ public unsubscribeV5( wsTopics: WsTopic[] | WsTopic, category: CategoryV5, isPrivateTopic?: boolean, ): Promise[] ⋮---- // Sort into per-WsKey batches, in case there is a mix of topics here ⋮---- // Batch sub topics per ws key ⋮---- // Return promise to resolve midflight WS request (only works if already connected before request) ⋮---- /** * Note: subscribeV5() might be simpler to use. The end result is the same. * * 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, category: CategoryV5}. * * - 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)[], requestedWsKey?: WsKey, ) ⋮---- // Batch sub topics per ws key ⋮---- /** * Note: unsubscribe() might be simpler to use. The end result is the same. * 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, ) ⋮---- // Batch sub topics per ws key ⋮---- /** * * * * WS API Methods - similar to the REST API, but via WebSockets * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline * * * */ ⋮---- /** * Send a Websocket API command/request on a connection. Returns a promise that resolves on reply. * * WS API Documentation for list of operations and parameters: * https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline * * 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). * * Authentication is automatic. If you didn't request authentication yourself, there might * be a small delay after your first request, while the SDK automatically authenticates. * * @param wsKey - The connection this event is for. Currently only "v5PrivateTrade" is supported * for Bybit, since that is the dedicated WS API connection. * @param operation - The command being sent, e.g. "order.create" to submit a new order. * @param params - Any request parameters for the command. E.g. `OrderParamsV5` to submit a new * order. Only send parameters for the request body. Everything else is automatically handled. * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response */ ⋮---- // This overload allows the caller to omit the 3rd param, if it isn't required sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap, TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], TWSParams extends Exact, >( wsKey: TWSKey, operation: TWSOperation, ...params: TWSParams extends undefined ? [] : [TWSParams] ): Promise; ⋮---- // These overloads give stricter types than mapped generics, since generic constraints // do not trigger excess property checks // Without these overloads, TypeScript won't complain if you include an // unexpected property with your request (if it doesn't clash with an existing property) sendWSAPIRequest( wsKey: typeof WS_KEY_MAP.v5PrivateTrade, operation: TWSOperation, params: WsAPITopicRequestParamMap[TWSOperation], ): Promise; ⋮---- sendWSAPIRequest( wsKey: typeof WS_KEY_MAP.v5PrivateTrade, operation: TWSOperation, params: WsAPITopicRequestParamMap[TWSOperation], ): Promise; ⋮---- sendWSAPIRequest( wsKey: typeof WS_KEY_MAP.v5PrivateTrade, operation: TWSOperation, params: WsAPITopicRequestParamMap[TWSOperation], ): Promise; ⋮---- async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap, TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], TWSParams extends Exact, TWSAPIResponse extends WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], >( wsKey: WsKey = WS_KEY_MAP.v5PrivateTrade, operation: TWSOperation, params: TWSParams, ): Promise ⋮---- // Sign, if needed ⋮---- // Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- // Enrich returned promise with request context for easier debugging ⋮---- // throw e; ⋮---- // Send event ⋮---- // Return deferred promise, so caller can await this call ⋮---- /** * * * Internal methods - not intended for public use * * */ ⋮---- /** * @returns The WS URL to connect to for this WS key */ protected async getWsUrl(wsKey: WsKey): Promise ⋮---- // If auth is needed for this wsKey URL, this returns a suffix ⋮---- /** * Return params required to make authorized request */ private async getWsAuthURLSuffix(): Promise ⋮---- private async signMessage( paramsStr: string, secret: string, method?: 'hex' | 'base64', algorithm: SignAlgorithm = 'SHA-256', ): Promise ⋮---- protected async getWsAuthRequestEvent( wsKey: WsKey, ): Promise> ⋮---- private async getWsAuthSignature( wsKey: WsKey, ): Promise< ⋮---- undefined, // Let the function automatically determine encoding based on key type ⋮---- private async signWSAPIRequest( requestEvent: WSAPIRequest, ): Promise> ⋮---- // Not needed for Bybit. Auth happens only on connection open, automatically. ⋮---- protected sendPingEvent(wsKey: WsKey) ⋮---- protected sendPongEvent(wsKey: WsKey) ⋮---- /** Force subscription requests to be sent in smaller batches, if a number is returned */ protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ protected async getWsRequestEvents( market: WsMarket, operation: WsOperation, requests: WsTopicRequest[], // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars wsKey: WsKey, ): Promise>[]> ⋮---- // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars ⋮---- // Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any protected isWsPing(msg: any): boolean ⋮---- // eslint-disable-next-line @typescript-eslint/no-explicit-any protected isWsPong(msg: any): boolean ⋮---- // public ws connections ⋮---- // private ws connections ⋮---- /** * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- // this.logger.trace('resolveEmittableEvents', { // ...WS_LOGGER_CATEGORY, // wsKey, // parsed: JSON.stringify(parsed), // }); ⋮---- // Only applies to the V5 WS topics ⋮---- // WS API response ⋮---- // eslint-disable-next-line max-len ⋮---- // WS API Exception ⋮---- // WS API Success ⋮---- // Messages for a subscribed topic all include the "topic" property ⋮---- // Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property ⋮---- // Failed request ⋮---- // These are r equest/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- // Request/reply pattern for authentication success ⋮---- // In case of catastrophic failure, fallback to noisy emit update ================ File: README.md ================ # Node.js & JavaScript SDK for Bybit REST API, WebSocket API & WebSocket Events [![Build & Test](https://github.com/tiagosiebler/bybit-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/bybit-api/actions/workflows/e2etest.yml) [![npm version](https://img.shields.io/npm/v/bybit-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/bybit-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/bybit-api)][1] [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bybit-api)][1] [![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api) [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)

SDK Logo

[1]: https://www.npmjs.com/package/bybit-api Professional Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs, WebSocket APIs & WebSocket Events: - Complete integration with all Bybit REST APIs & WebSockets, including the WebSocket API. - Actively maintained with a modern, promise-driven interface. - Exclusive benefits with this Node.js, JavaScript & TypeScript SDK for Bybit: - Higher API rate limits with this SDK than the highest VIP tier! - All qualified API requests made with this SDK are automatically subject to significantly higher rate limits. - Rate limits are raised to 400 requests per second, higher than the highest VIP tier. - No action required. This is automatic for any API calls made with this SDK, for any user. - Read more in the announcement: [here](https://github.com/tiagosiebler/bybit-api/issues/458). - Lower minimum order notional value with this SDK!\* - Place orders with a notional value as low as $1. - Lower than the default minimum notional order value $5. - \*Note: the lower min notional requirement is an undocumented benefit that may end at any time. - Automatic support for HMAC & RSA authentication. - TypeScript support (thorough type declarations for most API requests & responses, including WS API). - JavaScript support (TypeScript not required but definitely recommended). - Thorough & automatic end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm. - Proxy support via axios integration. - Robust WebSocket consumer integration with configurable heartbeats & automatic reconnect then resubscribe workflows. - Event driven messaging - Smart WebSocket persistence - Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - Automatically handle authentication. - Emit `reconnected` event when dropped connection is restored. - WebSocket API integration, with two design patterns to choose from: 1. Asynchronous **promise**-driven responses: - Make requests like a REST API, using the WebSocket API. No need to subscribe to asynchronous events. - Import the `WebsocketAPIClient` and use it like the REST API client. Call functions and await responses. - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts). - Prefer something more raw? Use the `sendWSAPIRequest(...)` method and await responses - See example for more details: [examples/ws-api-raw-promises.ts](./examples/ws-api-raw-promises.ts) 2. Asynchronous **event**-driven responses: - Subscribe to `response` and `error` events from WebsocketClient's event emitter. - Send commands with the `sendWSAPIRequest(...)` method. - Responses to commands will arrive via the `response` and `error` events emitted by the client. - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). # Table of Contents ## Overview - [Installation](#installation) - [Issues & Discussion](#issues--discussion) - [Related Projects](#related-projects) - [Documentation](#documentation) - [Examples](#examples) ## REST API Examples - [API Clients](#api-clients) - [REST API Usage](#rest-api-usage) ## WebSocket Integration & Examples - [WebSockets](#websockets) - [WebSocket Subscriptions - Consuming Events](#websocket-subscriptions---consuming-events) - [Websocket API - Sending Orders via WebSockets](#websocket-api---sending-orders-via-websockets) - [Consumer Load Balancing](#balancing-load-across-multiple-connections) ## Additional Features - [Logging](#logging) - [Customise Logging](#customise-logging) - [Debug HTTP Requests](#debug-http-requests) - [Browser Usage](#browser-usage) - [Import](#import) - [Webpack](#webpack) - [Use with LLMs & AI](#use-with-llms--ai) - [Used By](#used-by) ## Contributing - [Contributions & Thanks](#contributions--thanks) --- ## Installation `npm install --save bybit-api` ## Issues & Discussion - Issues? Check the [issues tab](https://github.com/tiagosiebler/bybit-api/issues). - Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. - Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) ## Related projects Check out my related JavaScript/TypeScript/Node.js projects: - Try my REST API & WebSocket SDKs: - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) ## Documentation Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within the github repository (see table below for convenient links to each class). TypeScript is definitely recommended, but not required. - [Bybit API Docs](https://bybit-exchange.github.io/docs/v5/intro) - [REST Endpoint Function List](./docs/endpointFunctionList.md) - [TSDoc Documentation (generated using typedoc via npm module)](https://tsdocs.dev/docs/bybit-api) ## Structure The SDK is written in TypeScript, but fully compatible with both TypeScript and pure JavaScript projects. A pure JavaScript version can be built using `npm run build`. The output of the `build` command is the version published to npm, packaged as a JavaScript module (with types available for you TypeScript users). - [src](./src) - the complete SDK written in TypeScript. - [lib](./lib) - the JavaScript version of the project (built from TypeScript) that is published to npm. This should not be edited directly, as it will be overwritten with each release. - [examples](./examples) - examples & demonstrations. Contributions are welcome! - [test](./test) - automated end-to-end tests that run before every release, making real API calls. --- ## Examples Examples for using each client can be found in: - the [examples](./examples) folder. - the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository. If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler). ## API Clients You should be using the V5 APIs. If you aren't, you should upgrade your project to use the V5 APIs as soon as possible. Bybit used to have several API groups (originally one per product), but the V5 API is currently the latest standard. Refer to the [V5 interface mapping page](https://bybit-exchange.github.io/docs/v5/intro#v5-and-v3-interface-mapping-list) for more information on which V5 endpoints can be used instead of previous V3 endpoints. To learn more about the V5 API, please read the [V5 upgrade guideline](https://bybit-exchange.github.io/docs/v5/upgrade-guide). Here are the available REST clients and the corresponding API groups described in the documentation: | Class | Description | | :-----------------------------------------------: | :------------------------------------------------------------------------------------------------------: | | [ **V5 API** ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). | | [RestClientV5](src/rest-client-v5.ts) | Unified V5 all-in-one REST client for all [V5 REST APIs](https://bybit-exchange.github.io/docs/v5/intro) | | [WebsocketClient](src/websocket-client.ts) | All WebSocket features (Public & Private consumers for all API categories & the WebSocket API) | | [WebsocketAPIClient](src/websocket-api-client.ts) | Use the WebSocket API like a REST API. Call functions and await responses, powered by WebSockets. | ## REST API Usage Create API credentials on Bybit's website: - [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) - [Testnet](https://testnet.bybit.com/app/user/api-management) The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the [examples](./examples/) folder in the repository on GitHub: ```typescript const { RestClientV5 } = require('bybit-api'); // or // import { RestClientV5 } from 'bybit-api'; const restClientOptions = { /** supports HMAC & RSA API keys - automatically detected */ /** Your API key */ key: 'apiKeyHere', /** Your API secret */ secret: 'apiSecretHere', /** Set to `true` to connect to testnet. Uses the live environment by default. */ // testnet: true, /** * Set to `true` to use Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Note: to use demo trading, you should have `testnet` disabled. * * You can find a detailed demoTrading example in the examples folder on GitHub. */ // demoTrading: true, /** Override the max size of the request window (in ms) */ // recv_window: 5000, // 5000 = 5 seconds /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ // keepAlive: true, /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over * sockets being kept alive. Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ // keepAliveMsecs: 1000, // 1000 = 1 second /** * Optionally override API domain used: * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', **/ // apiRegion: 'bytick', /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ // parseAPIRateLimits: true, /** * Allows you to provide a custom "signMessage" function, * e.g. to use node crypto's much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new RestClientV5( { key: API_KEY, secret: API_SECRET, // demoTrading: true, // Optional: enable to try parsing rate limit values from responses // parseAPIRateLimits: true }, // requestLibraryOptions ); // For public-only API calls, simply don't provide a key & secret or set them to undefined // const client = new RestClientV5(); client .getAccountInfo() .then((result) => { console.log('getAccountInfo result: ', result); }) .catch((err) => { console.error('getAccountInfo error: ', err); }); client .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) .then((result) => { console.log('getOrderBook result: ', result); }) .catch((err) => { console.error('getOrderBook error: ', err); }); ``` --- ## WebSockets The WebsocketClient will automatically use the latest V5 WebSocket endpoints by default. To use a different endpoint, use the `market` parameter. Except for the WebSocket API - this can be accessed without any special configuration. ## WebSocket Subscriptions - Consuming events Here's a minimal example for using the websocket client. For more complete examples, look into the ws-\* examples in the [examples](./examples/) folder in the repo on GitHub. ```javascript const { WebsocketClient } = require('bybit-api'); // or // import { WebsocketClient } from 'bybit-api'; const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const wsConfig = { /** * API credentials are optional. They are only required if you plan on using * any account-specific topics or the WS API * supports HMAC & RSA API keys - automatically detected */ key: 'yourAPIKeyHere', secret: 'yourAPISecretHere', /* The following parameters are optional: */ /** * Set to `true` to connect to Bybit's testnet environment. * - If demo trading, `testnet` should be set to false! * - If testing a strategy, use demo trading instead. Testnet market * data is very different from real market conditions. */ // testnet: true /** * Set to `true` to connect to Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Refer to the examples folder on GitHub for a more detailed demonstration. */ // demoTrading: true, // recv window size for websocket authentication (higher latency connections // (VPN) can cause authentication to fail if the recv window is too small) // recvWindow: 5000, /** How often to check if the connection is alive (in ms) */ // pingInterval: 10000, /** * How long to wait (in ms) for a pong (heartbeat reply) before assuming the * connection is dead */ // pongTimeout: 1000, /** Delay in milliseconds before respawning the connection */ // reconnectTimeout: 500, // override which URL to use for websocket connections // wsUrl: 'wss://stream.bytick.com/realtime' /** * Allows you to provide a custom "signMessage" function, e.g. to use node's * much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const ws = new WebsocketClient(wsConfig); // (v5) subscribe to multiple topics at once ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); // Or one at a time ws.subscribeV5('kline.5.BTCUSDT', 'linear'); ws.subscribeV5('kline.5.ETHUSDT', 'linear'); // Private/public topics can be used in the same WS client instance, even for // different API groups (linear, options, spot, etc) ws.subscribeV5('position', 'linear'); ws.subscribeV5('publicTrade.BTC', 'option'); /** * The Websocket Client will automatically manage all connectivity & authentication for you. * * If a network issue occurs, it will automatically: * - detect it, * - remove the dead connection, * - replace it with a new one, * - resubscribe to everything you were subscribed to. * * When this happens, you will see the "reconnected" event. */ // Listen to events coming from websockets. This is the primary data source ws.on('update', (data) => { console.log('data received', JSON.stringify(data, null, 2)); }); // Optional: Listen to websocket connection open event // (automatic after subscribing to one or more topics) ws.on('open', ({ wsKey, event }) => { console.log('connection open for websocket with ID: ', wsKey); }); // Optional: Listen to responses to websocket queries // (e.g. the response after subscribing to a topic) ws.on('response', (response) => { console.log('response', response); }); // Optional: Listen to connection close event. // Unexpected connection closes are automatically reconnected. ws.on('close', () => { console.log('connection closed'); }); // Listen to raw error events. Recommended. ws.on('exception', (err) => { console.error('exception', err); }); ws.on('reconnect', ({ wsKey }) => { console.log('ws automatically reconnecting.... ', wsKey); }); ws.on('reconnected', (data) => { console.log('ws has reconnected ', data?.wsKey); }); ``` ## Websocket API - Sending orders via WebSockets Bybit supports sending, amending and cancelling orders over a WebSocket connection. The [WebsocketClient](./src/WebsocketClient.ts) fully supports Bybit's WebSocket API via the `sendWSAPIRequest(...)` method. There is also a dedicated [WebsocketAPIClient](./src/websocket-api-client.ts), built over the WSClient's sendWSAPIRequest mechanism for a simpler experience. Links for reference: - [Bybit WebSocket API Documentation](https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline) - [WebsocketAPIClient example, use the Websocket API like a REST API](./examples/ws-api-client.ts) - [Raw Asynchronous Websocket API Node.js/TypeScript/JavaScript example](./examples/ws-api-raw-promises.ts) Note: as of January 2025, the demo trading environment does not support the WebSocket API. There are two ways to use the WS API, depending on individual preference: 1. event-driven: - send requests via `client.sendWSAPIRequest(wsKey, operation, params)`, fire and forget - handle async replies via event handlers on `client.on('exception', cb)` and `client.on('response', cb)` - See example for more details: [examples/ws-api-raw-events.ts](./examples/ws-api-raw-events.ts) 2. promise-driven: - import the `WebsocketAPIClient` and use it much like a REST API. - make an instance & call the Websocket API with a function. - await responses, much like a REST API. - use try/catch blocks to handle promise rejections - See example for more details: [examples/ws-api-client.ts](./examples/ws-api-client.ts) The below example demonstrates the promise-driven approach, which behaves similar to a REST API. The WebSocket API even accepts the same parameters as the corresponding REST API endpoints, so this approach should be compatible with existing REST implementations. Connectivity, authentication and connecting requests & responses to promises - these are all handled automatically without additional configuration by the WebsocketClient. The WebsocketAPIClient is a wrapper built on top of this, providing dedicated methods for every available Websocket API command. Each method has fully typed requests & responses. Benefit from the capabilities of the WebSocket API without the complexity of managing asynchronous messaging over WebSockets. ```javascript const { WS_KEY_MAP, WebsocketAPIClient } = require('bybit-api'); // or // import { WS_KEY_MAP, WebsocketAPIClient } from 'bybit-api'; // Create an instance of the WebsocketAPIClient. This is built on // top of the WebsocketClient and will automatically handle WebSocket // persistence and authentication for you. // supports HMAC & RSA API keys - automatically detected const wsClient = new WebsocketAPIClient({ key: 'yourApiKeyHere', secret: 'yourApiSecretHere', // Whether to use the testnet environment. // Create testnet API keys here: https://testnet.bybit.com/app/user/api-management // testnet: true, // Whether to use the livenet demo trading environment // Note: As of Jan 2025, demo trading only supports consuming events, it does // NOT support the WS API. // demoTrading: false, // If you want your own event handlers instead of the default ones with logs, // disable this setting and see ws-api-client example for more details. // attachEventListeners: false }); // This example is wrapped in an async function, so "await" can be used async function main() { /** * Optional. Can be used to prepare a connection before sending * commands (e.g. as part of your startup process). * * This is not necessary and will happen automatically when * sending a command, if you aren't connected/authenticated yet. */ // await wsClient.getWSClient().connectWSAPI(); try { console.log('Step 1: Create an order'); const response = await wsClient.submitNewOrder({ category: 'linear', symbol: 'BTCUSDT', orderType: 'Limit', qty: '0.001', side: 'Buy', price: '50000', }); console.log('submitNewOrder response: ', response); } catch (e) { console.log('submitNewOrder error: ', e); } try { console.log('Step 2: Amend an order'); const response = await wsClient.amendOrder({ category: 'linear', symbol: 'BTCUSDT', orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', qty: '0.001', price: '60000', }); console.log('amendOrder response: ', response); } catch (e) { console.log('amendOrder error: ', e); } try { console.log('Step 3: Cancel an order'); const response = await wsClient.cancelOrder({ category: 'linear', symbol: 'BTCUSDT', orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', }); console.log('cancelOrder response: ', response); } catch (e) { console.log('cancelOrder error: ', e); } } // Start executing the example workflow main(); ``` --- ### Balancing load across multiple connections The WebsocketClient will automatically prepare one connection per API group, for all topics in that API group. Any topics that you subscribe to on that WebSocket client will automatically be added to the same connection. To spread your subscribed topics over multiple connections, e.g. to reduce the throughput of an individual connectionk, you can make one instance of the WebsocketClient per connection group. ```typescript const wsClientGroup1 = new WebsocketClient(); const wsClientGroup2 = new WebsocketClient(); // Attach event listeners to each WS Client // Divide your desired topics into separate groups ``` Important: do not subscribe to the same topics on both clients or you will receive duplicate messages (once per WS client). --- ## Logging ### Customise logging Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired, as in the example below: ```javascript const { WebsocketClient, DefaultLogger } = require('bybit-api'); // Enable all logging on the trace level (disabled by default) const customLogger = { ...DefaultLogger, trace: (...params) => console.log('trace', ...params), }; const wsClient = new WebsocketClient( { key: 'xxx', secret: 'yyy' }, customLogger, ); ``` ### Debug HTTP requests In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the `BYBITTRACE` env var to `true`. ## Browser Usage ### Import This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. 1. Install these dependencies ```sh npm install stream-browserify ``` 2. Add this to your `tsconfig.json` ```json { "compilerOptions": { "paths": { "stream": [ "./node_modules/stream-browserify" ] } ``` 3. Declare this in the global context of your application (ex: in polyfills for angular) ```js (window as any).global = window; ``` ### Webpack This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. Build a bundle using webpack: - `npm install` - `npm build` - `npm pack` The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO - contributions welcome. ## Use with LLMs & AI This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. --- ## Used By [![Repository Users Preview Image](https://dependents.info/tiagosiebler/bybit-api/image)](https://github.com/tiagosiebler/bybit-api/network/dependents) --- ### Contributions & Thanks Have my projects helped you? Share the love, there are many ways you can show your thanks: - Star & share my projects. - Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler - Have an interesting project? Get in touch & invite me to it. - Or buy me all the coffee: - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` ### Contributions & Pull Requests Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) ================ File: src/types/request/v5-crypto-loan.ts ================ export interface BorrowCryptoLoanParamsV5 { loanCurrency: string; loanAmount?: string; loanTerm?: string; collateralCurrency: string; collateralAmount?: string; } ⋮---- export interface GetUnpaidLoanOrdersParamsV5 { orderId?: string; loanCurrency?: string; collateralCurrency?: string; loanTermType?: string; loanTerm?: string; limit?: string; cursor?: string; } ⋮---- export interface GetRepaymentHistoryParamsV5 { orderId?: string; repayId?: string; loanCurrency?: string; limit?: string; cursor?: string; } ⋮---- export interface GetCompletedLoanOrderHistoryParamsV5 { orderId?: string; loanCurrency?: string; collateralCurrency?: string; limit?: string; cursor?: string; } ⋮---- export interface GetLoanLTVAdjustmentHistoryParamsV5 { orderId?: string; adjustId?: string; collateralCurrency?: string; limit?: string; cursor?: string; } ⋮---- // New Crypto Loan Request Types ⋮---- export interface GetBorrowableCoinsParamsV5 { vipLevel?: string; currency?: string; } ⋮---- export interface GetCollateralCoinsParamsV5 { currency?: string; } ⋮---- export interface GetMaxCollateralAmountParamsV5 { currency: string; } ⋮---- export interface AdjustCollateralAmountParamsV5 { currency: string; amount: string; direction: '0' | '1'; } ⋮---- export interface GetCollateralAdjustmentHistoryParamsV5 { adjustId?: string; collateralCurrency?: string; limit?: string; cursor?: string; } ⋮---- // Flexible Loan Request Types ⋮---- export interface BorrowFlexibleParamsV5 { loanCurrency: string; loanAmount: string; collateralList?: { currency: string; amount: string; }[]; } ⋮---- export interface RepayFlexibleParamsV5 { loanCurrency: string; amount: string; } ⋮---- export interface RepayCollateralFlexibleParamsV5 { loanCurrency: string; collateralCoin: string; amount: string; } ⋮---- export interface GetOngoingFlexibleLoansParamsV5 { loanCurrency?: string; } ⋮---- export interface GetBorrowHistoryFlexibleParamsV5 { orderId?: string; loanCurrency?: string; limit?: string; cursor?: string; } ⋮---- export interface GetRepaymentHistoryFlexibleParamsV5 { repayId?: string; loanCurrency?: string; limit?: string; cursor?: string; } ⋮---- // Fixed Loan Request Types ⋮---- export interface GetSupplyOrderQuoteFixedParamsV5 { orderCurrency: string; term?: string; orderBy: 'apy' | 'term' | 'quantity'; sort?: number; limit?: number; } ⋮---- export interface GetBorrowOrderQuoteFixedParamsV5 { orderCurrency: string; term?: string; orderBy: 'apy' | 'term' | 'quantity'; sort?: number; limit?: number; } ⋮---- export interface CreateBorrowOrderFixedParamsV5 { orderCurrency: string; orderAmount: string; annualRate: string; term: string; autoRepay?: string; // Deprecated repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan collateralList?: { currency: string; amount: string; }[]; } ⋮---- autoRepay?: string; // Deprecated repayType?: string; // 1: Auto Repayment (default); 2: Transfer to flexible loan ⋮---- export interface CreateSupplyOrderFixedParamsV5 { orderCurrency: string; orderAmount: string; annualRate: string; term: string; } ⋮---- export interface CancelBorrowOrderFixedParamsV5 { orderId: string; } ⋮---- export interface CancelSupplyOrderFixedParamsV5 { orderId: string; } ⋮---- export interface GetBorrowContractInfoFixedParamsV5 { orderId?: string; loanId?: string; orderCurrency?: string; term?: string; limit?: string; cursor?: string; } ⋮---- export interface GetSupplyContractInfoFixedParamsV5 { orderId?: string; supplyId?: string; supplyCurrency?: string; term?: string; limit?: string; cursor?: string; } ⋮---- export interface GetBorrowOrderInfoFixedParamsV5 { orderId?: string; orderCurrency?: string; state?: string; term?: string; limit?: string; cursor?: string; } ⋮---- export interface GetSupplyOrderInfoFixedParamsV5 { orderId?: string; orderCurrency?: string; state?: string; term?: string; limit?: string; cursor?: string; } ⋮---- export interface RepayFixedParamsV5 { loanId?: string; loanCurrency?: string; } ⋮---- export interface RepayCollateralFixedParamsV5 { loanCurrency: string; collateralCoin: string; amount: string; } ⋮---- export interface GetRepaymentHistoryFixedParamsV5 { repayId?: string; loanCurrency?: string; limit?: string; cursor?: string; } ⋮---- export interface RenewBorrowOrderFixedParamsV5 { loanId: string; collateralList?: { currency?: string; amount?: string; }[]; } ⋮---- export interface GetRenewOrderInfoFixedParamsV5 { orderId?: string; orderCurrency?: string; limit?: string; cursor?: string; } ================ File: src/types/response/v5-crypto-loan.ts ================ export interface CollateralCoinV5 { collateralAccuracy: number; initialLTV: string; liquidationLTV: string; marginCallLTV: string; maxLimit: string; } ⋮---- export interface VipCollateralCoinsV5 { list: CollateralCoinV5[]; vipLevel: string; } ⋮---- export interface BorrowableCoinV5 { borrowingAccuracy: number; currency: string; flexibleHourlyInterestRate: string; hourlyInterestRate7D: string; hourlyInterestRate14D: string; hourlyInterestRate30D: string; hourlyInterestRate90D: string; hourlyInterestRate180D: string; maxBorrowingAmount: string; minBorrowingAmount: string; } ⋮---- export interface VipBorrowableCoinsV5 { list: BorrowableCoinV5[]; vipLevel: string; } ⋮---- export interface AccountBorrowCollateralLimitV5 { collateralCurrency: string; loanCurrency: string; maxCollateralAmount: string; maxLoanAmount: string; minCollateralAmount: string; minLoanAmount: string; } ⋮---- export interface UnpaidLoanOrderV5 { collateralAmount: string; collateralCurrency: string; currentLTV: string; expirationTime: string; hourlyInterestRate: string; loanCurrency: string; loanTerm: string; orderId: string; residualInterest: string; residualPenaltyInterest: string; totalDebt: string; } ⋮---- export interface RepaymentHistoryV5 { collateralCurrency: string; collateralReturn: string; loanCurrency: string; loanTerm: string; orderId: string; repayAmount: string; repayId: string; repayStatus: number; repayTime: string; repayType: string; } ⋮---- export interface CompletedLoanOrderV5 { borrowTime: string; collateralCurrency: string; expirationTime: string; hourlyInterestRate: string; initialCollateralAmount: string; initialLoanAmount: string; loanCurrency: string; loanTerm: string; orderId: string; repaidInterest: string; repaidPenaltyInterest: string; status: number; } export interface LoanLTVAdjustmentHistoryV5 { collateralCurrency: string; orderId: string; adjustId: string; adjustTime: string; preLTV: string; afterLTV: string; direction: number; amount: string; } ⋮---- // New Crypto Loan Types ⋮---- export interface BorrowCoinV5 { currency: string; fixedBorrowable: boolean; fixedBorrowingAccuracy: number; flexibleBorrowable: boolean; flexibleBorrowingAccuracy: number; maxBorrowingAmount: string; minFixedBorrowingAmount: string; minFlexibleBorrowingAmount: string; vipLevel: string; flexibleAnnualizedInterestRate: string; annualizedInterestRate7D: string; annualizedInterestRate14D: string; annualizedInterestRate30D: string; annualizedInterestRate60D: string; annualizedInterestRate90D: string; annualizedInterestRate180D: string; } ⋮---- export interface CollateralRatioV5 { collateralRatio: string; maxValue: string; minValue: string; } ⋮---- export interface CollateralRatioConfigV5 { collateralRatioList: CollateralRatioV5[]; currencies: string; } ⋮---- export interface CurrencyLiquidationV5 { currency: string; liquidationOrder: number; } ⋮---- export interface CollateralDataV5 { collateralRatioConfigList: CollateralRatioConfigV5[]; currencyLiquidationList: CurrencyLiquidationV5[]; } ⋮---- // Additional New Crypto Loan Types ⋮---- export interface AdjustCollateralAmountV5 { adjustId: number; } ⋮---- export interface CollateralAdjustmentHistoryV5 { adjustId: number; adjustTime: number; afterLTV: string; amount: string; collateralCurrency: string; direction: number; preLTV: string; status: number; } ⋮---- export interface BorrowListV5 { fixedTotalDebt: string; fixedTotalDebtUSD: string; flexibleHourlyInterestRate: string; flexibleTotalDebt: string; flexibleTotalDebtUSD: string; loanCurrency: string; } ⋮---- export interface CollateralListV5 { amount: string; amountUSD: string; currency: string; ltv: string; } ⋮---- export interface SupplyListV5 { amount: string; amountUSD: string; currency: string; } ⋮---- export interface CryptoLoanPositionV5 { borrowList: BorrowListV5[]; collateralList: CollateralListV5[]; supplyList: SupplyListV5[]; totalCollateral: string; totalDebt: string; totalSupply: string; } ⋮---- // Flexible Loan Types ⋮---- export interface BorrowFlexibleV5 { orderId: string; } ⋮---- export interface RepayFlexibleV5 { repayId: string; } ⋮---- export interface OngoingFlexibleLoanV5 { hourlyInterestRate: string; loanCurrency: string; totalDebt: string; unpaidAmount: string; unpaidInterest: string; } ⋮---- export interface BorrowHistoryFlexibleV5 { borrowTime: number; initialLoanAmount: string; loanCurrency: string; orderId: string; status: number; } ⋮---- export interface RepaymentHistoryFlexibleV5 { loanCurrency: string; repayAmount: string; repayId: string; repayStatus: number; repayTime: number; repayType: number; } ⋮---- // Fixed Loan Types ⋮---- export interface SupplyOrderQuoteFixedV5 { orderCurrency: string; term: number; annualRate: string; qty: string; } ⋮---- export interface BorrowOrderQuoteFixedV5 { orderCurrency: string; term: number; annualRate: string; qty: string; } ⋮---- export interface CreateBorrowOrderFixedV5 { orderId: string; } ⋮---- export interface CreateSupplyOrderFixedV5 { orderId: string; } ⋮---- export interface BorrowContractInfoFixedV5 { annualRate: string; autoRepay: string; // Deprecated borrowCurrency: string; borrowTime: string; interestPaid: string; loanId: string; orderId: string; repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment repaymentTime: string; residualPenaltyInterest: string; residualPrincipal: string; status: number; term: string; } ⋮---- autoRepay: string; // Deprecated ⋮---- repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment ⋮---- export interface SupplyContractInfoFixedV5 { annualRate: string; supplyCurrency: string; supplyTime: string; supplyAmount: string; interestPaid: string; supplyId: string; orderId: string; redemptionTime: string; penaltyInterest: string; actualRedemptionTime: string; status: number; term: string; } ⋮---- export interface BorrowOrderInfoFixedV5 { annualRate: string; orderId: number; orderTime: string; filledQty: string; orderQty: string; orderCurrency: string; state: number; term: number; repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment } ⋮---- repayType: string; // 1: Auto Repayment; 2: Transfer to flexible loan; 0: No Automatic Repayment ⋮---- export interface SupplyOrderInfoFixedV5 { annualRate: string; orderId: number; orderTime: string; filledQty: string; orderQty: string; orderCurrency: string; state: number; term: number; } ⋮---- export interface RepayFixedV5 { repayId: string; } ⋮---- export interface RepaymentHistoryFixedV5 { details: { loanCurrency: string; loanId: string; repayAmount: string; }[]; loanCurrency: string; repayAmount: string; repayId: string; repayStatus: number; repayTime: number; repayType: number; } ⋮---- export interface RenewBorrowOrderFixedV5 { orderId: string; } ⋮---- export interface RenewOrderInfoFixedV5 { amount: string; autoRepay: number; borrowCurrency: string; contractNo: string; dueTime: string; loanId: string; orderId: number; renewLoanNo: string; time: string; } ================ File: package.json ================ { "name": "bybit-api", "version": "4.4.3", "description": "Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", "files": [ "lib/*", "index.js", "llms.txt" ], "scripts": { "test": "jest", "test:watch": "jest --watch", "clean": "rimraf lib dist", "build": "tsc --project tsconfig.build.json", "build:clean": "npm run clean && npm run build", "build:watch": "npm run clean && tsc --project tsconfig.build.json --watch", "pack": "webpack --config webpack/webpack.config.js", "prepublish": "npm run build:clean", "betapublish": "npm publish --tag beta", "lint": "eslint src" }, "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [], "dependencies": { "axios": "^1.10.0", "isomorphic-ws": "^4.0.1", "ws": "^7.4.0" }, "devDependencies": { "@types/jest": "^29.5.11", "@types/node": "^22.10.7", "@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" }, "optionalDependencies": { "source-map-loader": "^2.0.0", "ts-loader": "^8.0.11", "webpack": "^5.4.0", "webpack-bundle-analyzer": "^4.1.0", "webpack-cli": "^4.2.0" }, "keywords": [ "bybit", "bybit api", "api", "websocket", "rest", "rest api", "inverse", "linear", "usdt", "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/bybit-api" }, "bugs": { "url": "https://github.com/tiagosiebler/bybit-api/issues" }, "homepage": "https://github.com/tiagosiebler/bybit-api#readme" } ================ File: src/rest-client-v5.ts ================ /* eslint-disable max-len */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { AccountBorrowCollateralLimitV5, AccountCoinBalanceV5, AccountInfoV5, AccountInstrumentInfoResponseV5, AccountMarginModeV5, AccountOrderV5, AccountTypeV5, AddOrReduceMarginParamsV5, AddOrReduceMarginResultV5, AdjustCollateralAmountParamsV5, AdjustCollateralAmountV5, ADLAlertResponseV5, AffiliateUserInfoV5, AffiliateUserListItemV5, AllCoinsBalanceV5, AllowedDepositCoinInfoV5, AmendOrderParamsV5, AmendSpreadOrderParamsV5, ApiKeyInfoV5, APIResponseV3, APIResponseV3WithTime, AssetInfoV5, AvailableAmountToRepayV5, BatchAmendOrderParamsV5, BatchAmendOrderResultV5, BatchCancelOrderParamsV5, BatchCancelOrderResultV5, BatchCreateOrderResultV5, BatchOrderParamsV5, BatchOrdersRetExtInfoV5, BorrowableCoinV5, BorrowContractInfoFixedV5, BorrowCryptoLoanParamsV5, BorrowFlexibleParamsV5, BorrowFlexibleV5, BorrowHistoryFlexibleV5, BorrowHistoryRecordV5, BorrowOrderInfoFixedV5, BorrowOrderQuoteFixedV5, BrokerIssuedVoucherV5, BrokerVoucherSpecV5, CancelAllOrdersParamsV5, CancelAllRFQResultV5, CancelBorrowOrderFixedParamsV5, CancelOrderParamsV5, CancelRFQParamsV5, CancelRFQQuoteItemV5, CancelRFQQuoteParamsV5, CancelRFQQuoteResultV5, CancelRFQResultV5, CancelSupplyOrderFixedParamsV5, CategoryCursorListV5, CategoryListV5, CategorySymbolListV5, CategoryV5, ClosedOptionsPositionV5, ClosedPnLV5, CoinExchangeRecordV5, CoinGreeksV5, CoinInfoV5, CoinStateV5, CollateralAdjustmentHistoryV5, CollateralDataV5, CollateralInfoV5, CompletedLoanOrderV5, ConfirmNewRiskLimitParamsV5, ConvertCoinsParamsV5, ConvertCoinSpecV5, ConvertHistoryRecordV5, ConvertQuoteV5, ConvertStatusV5, CreateBorrowOrderFixedParamsV5, CreateBorrowOrderFixedV5, CreateP2PAdParamsV5, CreateRFQParamsV5, CreateRFQQuoteParamsV5, CreateRFQQuoteResultV5, CreateRFQResultV5, CreateSubApiKeyParamsV5, CreateSubApiKeyResultV5, CreateSubMemberParamsV5, CreateSubMemberResultV5, CreateSupplyOrderFixedParamsV5, CreateSupplyOrderFixedV5, CryptoLoanPositionV5, CurrencyPositionTiersV5, CursorListV5, CursorRowsV5, DCPInfoV5, DeleteSubMemberParamsV5, DeliveryPriceV5, DeliveryRecordV5, DepositAddressChainV5, DepositRecordV5, EarnHourlyYieldHistoryV5, EarnOrderHistoryV5, EarnPositionV5, EarnProductV5, EarnYieldHistoryV5, ExchangeBrokerAccountInfoV5, ExchangeBrokerEarningResultV5, ExchangeBrokerSubAccountDepositRecordV5, ExecuteRFQQuoteParamsV5, ExecuteRFQQuoteResultV5, ExecutionV5, FeeGroupStructureResponseV5, FeeRateV5, FundingRateHistoryResponseV5, GetAccountCoinBalanceParamsV5, GetAccountHistoricOrdersParamsV5, GetAccountInstrumentsInfoParamsV5, GetAccountOrdersParamsV5, GetADLAlertParamsV5, GetAffiliateUserListParamsV5, GetAllCoinsBalanceParamsV5, GetAllowedDepositCoinInfoParamsV5, GetAssetInfoParamsV5, GetAvailableAmountToRepayParamsV5, GetBorrowableCoinsParamsV5, GetBorrowContractInfoFixedParamsV5, GetBorrowHistoryFlexibleParamsV5, GetBorrowHistoryParamsV5, GetBorrowOrderInfoFixedParamsV5, GetBorrowOrderQuoteFixedParamsV5, GetBrokerIssuedVoucherParamsV5, GetBrokerSubAccountDepositsV5, GetClassicTransactionLogsParamsV5, GetClosedOptionsPositionsParamsV5, GetClosedPnLParamsV5, GetCoinExchangeRecordParamsV5, GetCoinStateParamsV5, GetCollateralAdjustmentHistoryParamsV5, GetCollateralCoinsParamsV5, GetCompletedLoanOrderHistoryParamsV5, GetConvertHistoryParamsV5, GetDeliveryPriceParamsV5, GetDeliveryRecordParamsV5, GetDepositRecordParamsV5, GetEarnHourlyYieldHistoryParamsV5, GetEarnOrderHistoryParamsV5, GetEarnPositionParamsV5, GetEarnYieldHistoryParamsV5, GetExchangeBrokerEarningsParamsV5, GetExecutionListParamsV5, GetFeeGroupStructureParamsV5, GetFeeRateParamsV5, GetFundingRateHistoryParamsV5, GetHistoricalVolatilityParamsV5, GetIndexPriceComponentsParamsV5, GetIndexPriceKlineParamsV5, GetInstrumentsInfoParamsV5, GetInsuranceParamsV5, GetInternalDepositRecordParamsV5, GetInternalTransferParamsV5, GetKlineParamsV5, GetLoanLTVAdjustmentHistoryParamsV5, GetLongShortRatioParamsV5, GetMarkPriceKlineParamsV5, GetMaxBorrowableAmountParamsV5, GetMaxCollateralAmountParamsV5, GetMovePositionHistoryParamsV5, GetOngoingFlexibleLoansParamsV5, GetOpenInterestParamsV5, GetOptionDeliveryPriceParamsV5, GetOrderbookParamsV5, GetP2PAccountCoinsBalanceParamsV5, GetP2PCounterpartyUserInfoParamsV5, GetP2POnlineAdsParamsV5, GetP2POrderMessagesParamsV5, GetP2POrdersParamsV5, GetP2PPendingOrdersParamsV5, GetP2PPersonalAdsParamsV5, GetPositionTiersParamsV5, GetPremiumIndexPriceKlineParamsV5, GetPreUpgradeClosedPnlParamsV5, GetPreUpgradeOptionDeliveryRecordParamsV5, GetPreUpgradeOrderHistoryParamsV5, GetPreUpgradeTradeHistoryParamsV5, GetPreUpgradeTransactionLogParamsV5, GetPreUpgradeUSDCSessionParamsV5, GetPublicTradingHistoryParamsV5, GetRenewOrderInfoFixedParamsV5, GetRepaymentHistoryFixedParamsV5, GetRepaymentHistoryFlexibleParamsV5, GetRepaymentHistoryParamsV5, GetRFQHistoryParamsV5, GetRFQListParamsV5, GetRFQPublicTradesParamsV5, GetRFQQuoteRealtimeParamsV5, GetRFQRealtimeParamsV5, GetRFQRealtimeResultV5, GetRFQTradeListParamsV5, GetRiskLimitParamsV5, GetRPIOrderbookParamsV5, GetSettlementRecordParamsV5, GetSpreadInstrumentsInfoParamsV5, GetSpreadOpenOrdersParamsV5, GetSpreadOrderHistoryParamsV5, GetSpreadTradeHistoryParamsV5, GetSubAccountAllApiKeysParamsV5, GetSubAccountDepositRecordParamsV5, GetSupplyContractInfoFixedParamsV5, GetSupplyOrderInfoFixedParamsV5, GetSupplyOrderQuoteFixedParamsV5, GetSystemStatusParamsV5, GetTickersParamsV5, GetTransactionLogParamsV5, GetUniversalTransferRecordsParamsV5, GetUnpaidLoanOrdersParamsV5, GetVIPMarginDataParamsV5, GetWalletBalanceParamsV5, GetWithdrawalAddressListParamsV5, GetWithdrawalRecordsParamsV5, HistoricalVolatilityV5, IndexPriceComponentsResponseV5, InstrumentInfoResponseV5, InsuranceResponseV5, InternalDepositRecordV5, InternalTransferRecordV5, IssueVoucherParamsV5, LoanLTVAdjustmentHistoryV5, LongShortRatioV5, ManualBorrowParamsV5, ManualBorrowResultV5, ManualRepayParamsV5, ManualRepayResultV5, ManualRepayWithoutConversionParamsV5, ManualRepayWithoutConversionResultV5, MarkP2POrderAsPaidParamsV5, MaxBorrowableAmountV5, MMPModifyParamsV5, MMPStateV5, MovePositionHistoryV5, MovePositionParamsV5, MovePositionResultV5, OHLCKlineV5, OHLCVKlineV5, OngoingFlexibleLoanV5, OpenInterestResponseV5, OptionDeliveryPriceV5, OrderbookResponseV5, OrderParamsV5, OrderPriceLimitV5, OrderResultV5, OrderSideV5, P2PAccountCoinsBalanceV5, P2PAdDetailV5, P2PCounterpartyUserInfoV5, P2PCreateAdResponseV5, P2POnlineAdsResponseV5, P2POrderDetailV5, P2POrderMessageV5, P2POrdersResponseV5, P2PPersonalAdsResponseV5, P2PUserInfoV5, P2PUserPaymentV5, PositionInfoParamsV5, PositionV5, PreCheckOrderResultV5, PreUpgradeOptionsDelivery, PreUpgradeTransaction, PreUpgradeUSDCSessionSettlement, PublicTradeV5, RenewBorrowOrderFixedParamsV5, RenewBorrowOrderFixedV5, RenewOrderInfoFixedV5, RepayCollateralFixedParamsV5, RepayCollateralFlexibleParamsV5, RepayFixedParamsV5, RepayFixedV5, RepayFlexibleParamsV5, RepayFlexibleV5, RepayLiabilityParamsV5, RepayLiabilityResultV5, RepaymentHistoryFixedV5, RepaymentHistoryFlexibleV5, RepaymentHistoryV5, RequestConvertQuoteParamsV5, RFQConfigV5, RFQHistory, RFQPublicTradeV5, RFQQuoteItemV5, RFQTradeV5, RiskLimitV5, RPIOrderbookResponseV5, SendP2POrderMessageParamsV5, SetAutoAddMarginParamsV5, SetCollateralCoinParamsV5, SetLeverageParamsV5, SetLimitPriceActionParamsV5, SetRiskLimitParamsV5, SetRiskLimitResultV5, SetSpotMarginLeverageParamsV5, SettlementRecordV5, SetTPSLModeParamsV5, SetTradingStopParamsV5, SpotBorrowCheckResultV5, SpotMarginStateV5, SpreadInstrumentInfoV5, SpreadOpenOrderV5, SpreadOrderbookResponseV5, SpreadOrderHistoryV5, SpreadRecentTradeV5, SpreadTickerV5, SpreadTradeV5, SubMemberV5, SubmitSpreadOrderParamsV5, SubmitStakeRedeemParamsV5, SupplyContractInfoFixedV5, SupplyOrderInfoFixedV5, SupplyOrderQuoteFixedV5, SwitchIsolatedMarginParamsV5, SwitchPositionModeParamsV5, SystemStatusItemV5, TickerLinearInverseV5, TickerOptionV5, TickerSpotV5, TPSLModeV5, TransactionLogV5, UnifiedAccountUpgradeResultV5, UniversalTransferParamsV5, UniversalTransferRecordV5, UnpaidLoanOrderV5, UpdateApiKeyParamsV5, UpdateApiKeyResultV5, UpdateP2PAdParamsV5, VaspEntityV5, VipBorrowableCoinsV5, VipCollateralCoinsV5, VIPMarginDataV5, WalletBalanceV5, WithdrawableAmountV5, WithdrawalAddressV5, WithdrawalRecordV5, WithdrawParamsV5, } from './types'; import { REST_CLIENT_TYPE_ENUM } from './util'; import BaseRestClient from './util/BaseRestClient'; ⋮---- /** * REST API client for V5 REST APIs * * https://bybit-exchange.github.io/docs/v5/intro */ export class RestClientV5 extends BaseRestClient ⋮---- /** * ****** Custom SDK APIs * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- /** * ****** Misc Bybit APIs * */ ⋮---- getSystemStatus(params?: GetSystemStatusParamsV5): Promise< APIResponseV3WithTime<{ list: SystemStatusItemV5[]; }> > { return this.getPrivate('/v5/system/status', params); ⋮---- getClientType() ⋮---- async fetchServerTime(): Promise ⋮---- getServerTime(): Promise< APIResponseV3WithTime<{ timeSecond: string; timeNano: string }> > { return this.get('/v5/market/time'); ⋮---- /** * ****** Demo Account APIs * */ ⋮---- requestDemoTradingFunds(params?: { adjustType?: 0 | 1; utaDemoApplyMoney?: Array<{ coin: string; amountStr: string; }>; }): Promise > { return this.get('/v5/spread/instrument', params); ⋮---- /** * Get Spread Orderbook */ getSpreadOrderbook(params: { symbol: string; limit?: number; }): Promise> ⋮---- /** * Get Spread Tickers */ getSpreadTickers(params: { symbol: string }): Promise< APIResponseV3WithTime<{ list: SpreadTickerV5[]; }> > { return this.get('/v5/spread/tickers', params); ⋮---- /** * Get Spread Public Recent Trades */ getSpreadRecentTrades(params: { symbol: string; limit?: number }): Promise< APIResponseV3WithTime<{ list: SpreadRecentTradeV5[]; }> > { return this.get('/v5/spread/recent-trade', params); ⋮---- /** * Create Spread Order */ submitSpreadOrder(params: SubmitSpreadOrderParamsV5): Promise< APIResponseV3WithTime<{ orderId: string; orderLinkId: string; }> > { return this.postPrivate('/v5/spread/order/create', params); ⋮---- /** * Amend Spread Order * You can only modify unfilled or partially filled orders. */ amendSpreadOrder(params: AmendSpreadOrderParamsV5): Promise< APIResponseV3WithTime<{ orderId: string; orderLinkId: string; }> > { return this.postPrivate('/v5/spread/order/amend', params); ⋮---- /** * Cancel Spread Order */ cancelSpreadOrder(params: { orderId?: string; orderLinkId?: string; }): Promise< APIResponseV3WithTime<{ orderId: string; orderLinkId: string; }> > { return this.postPrivate('/v5/spread/order/cancel', params); ⋮---- /** * Cancel All Spread Orders * * When a symbol is specified, all orders for that symbol will be canceled regardless of the cancelAll field. * When symbol is not specified and cancelAll=true, all orders, regardless of the symbol, will be canceled. */ cancelAllSpreadOrders(params?: { symbol?: string; cancelAll?: boolean; }): Promise< APIResponseV3WithTime<{ list: { orderId: string; orderLinkId: string; }[]; success: string; }> > { return this.postPrivate('/v5/spread/order/cancel-all', params); ⋮---- /** * Get Spread Open Orders * Query unfilled or partially filled orders in real-time. */ getSpreadOpenOrders(params?: GetSpreadOpenOrdersParamsV5): Promise< APIResponseV3WithTime<{ list: SpreadOpenOrderV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/spread/order/realtime', params); ⋮---- /** * Get Spread Order History * * Note: * - orderId & orderLinkId has a higher priority than startTime & endTime * - Fully canceled orders are stored for up to 24 hours * - Single leg orders can also be found with "createType"=CreateByFutureSpread via Get Order History */ getSpreadOrderHistory(params?: GetSpreadOrderHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: SpreadOrderHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/spread/order/history', params); ⋮---- /** * Get Spread Trade History * * Note: * - In self-trade cases, both the maker and taker single-leg trades will be returned in the same request * - Single leg executions can also be found with "execType"=FutureSpread via Get Trade History */ getSpreadTradeHistory(params?: GetSpreadTradeHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: SpreadTradeV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/spread/execution/list', params); ⋮---- /** * ****** Market APIs * */ ⋮---- /** * Query the kline data. Charts are returned in groups based on the requested interval. * * Covers: Spot / Linear contract / Inverse contract */ getKline( params: GetKlineParamsV5, ): Promise< APIResponseV3WithTime< CategorySymbolListV5 > > { return this.get('/v5/market/kline', params); ⋮---- /** * Query the mark price kline data. Charts are returned in groups based on the requested interval. * * Covers: Linear contract / Inverse contract */ getMarkPriceKline( params: GetMarkPriceKlineParamsV5, ): Promise< APIResponseV3WithTime< CategorySymbolListV5 > > { return this.get('/v5/market/mark-price-kline', params); ⋮---- /** * Query the index price kline data. Charts are returned in groups based on the requested interval. * * Covers: Linear contract / Inverse contract */ getIndexPriceKline( params: GetIndexPriceKlineParamsV5, ): Promise< APIResponseV3WithTime< CategorySymbolListV5 > > { return this.get('/v5/market/index-price-kline', params); ⋮---- /** * Retrieve the premium index price kline data. Charts are returned in groups based on the requested interval. * * Covers: Linear contract */ getPremiumIndexPriceKline( params: GetPremiumIndexPriceKlineParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/premium-index-price-kline', params); ⋮---- /** * Query a list of instruments of online trading pair. * * Covers: Spot / Linear contract / Inverse contract / Option * * Note: Spot does not support pagination, so limit & cursor are invalid. */ getInstrumentsInfo( params: GetInstrumentsInfoParamsV5 & { category: C }, ): Promise>> ⋮---- /** * Query orderbook data * * Covers: Spot / Linear contract / Inverse contract / Option */ getOrderbook( params: GetOrderbookParamsV5, ): Promise> ⋮---- /** * Get RPI Orderbook * Query for orderbook depth data with RPI (Retail Price Improvement) information. * * Covers: Spot / USDT contract / USDC contract / Inverse contract * Contract: 50-level of RPI orderbook data * Spot: 50-level of RPI orderbook data */ getRPIOrderbook( params: GetRPIOrderbookParamsV5, ): Promise> ⋮---- getTickers( ⋮---- getTickers( params: GetTickersParamsV5<'option'>, ): Promise>>; ⋮---- getTickers( params: GetTickersParamsV5<'spot'>, ): Promise>>; ⋮---- /** * Query the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours. * * Covers: Spot / Linear contract / Inverse contract / Option */ getTickers( params: GetTickersParamsV5, ): Promise< APIResponseV3WithTime< | CategoryListV5 | CategoryListV5 | CategoryListV5 > > { return this.get('/v5/market/tickers', params); ⋮---- /** * Query historical funding rate. Each symbol has a different funding interval. * * Covers: Linear contract / Inverse perpetual */ getFundingRateHistory( params: GetFundingRateHistoryParamsV5, ): Promise< APIResponseV3WithTime< CategoryListV5 > > { return this.get('/v5/market/funding/history', params); ⋮---- /** * Query recent public trading data in Bybit. * * Covers: Spot / Linear contract / Inverse contract / Option */ getPublicTradingHistory( params: GetPublicTradingHistoryParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/recent-trade', params); ⋮---- /** * Get open interest of each symbol. * * Covers: Linear contract / Inverse contract */ getOpenInterest( params: GetOpenInterestParamsV5, ): Promise> ⋮---- /** * Query option historical volatility * Covers: Option */ getHistoricalVolatility( params: GetHistoricalVolatilityParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/historical-volatility', params); ⋮---- /** * Query Bybit insurance pool data (BTC/USDT/USDC etc). The data is updated every 24 hours. */ getInsurance( params?: GetInsuranceParamsV5, ): Promise> ⋮---- /** * Query risk limit of futures * * Covers: Linear contract / Inverse contract */ getRiskLimit( params?: GetRiskLimitParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/risk-limit', params); ⋮---- /** * Get the delivery price for option * * Covers: Option * * @deprecated use getDeliveryPrice() instead */ getOptionDeliveryPrice( params: GetOptionDeliveryPriceParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/delivery-price', params); ⋮---- /** * Get the delivery price of Inverse futures, USDC futures and Options * * Covers: USDC futures / Inverse futures / Option */ getDeliveryPrice( params: GetDeliveryPriceParamsV5, ): Promise>> ⋮---- /** * Get New Delivery Price * Get historical option delivery prices. * * Covers: Option * * INFO * - It is recommended to query this endpoint 1 minute after settlement is completed, because the data returned by this endpoint may be delayed by 1 minute. * - By default, the most recent 50 records are returned in reverse order of "deliveryTime". */ getNewDeliveryPrice(params: { category: 'option'; baseCoin: string; settleCoin?: string; }): Promise< APIResponseV3WithTime<{ category: string; list: { deliveryPrice: string; deliveryTime: string; }[]; }> > { return this.get('/v5/market/new-delivery-price', params); ⋮---- getLongShortRatio( params: GetLongShortRatioParamsV5, ): Promise>> ⋮---- /** * Get Index Price Components * Query for index price components that contribute to the calculation of an index price. */ getIndexPriceComponents( params: GetIndexPriceComponentsParamsV5, ): Promise> ⋮---- getOrderPriceLimit(params: { symbol: string; category: 'spot' | 'linear' | 'inverse'; }): Promise> ⋮---- /** * Get ADL Alert * Query for ADL (auto-deleveraging mechanism) alerts and insurance pool information. * * Covers: USDT Perpetual / USDT Delivery / USDC Perpetual / USDC Delivery / Inverse Contracts * Data update frequency: every 1 minute */ getADLAlert( params?: GetADLAlertParamsV5, ): Promise> ⋮---- /** * Get Fee Group Structure * Query for the group fee structure and fee rates. * * The new grouped fee structure only applies to Pro-level and Market Maker clients. * Covers: USDT Perpetual / USDT Delivery / USDC Perpetual / USDC Delivery / Inverse Contracts */ getFeeGroupStructure( params: GetFeeGroupStructureParamsV5, ): Promise> ⋮---- /** * ****** Trade APIs * */ ⋮---- submitOrder( params: OrderParamsV5, ): Promise> ⋮---- amendOrder( params: AmendOrderParamsV5, ): Promise> ⋮---- cancelOrder( params: CancelOrderParamsV5, ): Promise> ⋮---- /** * Query unfilled or partially filled orders in real-time. To query older order records, please use the order history interface. */ getActiveOrders( params: GetAccountOrdersParamsV5, ): Promise>> ⋮---- cancelAllOrders( params: CancelAllOrdersParamsV5, ): Promise< APIResponseV3WithTime<{ list: OrderResultV5[]; success: string }> > { return this.postPrivate('/v5/order/cancel-all', params); ⋮---- /** * Query order history. As order creation/cancellation is asynchronous, the data returned from this endpoint may delay. * * If you want to get real-time order information, you could query this endpoint or rely on the websocket stream (recommended). */ getHistoricOrders( params: GetAccountHistoricOrdersParamsV5, ): Promise>> ⋮---- /** * Query users' execution records, sorted by execTime in descending order * * Unified account covers: Spot / Linear contract / Options * Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures */ getExecutionList( params: GetExecutionListParamsV5, ): Promise>> ⋮---- /** * This endpoint allows you to place more than one order in a single request. * Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro) * * Make sure you have sufficient funds in your account when placing an order. * Once an order is placed, according to the funds required by the order, * the funds in your account will be frozen by the corresponding amount during the life cycle of the order. * * A maximum of 20 orders can be placed per request. The returned data list is divided into two lists. * The first list indicates whether or not the order creation was successful and the second list details the created order information. * The structure of the two lists are completely consistent. */ batchSubmitOrders( category: 'spot' | 'option' | 'linear' | 'inverse', orders: BatchOrderParamsV5[], ): Promise< APIResponseV3WithTime< { list: BatchCreateOrderResultV5[]; }, BatchOrdersRetExtInfoV5 > > { return this.postPrivate('/v5/order/create-batch', { category, request: orders, }); ⋮---- /** * This endpoint allows you to amend more than one open order in a single request. * Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro) * * You can modify unfilled or partially filled orders. Conditional orders are not supported. * * A maximum of 20 orders can be amended per request. */ batchAmendOrders( category: 'spot' | 'option' | 'linear' | 'inverse', orders: BatchAmendOrderParamsV5[], ): Promise< APIResponseV3WithTime< { list: BatchAmendOrderResultV5[]; }, BatchOrdersRetExtInfoV5 > > { return this.postPrivate('/v5/order/amend-batch', { category, request: orders, }); ⋮---- /** * This endpoint allows you to cancel more than one open order in a single request. * Covers: Option (UTA, UTA Pro) / USDT Perpetual, UDSC Perpetual, USDC Futures (UTA Pro) * * You must specify orderId or orderLinkId. If orderId and orderLinkId is not matched, the system will process orderId first. * * You can cancel unfilled or partially filled orders. A maximum of 20 orders can be cancelled per request. */ batchCancelOrders( category: 'spot' | 'option' | 'linear' | 'inverse', orders: BatchCancelOrderParamsV5[], ): Promise< APIResponseV3WithTime< { list: BatchCancelOrderResultV5[]; }, BatchOrdersRetExtInfoV5 > > { return this.postPrivate('/v5/order/cancel-batch', { category, request: orders, }); ⋮---- /** * Query the qty and amount of borrowable coins in spot account. * * Covers: Spot (Unified Account) */ getSpotBorrowCheck( symbol: string, side: OrderSideV5, ): Promise> ⋮---- /** * This endpoint allows you to set the disconnection protect time window. Covers: option (unified account). * * If you need to turn it on/off, you can contact your client manager for consultation and application. * The default time window is 10 seconds. * * Only for institutional clients! * * If it doesn't work, use v2! */ setDisconnectCancelAllWindow( category: 'option', timeWindow: number, ): Promise> ⋮---- /** * This endpoint allows you to set the disconnection protect time window. Covers: option (unified account). * * If you need to turn it on/off, you can contact your client manager for consultation and application. * The default time window is 10 seconds. * * Only for institutional clients! */ setDisconnectCancelAllWindowV2(params: { product?: 'OPTION' | 'SPOT' | 'DERIVATIVES'; timeWindow: number; }): Promise> ⋮---- /** * Pre-check order to calculate changes in IMR and MMR before placing an order * * This endpoint supports orders with category = inverse, linear, option. * Only Cross Margin mode and Portfolio Margin mode are supported, isolated margin mode is not supported. * category = inverse is not supported in Cross Margin mode. * Conditional order is not supported. */ preCheckOrder( params: OrderParamsV5, ): Promise> ⋮---- /** * ****** Position APIs * */ ⋮---- /** * Query real-time position data, such as position size, cumulative realizedPNL. * * 0: cross margin. 1: isolated margin * * Unified account covers: Linear contract / Options * * Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures * * Note: this will give a 404 error if you query the `option` category if your account is not unified */ getPositionInfo( params: PositionInfoParamsV5, ): Promise>> ⋮---- /** * Set the leverage * * Unified account covers: Linear contract * * Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures * * Note: Under one-way mode, buyLeverage must be the same as sellLeverage */ setLeverage(params: SetLeverageParamsV5): Promise> ⋮---- /** * This endpoint allows you to set the take profit, stop loss or trailing stop for a position. * Passing these parameters will create conditional orders by the system internally. * * The system will cancel these orders if the position is closed, and adjust the qty according to the size of the open position. * * Unified account covers: Linear contract. * Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures. */ setTradingStop( params: SetTradingStopParamsV5, ): Promise> ⋮---- /** * Query user's closed profit and loss records. The results are sorted by createdTime in descending order. * * Unified account covers: Linear contract * Normal account covers: USDT perpetual / Inverse perpetual / Inverse futures */ getClosedPnL( params: GetClosedPnLParamsV5, ): Promise>> ⋮---- /** * Get Closed Options Positions * Query user's closed options positions, sorted by closeTime in descending order * * INFO * Only supports users to query closed options positions in recently 6 months * Fee and price retain 8 decimal places and do not omit the last 0 */ getClosedOptionsPositions( params?: GetClosedOptionsPositionsParamsV5, ): Promise< APIResponseV3WithTime<{ nextPageCursor: string; category: string; list: ClosedOptionsPositionV5[]; }> > { return this.getPrivate('/v5/position/get-closed-positions', params); ⋮---- /** * Move positions between sub-master, master-sub, or sub-sub UIDs. * * Unified account covers: USDT perpetual / USDC contract / Spot / Option * * INFO * The endpoint can only be called by master UID api key * UIDs must be the same master-sub account relationship * The trades generated from move-position endpoint will not be displayed in the Recent Trade (Rest API & Websocket) * There is no trading fee * fromUid and toUid both should be Unified trading accounts, and they need to be one-way mode when moving the positions * Please note that once executed, you will get execType=MovePosition entry from Get Trade History, Get Closed Pnl, and stream from Execution. */ movePosition( params: MovePositionParamsV5, ): Promise> ⋮---- /** * Query moved position data by master UID api key. * * Unified account covers: USDT perpetual / USDC contract / Spot / Option */ getMovePositionHistory(params?: GetMovePositionHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: MovePositionHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/position/move-history', params); ⋮---- /** * Confirm new risk limit. * * It is only applicable when the user is marked as only reducing positions (please see the isReduceOnly field in the Get Position Info interface). * After the user actively adjusts the risk level, this interface is called to try to calculate the adjusted risk level, and if it passes (retCode=0), * the system will remove the position reduceOnly mark. You are recommended to call Get Position Info to check isReduceOnly field. * * Unified account covers: USDT perpetual / USDC contract / Inverse contract * Classic account covers: USDT perpetual / Inverse contract */ confirmNewRiskLimit( params: ConfirmNewRiskLimitParamsV5, ): Promise>> ⋮---- /** * Get users' execution records which occurred before you upgrade the account to Unified account, sorted by execTime in descending order * * For now, it only supports to query USDT perpetual, Inverse perpetual and futures. * * - You may have multiple executions in a single order. * - You can query by symbol, baseCoin, orderId and orderLinkId, and if you pass multiple params, * the system will process them according to this priority: orderId > orderLinkId > symbol > baseCoin. */ getPreUpgradeTradeHistory( params: GetPreUpgradeTradeHistoryParamsV5, ): Promise>> ⋮---- /** * Query user's closed profit and loss records. The results are sorted by createdTime in descending order. * * For now, it only supports to query USDT perpetual, Inverse perpetual and futures. */ getPreUpgradeClosedPnl( params: GetPreUpgradeClosedPnlParamsV5, ): Promise>> ⋮---- /** * Query transaction logs which occurred in the USDC Derivatives wallet before the account was upgraded to a Unified account. * * You can get USDC Perpetual, Option records. * * INFO * USDC Perpeual & Option support the recent 6 months data. Please download older data via GUI */ getPreUpgradeTransactions( params: GetPreUpgradeTransactionLogParamsV5, ): Promise< APIResponseV3WithTime<{ list: PreUpgradeTransaction[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/pre-upgrade/account/transaction-log', params); ⋮---- /** * Query delivery records of Option before you upgraded the account to a Unified account, sorted by deliveryTime in descending order. * * INFO * Supports the recent 6 months data. Please download older data via GUI */ getPreUpgradeOptionDeliveryRecord( params: GetPreUpgradeOptionDeliveryRecordParamsV5, ): Promise< APIResponseV3WithTime> > { return this.getPrivate('/v5/pre-upgrade/asset/delivery-record', params); ⋮---- /** * Query session settlement records of USDC perpetual before you upgrade the account to Unified account. * * INFO * USDC Perpetual support the recent 6 months data. Please download older data via GUI */ getPreUpgradeUSDCSessionSettlements( params: GetPreUpgradeUSDCSessionParamsV5, ): Promise< APIResponseV3WithTime< CategoryCursorListV5 > > { return this.getPrivate('/v5/pre-upgrade/asset/settlement-record', params); ⋮---- /** * ****** Account APIs * */ ⋮---- /** * Obtain wallet balance, query asset information of each currency, and account risk rate information under unified margin mode. * * By default, currency information with assets or liabilities of 0 is not returned. */ getWalletBalance( params: GetWalletBalanceParamsV5, ): Promise > { return this.getPrivate('/v5/account/withdrawal', params); ⋮---- /** * Get Account Instruments Info * Query for the instrument specification of online trading pairs that available to users. * * Covers: SPOT / USDT contract / USDC contract / Inverse contract * * Includes RPI permission information (isPublicRpi, myRpiPermission) */ getAccountInstrumentsInfo( params: GetAccountInstrumentsInfoParamsV5 & { category: C }, ): Promise>> ⋮---- /** * Upgrade to unified account. * * Banned/OTC loan/Net asset unsatisfying/Express path users cannot upgrade the account to Unified Account for now. */ upgradeToUnifiedAccount(): Promise< APIResponseV3WithTime > { return this.postPrivate('/v5/account/upgrade-to-uta'); ⋮---- /** * Get interest records, sorted in reverse order of creation time. * * Unified account */ getBorrowHistory( params?: GetBorrowHistoryParamsV5, ): Promise>> ⋮---- /** * You can manually repay the liabilities of Unified account * Applicable: Unified Account * Permission: USDC Contracts * * - Input the specific coin: repay the liability of this coin in particular * - No coin specified: repay the liability of all coins */ repayLiability( params?: RepayLiabilityParamsV5, ): Promise>> ⋮---- /** * Manual Repay * * If neither coin nor amount is passed, then repay all the liabilities. * If coin is passed and amount is not, the coin will be repaid in full. * * When repaying, the system will first use the spot available balance of the debt currency. * If that's not enough, the remaining amount will be repaid by converting other assets. * * Repayment is prohibited between 04:00 and 05:30 per hour. */ manualRepay( params?: ManualRepayParamsV5, ): Promise> ⋮---- /** * You can decide whether the assets in the Unified account needs to be collateral coins. */ setCollateralCoin( params: SetCollateralCoinParamsV5, ): Promise>> ⋮---- /** * Query the margin mode and the upgraded status of account */ getAccountInfo(): Promise> ⋮---- /** * Query the DCP configuration of the account's contracts (USDT perpetual, USDC perpetual and USDC Futures) / spot / options. * * Only the configured main / sub account can query information from this API. Calling this API by an account always returns empty. * * INFO * support linear contract (USDT, USDC Perp & USDC Futures) / Spot / Options only * Unified account only */ getDCPInfo(): Promise>> ⋮---- /** * Query transaction logs in the derivatives wallet (classic account), and inverse derivatives wallet (upgraded to UTA). * * API key permission: "Contract - Position" */ getClassicTransactionLogs( params?: GetClassicTransactionLogsParamsV5, ): Promise< APIResponseV3WithTime<{ list: TransactionLogV5[]; nextPageCursor: string }> > { return this.getPrivate('/v5/account/contract-transaction-log', params); ⋮---- /** * Query the SMP group ID of self match prevention. */ getSMPGroup(): Promise< APIResponseV3WithTime<{ smpGroup: number; }> > { return this.getPrivate('/v5/account/smp-group'); ⋮---- /** * Default is regular margin mode. * * This mode is valid for USDT Perp, USDC Perp and USDC Option. */ setMarginMode( marginMode: AccountMarginModeV5, ): Promise< APIResponseV3<{ reasons: { reasonCode: string; reasonMsg: string }[] }> > { return this.postPrivate('/v5/account/set-margin-mode', { setMarginMode: marginMode, }); ⋮---- /** * Turn on/off Spot hedging feature in Portfolio margin for Unified account. * * INFO * Only unified account is applicable * Only portfolio margin mode is applicable */ setSpotHedging(params: { setHedgingMode: 'ON' | 'OFF'; }): Promise > { return this.getPrivate('/v5/account/user-setting-config'); ⋮---- /** * Configure Market Maker Protection (MMP) */ setMMP(params: MMPModifyParamsV5): Promise> ⋮---- /** * Once the mmp triggered, you can unfreeze the account via this endpoint */ resetMMP(baseCoin: string): Promise> ⋮---- /** * Get MMP State */ getMMPState( baseCoin: string, ): Promise>> ⋮---- /** * Query session settlement records of USDC perpetual * * Covers: Linear contract (USDC Perpetual only, Unified Account) */ getSettlementRecords( params: GetSettlementRecordParamsV5, ): Promise< APIResponseV3WithTime> > { return this.getPrivate('/v5/asset/settlement-record', params); ⋮---- /** * Query the coin exchange records. * * CAUTION: You may experience long delays with this endpoint. */ getCoinExchangeRecords(params?: GetCoinExchangeRecordParamsV5): Promise< APIResponseV3WithTime<{ orderBody: CoinExchangeRecordV5[]; nextPageCursor?: string; }> > { return this.getPrivate('/v5/asset/exchange/order-record', params); ⋮---- /** * Query coin information, including chain information, withdraw and deposit status. */ getCoinInfo( coin?: string, ): Promise > { return this.getPrivate('/v5/asset/transfer/query-sub-member-list'); ⋮---- /** * Query asset information. * * INFO * For now, it can query SPOT only. */ getAssetInfo( params: GetAssetInfoParamsV5, ): Promise> ⋮---- /** * Query the balance of a specific coin in a specific account type. Supports querying sub UID's balance. * * CAUTION: Can query by the master UID's api key only. */ getCoinBalance( params: GetAccountCoinBalanceParamsV5, ): Promise> ⋮---- /** * Query withdrawable amount. */ getWithdrawableAmount(params: { coin: string; }): Promise>> ⋮---- /** * Enable Universal Transfer for Sub UID * * Use this endpoint to enable a subaccount to take part in a universal transfer. * It is a one-time switch which, once thrown, enables a subaccount permanently. * If not set, your subaccount cannot use universal transfers. * * @deprecated - You no longer need to configure transferable sub UIDs. * Now, all sub UIDs are automatically enabled for universal transfer. * */ enableUniversalTransferForSubUIDs( subMemberIds: string[], ): Promise>> ⋮---- /** * Query allowed deposit coin information. * To find out paired chain of coin, please refer to the coin info api. */ getAllowedDepositCoinInfo( params?: GetAllowedDepositCoinInfoParamsV5, ): Promise< APIResponseV3WithTime<{ configList: AllowedDepositCoinInfoV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/asset/deposit/query-allowed-list', params); ⋮---- /** * Set auto transfer account after deposit. The same function as the setting for Deposit on web GUI */ setDepositAccount(params: { accountType: AccountTypeV5 }): Promise< APIResponseV3WithTime<{ status: 0 | 1; }> > { return this.postPrivate('/v5/asset/deposit/deposit-to-account', params); ⋮---- /** * Query deposit records. * * TIP * endTime - startTime should be less than 30 days. Query last 30 days records by default. * * Can use main or sub UID api key to query deposit records respectively. */ getDepositRecords( params?: GetDepositRecordParamsV5, ): Promise< APIResponseV3WithTime<{ rows: DepositRecordV5[]; nextPageCursor: string }> > { return this.getPrivate('/v5/asset/deposit/query-record', params); ⋮---- /** * Query subaccount's deposit records by MAIN UID's API key. * * TIP: Query deposit records of SPOT only * endTime - startTime should be less than 30 days. * Queries for the last 30 days worth of records by default. */ getSubAccountDepositRecords( params: GetSubAccountDepositRecordParamsV5, ): Promise< APIResponseV3WithTime<{ rows: DepositRecordV5[]; nextPageCursor: string }> > { return this.getPrivate('/v5/asset/deposit/query-sub-member-record', params); ⋮---- /** * Get Internal Deposit Records (across Bybit) * Query deposit records through Bybit platform * * RULES * The maximum difference between the start time and the end time is 30 days. * Support to get deposit records by Master or Sub Member Api Key */ getInternalDepositRecords(params?: GetInternalDepositRecordParamsV5): Promise< APIResponseV3WithTime<{ rows: InternalDepositRecordV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/asset/deposit/query-internal-record', params); ⋮---- /** * Query the deposit address information of MASTER account. */ getMasterDepositAddress( coin: string, chainType?: string, ): Promise< APIResponseV3WithTime<{ coin: string; chains: DepositAddressChainV5[]; }> > { return this.getPrivate('/v5/asset/deposit/query-address', { coin, chainType, }); ⋮---- /** * Query the deposit address information of SUB account. */ getSubDepositAddress( coin: string, chainType: string, subMemberId: string, ): Promise< APIResponseV3WithTime<{ coin: string; chains: DepositAddressChainV5; }> > { return this.getPrivate('/v5/asset/deposit/query-sub-member-address', { coin, chainType, subMemberId, }); ⋮---- /** * @deprecated - duplicate function, use getSubDepositAddress() instead * Query the deposit address information of SUB account. * @deprecated Duplicate endpoint - Use getSubDepositAddress() instead * * CAUTION * Can use master UID's api key only */ querySubMemberAddress( coin: string, chainType: string, subMemberId: string, ): Promise< APIResponseV3<{ coin: string; chains: DepositAddressChainV5; }> > { return this.getPrivate('/v5/asset/deposit/query-sub-member-address', { coin, chainType, subMemberId, }); ⋮---- /** * Query withdrawal records. */ getWithdrawalRecords( params?: GetWithdrawalRecordsParamsV5, ): Promise>> ⋮---- /** * Get Withdrawal Address List * Query the withdrawal addresses in the address book. * * TIP: The API key for querying this endpoint must have withdrawal permissions. */ getWithdrawalAddressList(params?: GetWithdrawalAddressListParamsV5): Promise< APIResponseV3WithTime<{ rows: WithdrawalAddressV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/asset/withdraw/query-address', params); ⋮---- /** * Get Exchange Entity List. * * This endpoint is particularly used for kyc=KOR users. When withdraw funds, you need to fill entity id. */ getExchangeEntities(): Promise< APIResponseV3WithTime<{ vasp: VaspEntityV5[] }> > { return this.getPrivate('/v5/asset/withdraw/vasp/list'); ⋮---- /** * Withdraw assets from the SPOT account. * * CAUTION: Make sure you have whitelisted your wallet address before calling this endpoint. * * You can make an off-chain transfer if the target wallet address is from Bybit. This means that no blockchain fee will be charged. */ submitWithdrawal( params: WithdrawParamsV5, ): Promise > { return this.getPrivate('/v5/asset/exchange/query-coin-list', params); ⋮---- /** * Request a quote for converting coins. */ requestConvertQuote( params: RequestConvertQuoteParamsV5, ): Promise> ⋮---- /** * Confirm a quote for converting coins. */ confirmConvertQuote(params: { quoteTxId: string }): Promise< APIResponseV3WithTime<{ quoteTxId: string; exchangeStatus: 'init' | 'processing' | 'success' | 'failure'; }> > { return this.postPrivate('/v5/asset/exchange/convert-execute', params); ⋮---- /** * Query the exchange result by sending quoteTxId. */ getConvertStatus(params: { quoteTxId: string; accountType: | 'eb_convert_funding' | 'eb_convert_uta' | 'eb_convert_spot' | 'eb_convert_contract' | 'eb_convert_inverse'; }): Promise< APIResponseV3WithTime<{ result: ConvertStatusV5; }> > { return this.getPrivate('/v5/asset/exchange/convert-result-query', params); ⋮---- /** * Query the conversion history. */ getConvertHistory(params?: GetConvertHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: ConvertHistoryRecordV5[]; }> > { return this.getPrivate('/v5/asset/exchange/query-convert-history', params); ⋮---- /** * ****** User APIs * */ ⋮---- /** * Create a new sub user id. Use master user's api key only. * * The API key must have one of the permissions to be allowed to call the following API endpoint. * - master API key: "Account Transfer", "Subaccount Transfer", "Withdrawal" */ createSubMember( params: CreateSubMemberParamsV5, ): Promise> ⋮---- /** * To create new API key for those newly created sub UID. Use master user's api key only. * * TIP: The API key must have one of the permissions to be allowed to call the following API endpoint. * - master API key: "Account Transfer", "Subaccount Transfer", "Withdrawal" */ createSubUIDAPIKey( params: CreateSubApiKeyParamsV5, ): Promise> ⋮---- /** * This endpoint allows you to get a list of all sub UID of master account. At most 10k subaccounts. */ getSubUIDList(): Promise< APIResponseV3WithTime<{ subMembers: SubMemberV5[] }> > { return this.getPrivate('/v5/user/query-sub-members'); ⋮---- /** * This endpoint allows you to get a list of all sub UID of master account. No limit on the number of subaccounts. */ getSubUIDListUnlimited(params?: { pageSize?: string; nextCursor?: string; }): Promise< APIResponseV3WithTime<{ subMembers: SubMemberV5[]; nextCursor: string; }> > { return this.getPrivate('/v5/user/submembers', params); ⋮---- /** * Froze sub uid. Use master user's api key only. * * TIP: The API key must have one of the permissions to be allowed to call the following API endpoint. * - master API key: "Account Transfer", "Subaccount Transfer", "Withdrawal" */ setSubUIDFrozenState( subuid: number, frozen: 0 | 1, ): Promise> ⋮---- /** * Query all api keys information of a sub UID. */ getSubAccountAllApiKeys(params: GetSubAccountAllApiKeysParamsV5): Promise< APIResponseV3WithTime<{ result: ApiKeyInfoV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/user/sub-apikeys', params); ⋮---- getUIDWalletType(params: { memberIds: string }): Promise< APIResponseV3WithTime<{ accounts: { uid: string; accountType: string[]; }[]; }> > { return this.getPrivate('/v5/user/get-member-type', params); ⋮---- /** * Modify the settings of a master API key. Use the API key pending to be modified to call the endpoint. Use master user's API key only. * * TIP: The API key must have one of the permissions to be allowed to call the following API endpoint. * - master API key: "Account Transfer", "Subaccount Transfer", "Withdrawal" */ updateMasterApiKey( params: UpdateApiKeyParamsV5, ): Promise> ⋮---- /** * This endpoint modifies the settings of a sub API key. * Use the API key pending to be modified to call the endpoint or use master account api key to manage its sub account api key. * The API key must have one of the below permissions in order to call this endpoint * * - sub API key: "Account Transfer", "Sub Member Transfer" * - master API Key: "Account Transfer", "Sub Member Transfer", "Withdrawal" */ updateSubApiKey( params: UpdateApiKeyParamsV5, ): Promise> ⋮---- /** * Delete a sub UID. Before deleting the UID, please make sure there are no assets. * * TIP: * The API key must have one of the permissions to be allowed to call the following API endpoint. * - master API key: "Account Transfer", "Subaccount Transfer", "Withdrawal" */ deleteSubMember( params: DeleteSubMemberParamsV5, ): Promise > { return this.getPrivate('/v5/affiliate/aff-user-list', params); ⋮---- /** * Get Affiliate User Info. * * This API is used for affiliate to get their users information. * * TIP * Use master UID only * The api key can only have "Affiliate" permission * The transaction volume and deposit amount are the total amount of the user done on Bybit, and have nothing to do with commission settlement. Any transaction volume data related to commission settlement is subject to the Affiliate Portal. */ getAffiliateUserInfo(params: { uid: string; }): Promise> ⋮---- /** * ****** Spot Margin Trade APIs (UTA) * */ ⋮---- /** * Get VIP Margin Data. * * This margin data is for Unified account in particular. * * INFO * Do not need authentication */ getVIPMarginData( params?: GetVIPMarginDataParamsV5, ): Promise> ⋮---- /** * Get Historical Interest Rate * You can query up to six months borrowing interest rate of Margin trading. * INFO: Need authentication, the api key needs "Spot" permission. Only supports Unified account. */ getHistoricalInterestRate(params: { currency: string; vipLevel?: string; startTime?: number; endTime?: number; }): Promise< APIResponseV3WithTime<{ list: { timestamp: number; currency: string; hourlyBorrowRate: string; vipLevel: string; }[]; }> > { return this.getPrivate( '/v5/spot-margin-trade/interest-rate-history', params, ); ⋮---- /** * Turn spot margin trade on / off in your UTA account. * * CAUTION * Your account needs to turn on spot margin first. */ toggleSpotMarginTrade( spotMarginMode: '1' | '0', ): Promise> ⋮---- /** * Manual borrow for UTA */ manualBorrow( params: ManualBorrowParamsV5, ): Promise> ⋮---- /** * Get max borrowable amount */ getMaxBorrowableAmount( params: GetMaxBorrowableAmountParamsV5, ): Promise> ⋮---- /** * Get loan position risk information (position tiers) */ getPositionTiers(params?: GetPositionTiersParamsV5): Promise< APIResponseV3WithTime<{ list: CurrencyPositionTiersV5[]; }> > { return this.getPrivate('/v5/spot-margin-trade/position-tiers', params); ⋮---- /** * Get currency leverage information (coin state) */ getCoinState(params?: GetCoinStateParamsV5): Promise< APIResponseV3WithTime<{ list: CoinStateV5[]; }> > { return this.getPrivate('/v5/spot-margin-trade/coinstate', params); ⋮---- /** * Get available amount to repay */ getAvailableAmountToRepay( params: GetAvailableAmountToRepayParamsV5, ): Promise> ⋮---- /** * Manual repay without asset conversion * * IMPORTANT: Repayment is prohibited between 04:00 and 05:30 per hour. * When repaying, system will only use the spot available balance of the debt currency. */ manualRepayWithoutConversion( params: ManualRepayWithoutConversionParamsV5, ): Promise> ⋮---- /** * ****** Spot Margin Trade APIs (Normal) * */ ⋮---- /** * Get Margin Coin Info */ getSpotMarginCoinInfo(coin?: string): Promise< APIResponseV3WithTime<{ list: { coin: string; conversionRate: string; liquidationOrder: number; }[]; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/pledge-token', { coin, }); ⋮---- /** * Get Borrowable Coin Info */ getSpotMarginBorrowableCoinInfo(coin?: string): Promise< APIResponseV3WithTime<{ list: { coin: string; borrowingPrecision: number; repaymentPrecision: number; }[]; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/borrow-token', { coin, }); ⋮---- /** * Get Interest & Quota */ getSpotMarginInterestAndQuota(coin: string): Promise< APIResponseV3WithTime<{ list: { coin: string; interestRate: string; loanAbleAmount: string; maxLoanAmount: string; }[]; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/loan-info', { coin, }); ⋮---- /** * Get Loan Account Info */ getSpotMarginLoanAccountInfo(): Promise< APIResponseV3WithTime<{ acctBalanceSum: string; debtBalanceSum: string; loanAccountList: { free: string; interest: string; loan: string; remainAmount: string; locked: string; tokenId: string; total: string; }[]; riskRate: string; status: number; switchStatus: number; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/account'); ⋮---- /** * Borrow */ spotMarginBorrow(params: { coin: string; qty: string }): Promise< APIResponseV3WithTime<{ transactId: string; }> > { return this.postPrivate('/v5/spot-cross-margin-trade/loan', params); ⋮---- /** * Repay */ spotMarginRepay(params: { coin: string; qty?: string; completeRepayment: 0 | 1; }): Promise< APIResponseV3WithTime<{ repayId: string; }> > { return this.postPrivate('/v5/spot-cross-margin-trade/repay', params); ⋮---- /** * Get Borrow Order Detail */ getSpotMarginBorrowOrderDetail(params?: { startTime?: number; endTime?: number; coin?: string; status?: 0 | 1 | 2; limit?: number; }): Promise< APIResponseV3WithTime<{ list: { accountId: string; coin: string; createdTime: number; id: string; interestAmount: string; interestBalance: string; loanAmount: string; loanBalance: string; remainAmount: string; status: string; type: string; }[]; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/orders', params); ⋮---- /** * Get Repayment Order Detail */ getSpotMarginRepaymentOrderDetail(params?: { startTime?: number; endTime?: number; coin?: string; limit?: number; }): Promise< APIResponseV3WithTime<{ list: { accountId: string; coin: string; repaidAmount: string; repayId: string; repayMarginOrderId: string; repayTime: string; transactIds: { repaidInterest: string; repaidPrincipal: string; repaidSerialNumber: string; transactId: string; }[]; }[]; }> > { return this.getPrivate('/v5/spot-cross-margin-trade/repay-history', params); ⋮---- /** * Turn spot margin trade on / off in your NORMAL account. */ toggleSpotCrossMarginTrade(params: { switch: 1 | 0; }): Promise > { return this.get('/v5/crypto-loan/collateral-data', params); ⋮---- /** * Get Borrowable Coins * * INFO: Do not need authentication * @deprecated - Use "Crypto Loan - New" Endpoints instead */ getBorrowableCoins(params?: { vipLevel?: string; currency?: string; }): Promise< APIResponseV3WithTime<{ vipCoinList: VipBorrowableCoinsV5[]; }> > { return this.get('/v5/crypto-loan/loanable-data', params); ⋮---- /** * Get Account Borrow/Collateral Limit * Query the account borrowable/collateral limit * * Permission: "Spot trade" * @deprecated - Use "Crypto Loan - New" Endpoints instead */ getAccountBorrowCollateralLimit(params: { loanCurrency: string; collateralCurrency: string; }): Promise> ⋮---- /** * Borrow Crypto Loan * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" * * INFO: * The loan funds are released to the Funding account * The collateral funds are deducted from the Funding account, so make sure you have enough collateral amount in the funding wallet */ borrowCryptoLoan(params: BorrowCryptoLoanParamsV5): Promise< APIResponseV3WithTime<{ orderId: string; }> > { return this.postPrivate('/v5/crypto-loan/borrow', params); ⋮---- /** * Repay Crypto Loan * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * You can repay partial loan. If there is interest occurred, interest will be repaid in priority * * Permission: "Spot trade" * * INFO: * The repaid amount will be deducted from Funding account * The collateral amount will not be auto returned when you don't fully repay the debt, but you can also adjust collateral amount */ repayCryptoLoan(params: { orderId: string; amount: string }): Promise< APIResponseV3WithTime<{ repayId: string; }> > { return this.postPrivate('/v5/crypto-loan/repay', params); ⋮---- /** * Get Unpaid Loan Orders * Query the ongoing loan orders, which are not fully repaid * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" */ getUnpaidLoanOrders(params?: GetUnpaidLoanOrdersParamsV5): Promise< APIResponseV3WithTime<{ list: UnpaidLoanOrderV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan/ongoing-orders', params); ⋮---- /** * Get Repayment Transaction History * Query repaid transaction history * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" * * INFO: * Support querying last 6 months completed loan orders * Only successful repayments can be queried */ getRepaymentHistory(params?: GetRepaymentHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: RepaymentHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan/repayment-history', params); ⋮---- /** * Get Completed Loan Order History * Query the completed loan orders * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" * * INFO: * Support querying last 6 months completed loan orders */ getCompletedLoanOrderHistory( params?: GetCompletedLoanOrderHistoryParamsV5, ): Promise< APIResponseV3WithTime<{ list: CompletedLoanOrderV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan/borrow-history', params); ⋮---- /** * Get Max. Allowed Reduction Collateral Amount * Query the maximum allowed reduction collateral amount * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" */ getMaxAllowedReductionCollateralAmount(params: { orderId: string }): Promise< APIResponseV3WithTime<{ maxCollateralAmount: string; }> > { return this.getPrivate('/v5/crypto-loan/max-collateral-amount', params); ⋮---- /** * Adjust Collateral Amount * You can increase or reduce collateral amount. When you reduce, please follow the max. allowed reduction amount. * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" * * INFO: * The adjusted collateral amount will be returned to or deducted from Funding account */ adjustCollateralAmount(params: { orderId: string; amount: string; direction: '0' | '1'; }): Promise< APIResponseV3WithTime<{ adjustId: string; }> > { return this.postPrivate('/v5/crypto-loan/adjust-ltv', params); ⋮---- /** * Get Loan LTV Adjustment History * Query the transaction history of collateral amount adjustment * * @deprecated - Use "Crypto Loan - New" Endpoints instead * * Permission: "Spot trade" * * INFO: * Support querying last 6 months adjustment transactions * Only the ltv adjustment transactions launched by the user can be queried */ getLoanLTVAdjustmentHistory( params?: GetLoanLTVAdjustmentHistoryParamsV5, ): Promise< APIResponseV3WithTime<{ list: LoanLTVAdjustmentHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan/adjustment-history', params); ⋮---- /** * ****** Crypto Loan New * */ ⋮---- /** * Get Borrowable Coins New * */ getLoanBorrowableCoins(params?: GetBorrowableCoinsParamsV5): Promise< APIResponseV3WithTime<{ list: BorrowableCoinV5[]; }> > { return this.get('/v5/crypto-loan-common/loanable-data', params); ⋮---- /** * Get Collateral Coins New * */ getLoanCollateralCoins( params?: GetCollateralCoinsParamsV5, ): Promise> ⋮---- /** * Get Max. Allowed Collateral Reduction Amount New * */ getMaxCollateralAmount(params: GetMaxCollateralAmountParamsV5): Promise< APIResponseV3WithTime<{ maxCollateralAmount: string; }> > { return this.getPrivate( '/v5/crypto-loan-common/max-collateral-amount', params, ); ⋮---- /** * Adjust Collateral Amount New * You can increase or reduce your collateral amount. When you reduce, please obey the Get Max. Allowed Collateral Reduction Amount */ updateCollateralAmount( params: AdjustCollateralAmountParamsV5, ): Promise> ⋮---- /** * Get Collateral Adjustment History New * Query for your LTV adjustment history. * */ getCollateralAdjustmentHistory( params?: GetCollateralAdjustmentHistoryParamsV5, ): Promise< APIResponseV3WithTime<{ list: CollateralAdjustmentHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-common/adjustment-history', params); ⋮---- /** * Get Crypto Loan Position New * */ getCryptoLoanPosition(): Promise< APIResponseV3WithTime > { return this.getPrivate('/v5/crypto-loan-common/position'); ⋮---- /** * ****** Crypto Loan New - Flexible Loan * */ ⋮---- /** * Borrow Flexible Loan * Fully or partially repay a loan. If interest is due, that is paid off first, with the loaned amount being paid off only after due interest. * */ borrowFlexible( params: BorrowFlexibleParamsV5, ): Promise> ⋮---- /** * Repay Flexible Loan * Fully or partially repay a loan. If interest is due, that is paid off first, with the loaned amount being paid off only after due interest. * */ repayFlexible( params: RepayFlexibleParamsV5, ): Promise> ⋮---- /** * Collateral Repayment * Pay interest first, then repay the principal. */ repayCollateralFlexible( params: RepayCollateralFlexibleParamsV5, ): Promise > { return this.getPrivate('/v5/crypto-loan-flexible/ongoing-coin', params); ⋮---- /** * Get Borrow Orders History * */ getBorrowHistoryFlexible(params?: GetBorrowHistoryFlexibleParamsV5): Promise< APIResponseV3WithTime<{ list: BorrowHistoryFlexibleV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-flexible/borrow-history', params); ⋮---- /** * Get Repayment Orders History * */ getRepaymentHistoryFlexible( params?: GetRepaymentHistoryFlexibleParamsV5, ): Promise< APIResponseV3WithTime<{ list: RepaymentHistoryFlexibleV5[]; nextPageCursor: string; }> > { return this.getPrivate( '/v5/crypto-loan-flexible/repayment-history', params, ); ⋮---- /** * ****** Fixed Loan * */ ⋮---- /** * Get Supplying Market * If you want to supply, you can use this endpoint to check whether there are any suitable counterparty borrow orders available. * */ getSupplyOrderQuoteFixed(params: GetSupplyOrderQuoteFixedParamsV5): Promise< APIResponseV3WithTime<{ list: SupplyOrderQuoteFixedV5[]; }> > { return this.get('/v5/crypto-loan-fixed/supply-order-quote', params); ⋮---- /** * Get Borrowing Market * If you want to borrow, you can use this endpoint to check whether there are any suitable counterparty supply orders available. * */ getBorrowOrderQuoteFixed(params: GetBorrowOrderQuoteFixedParamsV5): Promise< APIResponseV3WithTime<{ list: BorrowOrderQuoteFixedV5[]; }> > { return this.get('/v5/crypto-loan-fixed/borrow-order-quote', params); ⋮---- /** * Create Borrow Order * The loan funds are released to the Funding wallet. * The collateral funds are deducted from the Funding wallet, so make sure you have enough collateral amount in the Funding wallet. */ createBorrowOrderFixed( params: CreateBorrowOrderFixedParamsV5, ): Promise> ⋮---- /** * Create Supply Order * * Permission: "Spot trade" */ createSupplyOrderFixed( params: CreateSupplyOrderFixedParamsV5, ): Promise> ⋮---- /** * Cancel Borrow Order * */ cancelBorrowOrderFixed( params: CancelBorrowOrderFixedParamsV5, ): Promise > { return this.getPrivate( '/v5/crypto-loan-fixed/borrow-contract-info', params, ); ⋮---- /** * Get Supply Contract Info * */ getSupplyContractInfoFixed( params?: GetSupplyContractInfoFixedParamsV5, ): Promise< APIResponseV3WithTime<{ list: SupplyContractInfoFixedV5[]; nextPageCursor: string; }> > { return this.getPrivate( '/v5/crypto-loan-fixed/supply-contract-info', params, ); ⋮---- /** * Get Borrow Order Info * */ getBorrowOrderInfoFixed(params?: GetBorrowOrderInfoFixedParamsV5): Promise< APIResponseV3WithTime<{ list: BorrowOrderInfoFixedV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-fixed/borrow-order-info', params); ⋮---- /** * Get Supply Order Info * */ getSupplyOrderInfoFixed(params?: GetSupplyOrderInfoFixedParamsV5): Promise< APIResponseV3WithTime<{ list: SupplyOrderInfoFixedV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-fixed/supply-order-info', params); ⋮---- /** * Repay Fixed Loan * Either loanId or loanCurrency needs to be passed * */ repayFixed( params: RepayFixedParamsV5, ): Promise> ⋮---- /** * Collateral Repayment * Pay interest first, then repay the principal. * */ repayCollateralFixed( params: RepayCollateralFixedParamsV5, ): Promise > { return this.getPrivate('/v5/crypto-loan-fixed/repayment-history', params); ⋮---- /** * Renew Borrow Order * This endpoint allows you to re-borrow the principal that was previously repaid. * The renewal amount is the same as the amount previously repaid on this loan. * * Permission: "Spot trade" * UID rate limit: 1 req / second */ renewBorrowOrderFixed( params: RenewBorrowOrderFixedParamsV5, ): Promise> ⋮---- /** * Get Renew Order Info * Query for renew order information * * Permission: "Spot trade" * UID rate limit: 5 req / second */ getRenewOrderInfoFixed(params?: GetRenewOrderInfoFixedParamsV5): Promise< APIResponseV3WithTime<{ list: RenewOrderInfoFixedV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-fixed/renew-info', params); ⋮---- /** * ****** Institutional Lending * */ ⋮---- /** * Get Product Info */ getInstitutionalLendingProductInfo( productId?: string, ): Promise > { return this.getPrivate('/v5/ins-loan/ltv'); ⋮---- /** * Get LTV with Ladder Conversion Rate */ getInstitutionalLendingLTVWithLadderConversionRate(): Promise< APIResponseV3WithTime<{ ltvInfo: any[] }> > { return this.getPrivate('/v5/ins-loan/ltv-convert'); ⋮---- /** * Bind or unbind UID for the institutional loan product. * * INFO * Risk unit designated UID cannot be unbound * This endpoint can only be called by uids in the risk unit list * The UID must be upgraded to UTA Pro if you try to bind it. * When the API is operated through the API Key of any UID in the risk unit, the UID is bound or unbound in the risk unit. */ bindOrUnbindUID(params: { uid: string; operate: '0' | '1' }): Promise< APIResponseV3WithTime<{ uid: string; operate: '0' | '1'; }> > { return this.postPrivate('/v5/ins-loan/association-uid', params); ⋮---- /** * ****** Broker * */ ⋮---- /** * Get Exchange Broker Earning. * * INFO * Use exchange broker master account to query * The data can support up to past 1 months until T-1. To extract data from over a month ago, please contact your Relationship Manager * begin & end are either entered at the same time or not entered, and latest 7 days data are returned by default * API rate limit: 10 req / sec */ getExchangeBrokerEarnings( params?: GetExchangeBrokerEarningsParamsV5, ): Promise> ⋮---- /** * Get Exchange Broker Account Info. * * INFO * Use exchange broker master account to query * API rate limit: 10 req / sec */ getExchangeBrokerAccountInfo(): Promise< APIResponseV3WithTime > { return this.getPrivate('/v5/broker/account-info'); ⋮---- /** * Get Sub Account Deposit Records. * * Exchange broker can query subaccount's deposit records by main UID's API key without specifying uid. * * API rate limit: 300 req / min * * TIP * endTime - startTime should be less than 30 days. Queries for the last 30 days worth of records by default. */ getBrokerSubAccountDeposits(params?: GetBrokerSubAccountDepositsV5): Promise< APIResponseV3WithTime<{ rows: ExchangeBrokerSubAccountDepositRecordV5[]; nextPageCursor: string; }> > { return this.getPrivate( '/v5/broker/asset/query-sub-member-deposit-record', params, ); ⋮---- /** * Query Voucher Spec */ getBrokerVoucherSpec(params: { id: string; }): Promise> ⋮---- /** * Issue a voucher to a user * * INFO * Use exchange broker master account to issue */ issueBrokerVoucher( params: IssueVoucherParamsV5, ): Promise> ⋮---- /** * Query an issued voucher * * INFO * Use exchange broker master account to query */ getBrokerIssuedVoucher( params: GetBrokerIssuedVoucherParamsV5, ): Promise> ⋮---- /** * ****** EARN * */ ⋮---- /** * Get Product Info for Earn products * * INFO: Do not need authentication */ getEarnProduct(params: { category: string; coin?: string }): Promise< APIResponseV3WithTime<{ list: EarnProductV5[]; }> > { return this.get('/v5/earn/product', params); ⋮---- /** * Stake or Redeem Earn products * * INFO: API key needs "Earn" permission * * NOTE: In times of high demand for loans in the market for a specific cryptocurrency, * the redemption of the principal may encounter delays and is expected to be processed * within 48 hours. Once the redemption request is initiated, it cannot be canceled, * and your principal will continue to earn interest until the process is completed. */ submitStakeRedeem(params: SubmitStakeRedeemParamsV5): Promise< APIResponseV3WithTime<{ orderId: string; orderLinkId: string; }> > { return this.postPrivate('/v5/earn/place-order', params); ⋮---- /** * Get Stake/Redeem Order History * * INFO: API key needs "Earn" permission * * Note: * - For category = OnChain, either orderId or orderLinkId is required * - If both are passed, make sure they're matched, otherwise returning empty result * - Supports batch query with productId, startTime, endTime, limit, cursor */ getEarnOrderHistory(params: GetEarnOrderHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: EarnOrderHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/earn/order', params); ⋮---- /** * Get Staked Position * * INFO: API key needs "Earn" permission * * Note: Fully redeemed position is also returned in the response */ getEarnPosition(params: GetEarnPositionParamsV5): Promise< APIResponseV3WithTime<{ list: EarnPositionV5[]; }> > { return this.getPrivate('/v5/earn/position', params); ⋮---- /** * Get Yield History * * INFO: API key needs "Earn" permission */ getEarnYieldHistory(params: GetEarnYieldHistoryParamsV5): Promise< APIResponseV3WithTime<{ yield: EarnYieldHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/earn/yield', params); ⋮---- /** * Get Hourly Yield History * * INFO: API key needs "Earn" permission */ getEarnHourlyYieldHistory(params: GetEarnHourlyYieldHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: EarnHourlyYieldHistoryV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/earn/hourly-yield', params); ⋮---- /** * ****** RFQ APIs * */ ⋮---- /** * Create RFQ * Create a new request for quote (RFQ) to specified counterparties */ createRFQ( params: CreateRFQParamsV5, ): Promise> ⋮---- /** * Get RFQ Configuration * Query the information of the quoting party that can participate in the transaction * and your own deskCode and other configuration information */ getRFQConfig(): Promise> ⋮---- /** * Cancel RFQ * Cancel your inquiry * Pass at least one rfqId or rfqLinkId */ cancelRFQ( params: CancelRFQParamsV5, ): Promise> ⋮---- /** * Cancel All RFQ * Cancel all your inquiry forms */ cancelAllRFQ(): Promise> ⋮---- /** * Create Quote * Allow the quotation party specified in the inquiry form to quote * Pass at least one quoteBuyList and quoteSellList */ createRFQQuote( params: CreateRFQQuoteParamsV5, ): Promise> ⋮---- /** * Execute Quote * Execute quotes, only for the creator of the inquiry form * Need to view the execution result through the /v5/rfq/blocktrade-list interface */ executeRFQQuote( params: ExecuteRFQQuoteParamsV5, ): Promise> ⋮---- /** * Cancel Quote * Cancel a quotation * Pass at least one quoteId, rfqId, and quoteLinkId */ cancelRFQQuote( params: CancelRFQQuoteParamsV5, ): Promise> ⋮---- /** * Cancel All Quotes * Cancel all quotations */ cancelAllRFQQuotes(): Promise< APIResponseV3WithTime<{ data: CancelRFQQuoteItemV5[]; // Array of cancellation results }> > { return this.postPrivate('/v5/rfq/cancel-all-quotes'); ⋮---- data: CancelRFQQuoteItemV5[]; // Array of cancellation results ⋮---- /** * Get Real-time RFQ Information * Obtain the inquiry information sent or received by the user, query from rfq-engine without delay * Pass both rfqId and rfqLinkId, rfqId shall prevail * Sort in reverse order according to the creation time of rfq and return it */ getRFQRealtimeInfo( params?: GetRFQRealtimeParamsV5, ): Promise> ⋮---- /** * Get Historical RFQ Information * Obtain the information of the inquiry form sent or received by the user, query from the database * Pass both rfqId and rfqLinkId, rfqId shall prevail * Sort in reverse order according to the creation time of rfq and return it */ getRFQHistory( params?: GetRFQListParamsV5, ): Promise> ⋮---- /** * Get Real-time Quote Information * Obtain quotation information sent or received by users, query from rfq-engine without delay * Pass quoteId and quoteLinkId, quoteId shall prevail * Pass both rfqId and rfqLinkId, rfqId shall prevail * Sort in reverse order according to the creation time of the quotation * Return all non-final quotes */ getRFQRealtimeQuote(params?: GetRFQQuoteRealtimeParamsV5): Promise< APIResponseV3WithTime<{ list: RFQQuoteItemV5[]; }> > { return this.getPrivate('/v5/rfq/quote-realtime', params); ⋮---- /** * Get Historical Quote Information * Obtain the quotation information sent or received by the user, query from the database * Pass quoteId and quoteLinkId, quoteId shall prevail * Pass both rfqId and rfqLinkId, rfqId shall prevail * Sort in reverse order according to the creation time of the quotation */ getRFQHistoryQuote(params?: GetRFQHistoryParamsV5): Promise< APIResponseV3WithTime<{ cursor: string; // Page turning mark list: RFQQuoteItemV5[]; // Array of quote items }> > { return this.getPrivate('/v5/rfq/quote-list', params); ⋮---- cursor: string; // Page turning mark list: RFQQuoteItemV5[]; // Array of quote items ⋮---- /** * Get Trade Information * Obtain transaction information executed by the user */ getRFQTrades(params?: GetRFQTradeListParamsV5): Promise< APIResponseV3WithTime<{ cursor: string; // Page turning mark list: RFQTradeV5[]; // Array of trade items }> > { return this.getPrivate('/v5/rfq/trade-list', params); ⋮---- cursor: string; // Page turning mark list: RFQTradeV5[]; // Array of trade items ⋮---- /** * Get RFQ Public Transaction Data * Get the recently executed RFQ successfullys */ getRFQPublicTrades(params?: GetRFQPublicTradesParamsV5): Promise< APIResponseV3WithTime<{ cursor: string; // Page turning mark list: RFQPublicTradeV5[]; // Array of public trade items }> > { return this.getPrivate('/v5/rfq/public-trades', params); ⋮---- cursor: string; // Page turning mark list: RFQPublicTradeV5[]; // Array of public trade items ⋮---- /** * ****** P2P TRADING * */ ⋮---- /** * * General P2P */ ⋮---- /** * Get coin balance of all account types under the master account, and sub account. * * Note: this field is mandatory for accountType=UNIFIED, and supports up to 10 coins each request */ getP2PAccountCoinsBalance( params: GetP2PAccountCoinsBalanceParamsV5, ): Promise> ⋮---- /** * * Advertisement P2P */ ⋮---- /** * Get market online ads list */ getP2POnlineAds( params: GetP2POnlineAdsParamsV5, ): Promise> ⋮---- /** * Post new P2P advertisement */ createP2PAd( params: CreateP2PAdParamsV5, ): Promise> ⋮---- /** * Cancel P2P advertisement */ cancelP2PAd(params: { itemId: string }): Promise< APIResponseV3WithTime<{ securityRiskToken: string; riskTokenType: string; riskVersion: string; needSecurityRisk: boolean; }> > { return this.postPrivate('/v5/p2p/item/cancel', params); ⋮---- /** * Update or relist P2P advertisement */ updateP2PAd( params: UpdateP2PAdParamsV5, ): Promise> ⋮---- /** * Get personal P2P ads list * */ getP2PPersonalAds( params: GetP2PPersonalAdsParamsV5, ): Promise> ⋮---- /** * Get P2P ad details */ getP2PAdDetail(params: { itemId: string; }): Promise> ⋮---- /** * * Orders P2P */ ⋮---- /** * Get all P2P orders * */ getP2POrders( params: GetP2POrdersParamsV5, ): Promise> ⋮---- /** * Get P2P order details * */ getP2POrderDetail(params: { orderId: string; }): Promise> ⋮---- /** * Get pending P2P orders */ getP2PPendingOrders( params: GetP2PPendingOrdersParamsV5, ): Promise> ⋮---- /** * Mark P2P order as paid */ markP2POrderAsPaid( params: MarkP2POrderAsPaidParamsV5, ): Promise> ⋮---- /** * Release digital assets in a P2P order */ releaseP2POrder(params: { orderId: string; }): Promise> ⋮---- /** * Send chat message in a P2P order */ sendP2POrderMessage( params: SendP2POrderMessageParamsV5, ): Promise> ⋮---- /** * Upload chat file for P2P order (Node.js only) * * Note: You must provide a Buffer. To upload from a file path, read it into a Buffer first: * ```typescript * import fs from 'fs'; * const buffer = fs.readFileSync('./path/to/file.png'); * await client.uploadP2PChatFile({ fileBuffer: buffer, fileName: 'file.png' }); * ``` * * Supported file types: jpg, png, jpeg, pdf, mp4 */ uploadP2PChatFile(params: { fileBuffer: Buffer; fileName: string; // Required: the filename (used for MIME type detection) }): Promise< APIResponseV3WithTime<{ url: string; type: string; uploadId: string | null; }> > { return this.postPrivateFile('/v5/p2p/oss/upload_file', params); ⋮---- fileName: string; // Required: the filename (used for MIME type detection) ⋮---- /** * Get chat messages in a P2P order */ getP2POrderMessages( params: GetP2POrderMessagesParamsV5, ): Promise> ⋮---- /** * * User P2P */ ⋮---- /** * Get P2P user account information */ getP2PUserInfo(): Promise> ⋮---- /** * Get counterparty user information in a P2P order */ getP2PCounterpartyUserInfo( params: GetP2PCounterpartyUserInfoParamsV5, ): Promise> ⋮---- /** * Get user payment information */ getP2PUserPayments(): Promise> ⋮---- /** * ****** API Rate Limit Management APIs * */ ⋮---- /** * Set API rate limit * * API rate limit: 50 req per second * * INFO * - If UID requesting this endpoint is a master account, uids in the input parameter must be subaccounts of the master account. * - If UID requesting this endpoint is not a master account, uids in the input parameter must be the UID requesting this endpoint * - UID requesting this endpoint must be an institutional user. */ setApiRateLimit(params: { list: { uids: string; bizType: string; rate: number; }[]; }): Promise< APIResponseV3WithTime<{ result: { uids: string; bizType: string; rate: number; success: boolean; msg: string; }[]; }> > { return this.postPrivate('/v5/apilimit/set', params); ⋮---- /** * Query API rate limit * * API rate limit: 50 req per second * * INFO * - A master account can query api rate limit of its own and subaccounts. * - A subaccount can only query its own api rate limit. */ queryApiRateLimit(params: { uids: string }): Promise< APIResponseV3WithTime<{ list: { uids: string; bizType: string; rate: number; }[]; }> > { return this.getPrivate('/v5/apilimit/query', params); ⋮---- /** * Get Rate Limit Cap * Get your institution's total rate limit usage and cap, across the board. * * API rate limit: 50 req per second * Main UIDs or sub UIDs can query this endpoint, but a main UID can only see the rate limits of subs below it. */ getRateLimitCap(): Promise< APIResponseV3WithTime<{ list: { bizType: string; totalRate: number; insCap: number; uidCap: number; }[]; }> > { return this.getPrivate('/v5/apilimit/query-cap'); ⋮---- /** * Get All Rate Limits * Query for all your UID-level rate limits, including all master accounts and subaccounts. * * API rate limit: 50 req per second */ getAllRateLimits(params?: { limit?: string; cursor?: string; uids?: string; }): Promise< APIResponseV3WithTime<{ list: { uids: string; bizType: string; rate: number; }[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/apilimit/query-all', params); ================================================================ End of Codebase ================================================================