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/, 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/ apidoc/ V5/ Account/ batch-set-collateral-coin.js get-account-info.js get-borrow-history.js get-coin-greeks.js get-collateral-info.js get-dcp-info.js get-fee-rate.js get-mmp-state.js get-smp-group-id.js get-transaction-log-classic.js get-transaction-log-UTA.js get-transferable-amount-unified.js get-wallet-balance.js README.md repay-liability.js reset-mmp.js set-collateral-coin.js set-limit-price-behaviour.js set-margin-mode.js set-mmp.js set-spot-hedging.js upgrade-to-unified-account.js Affiliate/ get-affiliate-user-info.js get-affiliate-user-list.js Asset/ cancel-withdrawal.js confirm-convert-quote.js create-internal-transfer.js create-universal-transfer.js enable-universal-transfer-for-sub-uid.js get-all-coins-balance.js get-allowed-deposit-coin-info.js get-asset-info-spot.js get-coin-exchange-records.js get-coin-info.js get-convert-coins.js get-convert-history.js get-convert-status.js get-delivery-record.js get-deposit-records.js get-exchange-entity-list.js get-internal-deposit-records.js get-internal-transfer-records.js get-master-deposit-address.js get-single-coin-balance.js get-sub-deposit-address.js get-sub-deposit-records.js get-sub-uid.js get-transferable-coin.js get-universal-transfer-records.js get-usdc-session-settlement.js get-withdrawable-amount.js get-withdrawal-records.js README.md request-convert-quote.js set-deposit-account.js withdraw.js Broker/ get-exchange-broker-account-info.js get-exchange-broker-earning.js get-subaccount-deposit-records.js issue-voucher.js query-issued-voucher.js query-voucher-spec.js Crypto-Loan-Legacy/ adjust-collateral-amount.js borrow.js get-account-borrow-collateral-limit.js get-borrowable-coins.js get-collateral-coins.js get-completed-loan-order-history.js get-loan-LTV-adjustment-history.js get-max-allowed-reduction-collateral-amount.js get-repayment-transaction-history.js get-unpaid-loan-orders.js repay.js Crypto-Loan-New/ Fixed-Loan/ cancel-borrow-order.js cancel-supply-order.js create-borrow-order.js create-supply-order.js get-borrow-contract-info.js get-borrow-order-info.js get-borrow-order-quote.js get-repayment-history.js get-supply-contract-info.js get-supply-order-info.js get-supply-order-quote.js repay.js Flexible-Loan/ borrow.js get-borrow-history.js get-ongoing-flexible-loans.js get-repayment-history.js repay.ts adjust-collateral-amount.js get-borrowable-coins.js get-collateral-adjustment-history.js get-collateral-coins.js get-crypto-loan-position.js get-max-collateral-amount.js Earn/ get-product-info.js get-stake-redeem-order-history.js get-staked-position.js stake-redeem.js Institutional-Loan/ bind-or-unbind-uid.js get-loan-orders.js get-LTV.js get-margin-coin-info.js get-product-info.js get-repayment-orders.js Market/ get-Bybit-server-time.js get-delivery-price.js get-funding-rate-history.js get-historical-volatility.js get-instruments-info.js get-insurance.js get-kline-index-price.js get-kline-mark-price.js get-kline-premium-index-price.js get-kline.js get-long-short-ratio.js get-open-interest.js get-order-price-limit.js get-orderbook.js get-public-trading-history.js get-risk-limit.js get-tickers.js README.md P2P/ get-account-information.js get-ad-detail.js get-all-orders.js get-chat-message.js get-coin-balance.js get-counterparty-user-info.js get-market-online-ads-list.js get-my-ads-list.js get-order-detail.js get-pending-orders.js get-user-payment.js mark-order-as-paid.js post-new-ad.js release-digital-asset.js remove-my-ad.js send-chat-message.js update-relist-my-ad.js upload-chat-file.js Position/ add-or-reduce-margin.js confirm-new-risk-limit.js get-closed-options-positions.js get-closed-pnl.js get-execution.js get-move-position-history.js get-position-info.js move-position.js README.md set-auto-add-margin.js set-leverage.js set-risk-limit.js set-tpsl-mode.js set-trading-stop.js switch-cross-isolated-margin.js switch-position-mode.js Preupgrade/ get-preupgrade-closed-pnl.js get-preupgrade-option-delivery-record.js get-preupgrade-order-history.js get-preupgrade-trade-history.js get-preupgrade-transaction-log.js get-preupgrade-USDC-session-settlement.js Spot-Leverage-Token/ get-leverage-token-info.js get-leveraged-token-market.js get-purchase-redemption-records.js purchase.js README.md redeem.js Spot-Margin-Trade-(Normal)/ borrow.js get-borrow-order-detail.js get-borrowable-coin-info.js get-interest-and-quota.js get-loan-account-info.js get-margin-coin-info.js get-repayment-order-detail.js README.md repay.js toggle-margin-trade-normal.js Spot-Margin-Trade-(UTA)/ get-historical-interest-rate.js get-status-and-leverage.js get-vip-margin-data.js README.md set-leverage.js toggle-margin-trade.js Spread-Trading/ amend-spread-order.js cancel-all-spread-orders.js cancel-spread-order.js create-spread-order.js get-spread-instruments-info.js get-spread-open-orders.js get-spread-order-history.js get-spread-orderbook.js get-spread-tickers.js get-spread-trade-history.js Trade/ amend-order.js batch-amend-order.js batch-cancel-order.js batch-place-order.js cancel-all-orders.js cancel-order.js confirm-new-risk-limit.js get-move-position-history.js get-open-orders.js get-order-history.js get-spot-borrow-quota.js move-position.js place-order.js pre-check-order.js README.md set-dcp.js User/ create-sub-uid-api-key.js create-sub-uid.js delete-master-api-key.js delete-sub-api-key.js delete-sub-uid.js freeze-sub-uid.js get-api-key-info.js get-sub-all-api-keys.js get-sub-uid-list-unlimited.js get-sub-uid-list.js get-uid-wallet-type.js modify-master-api-key.js modify-sub-api-key.js README.md README.md typescripttest.ts 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-private.ts rest-v5-proxies.ts rest-v5-proxies2.ts rest-v5-public.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-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-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/apidoc/V5/Account/batch-set-collateral-coin.js ================ const client = new RestClientV5({ ⋮---- .batchSetCollateralCoin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-account-info.js ================ const client = new RestClientV5({ ⋮---- .getAccountInfo() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-borrow-history.js ================ const client = new RestClientV5({ ⋮---- .getBorrowHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-coin-greeks.js ================ const client = new RestClientV5({ ⋮---- .getCoinGreeks('BTC') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-collateral-info.js ================ const client = new RestClientV5({ ⋮---- .getCollateralInfo('BTC') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-dcp-info.js ================ const client = new RestClientV5({ ⋮---- .getDCPInfo() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-fee-rate.js ================ const client = new RestClientV5({ ⋮---- .getFeeRate({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-mmp-state.js ================ const client = new RestClientV5({ ⋮---- .getMMPState('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-smp-group-id.js ================ const client = new RestClientV5({ ⋮---- .getSMPGroup() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-transaction-log-classic.js ================ const client = new RestClientV5({ ⋮---- .getClassicTransactionLogs({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-transaction-log-UTA.js ================ const client = new RestClientV5({ ⋮---- .getTransactionLog({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-transferable-amount-unified.js ================ const client = new RestClientV5({ ⋮---- .getTransferableAmount({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/get-wallet-balance.js ================ const client = new RestClientV5({ ⋮---- .getWalletBalance({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/README.md ================ # V5 - REST - Account https://bybit-exchange.github.io/docs/v5/account/wallet-balance ================ File: examples/apidoc/V5/Account/repay-liability.js ================ const client = new RestClientV5({ ⋮---- .repayLiability({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/reset-mmp.js ================ const client = new RestClientV5({ ⋮---- .resetMMP('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/set-collateral-coin.js ================ const client = new RestClientV5({ ⋮---- .setCollateralCoin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/set-margin-mode.js ================ const client = new RestClientV5({ ⋮---- .setMarginMode('PORTFOLIO_MARGIN') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/set-mmp.js ================ const client = new RestClientV5({ ⋮---- .setMMP({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/set-spot-hedging.js ================ const client = new RestClientV5({ ⋮---- .setSpotHedging({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Account/upgrade-to-unified-account.js ================ const client = new RestClientV5({ ⋮---- .upgradeToUnifiedAccount() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Affiliate/get-affiliate-user-info.js ================ // https://api.bybit.com/v5/broker/account-info ⋮---- const client = new RestClientV5({ ⋮---- .getAffiliateUserInfo({ uid: '1234567890' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Affiliate/get-affiliate-user-list.js ================ // https://api.bybit.com/v5/broker/account-info ⋮---- const client = new RestClientV5({ ⋮---- .getAffiliateUserList() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/cancel-withdrawal.js ================ const client = new RestClientV5({ ⋮---- .cancelWithdrawal('10197') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/confirm-convert-quote.js ================ const client = new RestClientV5({ ⋮---- .confirmConvertQuote({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/create-internal-transfer.js ================ const client = new RestClientV5({ ⋮---- .createInternalTransfer( ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/create-universal-transfer.js ================ const client = new RestClientV5({ ⋮---- .createUniversalTransfer({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/enable-universal-transfer-for-sub-uid.js ================ const client = new RestClientV5({ ⋮---- .enableUniversalTransferForSubUIDs(['554117', '592324', '592334']) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-all-coins-balance.js ================ const client = new RestClientV5({ ⋮---- .getAllCoinsBalance({ accountType: 'FUND', coin: 'USDC' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-allowed-deposit-coin-info.js ================ const client = new RestClientV5({ ⋮---- .getAllowedDepositCoinInfo({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-asset-info-spot.js ================ const client = new RestClientV5({ ⋮---- .getAssetInfo({ accountType: 'FUND', coin: 'USDC' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-coin-exchange-records.js ================ const client = new RestClientV5({ ⋮---- .getCoinExchangeRecords({ limit: 10 }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-coin-info.js ================ const client = new RestClientV5({ ⋮---- .getCoinInfo('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-convert-coins.js ================ const client = new RestClientV5({ ⋮---- .getConvertCoins({ accountType: 'eb_convert_spot' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-convert-history.js ================ const client = new RestClientV5({ ⋮---- .getConvertHistory() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-convert-status.js ================ const client = new RestClientV5({ ⋮---- .getConvertStatus({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-delivery-record.js ================ const client = new RestClientV5({ ⋮---- .getDeliveryRecord({ category: 'option', expDate: '29DEC22' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-deposit-records.js ================ const client = new RestClientV5({ ⋮---- .getDepositRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-exchange-entity-list.js ================ // https://api.bybit.com/v5/asset/withdraw/vasp/list ⋮---- const client = new RestClientV5({ ⋮---- .getExchangeEntities() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-internal-deposit-records.js ================ const client = new RestClientV5({ ⋮---- .getInternalDepositRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-internal-transfer-records.js ================ const client = new RestClientV5({ ⋮---- .getInternalTransferRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-master-deposit-address.js ================ const client = new RestClientV5({ ⋮---- .getMasterDepositAddress('USDT', 'ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-single-coin-balance.js ================ const client = new RestClientV5({ ⋮---- .getCoinBalance({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-sub-deposit-address.js ================ const client = new RestClientV5({ ⋮---- .getSubDepositAddress('USDT', 'TRX', '592334') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-sub-deposit-records.js ================ const client = new RestClientV5({ ⋮---- .getSubAccountDepositRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-sub-uid.js ================ const client = new RestClientV5({ ⋮---- .getSubUID() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-transferable-coin.js ================ const client = new RestClientV5({ ⋮---- .getTransferableCoinList('UNIFIED', 'CONTRACT') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-universal-transfer-records.js ================ const client = new RestClientV5({ ⋮---- .getUniversalTransferRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-usdc-session-settlement.js ================ const client = new RestClientV5({ ⋮---- .getSettlementRecords({ category: 'linear' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-withdrawable-amount.js ================ const client = new RestClientV5({ ⋮---- .getWithdrawableAmount({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/get-withdrawal-records.js ================ const client = new RestClientV5({ ⋮---- .getWithdrawalRecords({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/README.md ================ # V5 - REST - Asset https://bybit-exchange.github.io/docs/v5/asset/exchange ================ File: examples/apidoc/V5/Asset/request-convert-quote.js ================ const client = new RestClientV5({ ⋮---- .requestConvertQuote({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/set-deposit-account.js ================ const client = new RestClientV5({ ⋮---- .setDepositAccount({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Asset/withdraw.js ================ const client = new RestClientV5({ ⋮---- .submitWithdrawal({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/get-exchange-broker-account-info.js ================ // https://api.bybit.com/v5/broker/account-info ⋮---- const client = new RestClientV5({ ⋮---- .getExchangeBrokerAccountInfo() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/get-exchange-broker-earning.js ================ // https://api.bybit.com/v5/broker/earnings-info ⋮---- const client = new RestClientV5({ ⋮---- .getExchangeBrokerEarnings({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/get-subaccount-deposit-records.js ================ // https://api.bybit.com/v5/broker/asset/query-sub-member-deposit-record ⋮---- const client = new RestClientV5({ ⋮---- .getBrokerSubAccountDeposits({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/issue-voucher.js ================ const client = new RestClientV5({ ⋮---- .issueBrokerVoucher({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/query-issued-voucher.js ================ const client = new RestClientV5({ ⋮---- .getBrokerVoucherSpec({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Broker/query-voucher-spec.js ================ const client = new RestClientV5({ ⋮---- .getBrokerIssuedVoucher({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Earn/get-product-info.js ================ const client = new RestClientV5({ ⋮---- .getEarnProduct({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Earn/get-stake-redeem-order-history.js ================ const client = new RestClientV5({ ⋮---- .getEarnOrderHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Earn/get-staked-position.js ================ const client = new RestClientV5({ ⋮---- .getEarnPosition({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Earn/stake-redeem.js ================ const client = new RestClientV5({ ⋮---- .submitStakeRedeem({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/bind-or-unbind-uid.js ================ // https://api.bybit.com/v5/ins-loan/association-uid ⋮---- const client = new RestClientV5({ ⋮---- .bindOrUnbindUID({ ⋮---- operate: '0', // 0 for bind, 1 for unbind ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/get-loan-orders.js ================ // https://api.bybit.com/v5/ins-loan/loan-order ⋮---- const client = new RestClientV5({ ⋮---- .getInstitutionalLendingLoanOrders({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/get-LTV.js ================ // https://api.bybit.com/v5/ins-loan/ltv-convert ⋮---- const client = new RestClientV5({ ⋮---- .getInstitutionalLendingLTVWithLadderConversionRate() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/get-margin-coin-info.js ================ // https://api.bybit.com/v5/ins-loan/ensure-tokens-convert ⋮---- const client = new RestClientV5({ ⋮---- .getInstitutionalLendingMarginCoinInfoWithConversionRate({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/get-product-info.js ================ // https://api.bybit.com/v5/ins-loan/product-infos ⋮---- const client = new RestClientV5({ ⋮---- .getInstitutionalLendingProductInfo({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Institutional-Loan/get-repayment-orders.js ================ // https://api.bybit.com/v5/ins-loan/repaid-history ⋮---- const client = new RestClientV5({ ⋮---- .getInstitutionalLendingRepayOrders({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-Bybit-server-time.js ================ const client = new RestClientV5({ ⋮---- .getServerTime() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-delivery-price.js ================ const client = new RestClientV5({ ⋮---- .getDeliveryPrice({ category: 'option', symbol: 'ETH-26DEC22-1400-C' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-funding-rate-history.js ================ const client = new RestClientV5({ ⋮---- .getFundingRateHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-historical-volatility.js ================ const client = new RestClientV5({ ⋮---- .getHistoricalVolatility({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-instruments-info.js ================ const client = new RestClientV5({ ⋮---- // linear ⋮---- .getInstrumentsInfo({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ⋮---- // option ⋮---- // spot ================ File: examples/apidoc/V5/Market/get-insurance.js ================ const client = new RestClientV5({ ⋮---- .getInsurance({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-kline-index-price.js ================ const client = new RestClientV5({ ⋮---- .getIndexPriceKline({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-kline-mark-price.js ================ const client = new RestClientV5({ ⋮---- .getMarkPriceKline({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-kline-premium-index-price.js ================ const client = new RestClientV5({ ⋮---- .getPremiumIndexPriceKline({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-kline.js ================ const client = new RestClientV5({ ⋮---- .getKline({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-long-short-ratio.js ================ const client = new RestClientV5({ ⋮---- .getLongShortRatio({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-open-interest.js ================ const client = new RestClientV5({ ⋮---- .getOpenInterest({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-orderbook.js ================ const client = new RestClientV5({ ⋮---- .getOrderbook({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-public-trading-history.js ================ const client = new RestClientV5({ ⋮---- .getPublicTradingHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-risk-limit.js ================ const client = new RestClientV5({ ⋮---- .getRiskLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Market/get-tickers.js ================ const client = new RestClientV5({ ⋮---- // inverse ⋮---- .getTickers({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ⋮---- // option ⋮---- // spot ================ File: examples/apidoc/V5/Market/README.md ================ # V5 - REST - Market https://bybit-exchange.github.io/docs/v5/market/kline ================ File: examples/apidoc/V5/Position/add-or-reduce-margin.js ================ const client = new RestClientV5({ ⋮---- .addOrReduceMargin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/confirm-new-risk-limit.js ================ const client = new RestClientV5({ ⋮---- .confirmNewRiskLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/get-closed-pnl.js ================ const client = new RestClientV5({ ⋮---- .getClosedPnL({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/get-execution.js ================ const client = new RestClientV5({ ⋮---- .addOrReduceMargin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/get-move-position-history.js ================ const client = new RestClientV5({ ⋮---- .getMovePositionHistory() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/get-position-info.js ================ const client = new RestClientV5({ ⋮---- .getPositionInfo({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/move-position.js ================ const client = new RestClientV5({ ⋮---- .movePosition({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/README.md ================ # V5 - REST - Position https://bybit-exchange.github.io/docs/v5/position ================ File: examples/apidoc/V5/Position/set-auto-add-margin.js ================ const client = new RestClientV5({ ⋮---- .setAutoAddMargin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/set-leverage.js ================ const client = new RestClientV5({ ⋮---- .setLeverage({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/set-risk-limit.js ================ const client = new RestClientV5({ ⋮---- .setRiskLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/set-tpsl-mode.js ================ const client = new RestClientV5({ ⋮---- .setTPSLMode({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/set-trading-stop.js ================ const client = new RestClientV5({ ⋮---- .setTradingStop({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/switch-cross-isolated-margin.js ================ const client = new RestClientV5({ ⋮---- .switchIsolatedMargin({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/switch-position-mode.js ================ const client = new RestClientV5({ ⋮---- .switchPositionMode({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-closed-pnl.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeClosedPnl({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-option-delivery-record.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeOptionDeliveryRecord({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-order-history.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeOrderHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-trade-history.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeTradeHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-transaction-log.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeTransactionLog({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Preupgrade/get-preupgrade-USDC-session-settlement.js ================ const client = new RestClientV5({ ⋮---- .getPreUpgradeUSDCSessionSettlement({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Leverage-Token/get-leverage-token-info.js ================ const client = new RestClientV5({ ⋮---- .getLeveragedTokenInfo('BTC3L') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Leverage-Token/get-leveraged-token-market.js ================ const client = new RestClientV5({ ⋮---- .getLeveragedTokenMarket('BTC3L') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Leverage-Token/get-purchase-redemption-records.js ================ const client = new RestClientV5({ ⋮---- .getSpotLeveragedTokenOrderHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Leverage-Token/purchase.js ================ const client = new RestClientV5({ ⋮---- .purchaseSpotLeveragedToken({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Leverage-Token/README.md ================ # V5 - REST - Spot Leverage Token https://bybit-exchange.github.io/docs/v5/lt/leverage-token-info ================ File: examples/apidoc/V5/Spot-Leverage-Token/redeem.js ================ const client = new RestClientV5({ ⋮---- .redeemSpotLeveragedToken({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/borrow.js ================ const client = new RestClientV5({ ⋮---- .spotMarginBorrow({ coin: 'ETH', qty: '10' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-borrow-order-detail.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginBorrowOrderDetail({ coin: 'ETH', limit: 1, status: 2 }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-borrowable-coin-info.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginBorrowableCoinInfo('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-interest-and-quota.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginInterestAndQuota('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-loan-account-info.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginLoanAccountInfo() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-margin-coin-info.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginCoinInfo('ETH') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/get-repayment-order-detail.js ================ const client = new RestClientV5({ ⋮---- .getSpotMarginRepaymentOrderDetail({ coin: 'ETH', limit: 1 }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/README.md ================ # V5 - REST - Spot Margin Trade (Normal) https://bybit-exchange.github.io/docs/v5/spot-margin-normal/margin-data ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/repay.js ================ const client = new RestClientV5({ ⋮---- .spotMarginRepay({ coin: 'ETH', completeRepayment: 1 }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(Normal)/toggle-margin-trade-normal.js ================ const client = new RestClientV5({ ⋮---- .toggleSpotCrossMarginTrade({ switch: 0 }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-historical-interest-rate.js ================ const client = new RestClientV5({ ⋮---- .getHistoricalInterestRate({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-status-and-leverage.js ================ // https://api.bybit.com/v5/spot-margin-trade/state ⋮---- const client = new RestClientV5({ ⋮---- .getSpotMarginState() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/get-vip-margin-data.js ================ // https://api.bybit.com/v5/spot-margin-trade/data ⋮---- const client = new RestClientV5({ ⋮---- .getVIPMarginData({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/README.md ================ # V5 - REST - Spot Margin Trade (UTA) https://bybit-exchange.github.io/docs/v5/spot-margin-uta/switch-mode ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/set-leverage.js ================ const client = new RestClientV5({ ⋮---- .setSpotMarginLeverage('4') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spot-Margin-Trade-(UTA)/toggle-margin-trade.js ================ const client = new RestClientV5({ ⋮---- .toggleSpotMarginTrade('0') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/amend-order.js ================ const client = new RestClientV5({ ⋮---- .submitOrder({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/batch-amend-order.js ================ const client = new RestClientV5({ ⋮---- .batchAmendOrders('option', [ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/batch-cancel-order.js ================ const client = new RestClientV5({ ⋮---- .batchCancelOrders('option', [ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/batch-place-order.js ================ const client = new RestClientV5({ ⋮---- .batchSubmitOrders('option', [ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/cancel-all-orders.js ================ const client = new RestClientV5({ ⋮---- .cancelAllOrders({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/cancel-order.js ================ const client = new RestClientV5({ ⋮---- .cancelOrder({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/confirm-new-risk-limit.js ================ const client = new RestClientV5({ ⋮---- .confirmNewRiskLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/get-move-position-history.js ================ const client = new RestClientV5({ ⋮---- .getMovePositionHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/get-open-orders.js ================ const client = new RestClientV5({ ⋮---- .getActiveOrders({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/get-order-history.js ================ const client = new RestClientV5({ ⋮---- .getHistoricOrders({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/get-spot-borrow-quota.js ================ const client = new RestClientV5({ ⋮---- .getSpotBorrowCheck('BTCUSDT', 'Buy') .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/move-position.js ================ const client = new RestClientV5({ ⋮---- .movePosition({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/place-order.js ================ const client = new RestClientV5({ ⋮---- // Submit a market order ⋮---- .submitOrder({ ⋮---- .then((response) => { console.log('Market order result', response); ⋮---- .catch((error) => { console.error('Market order error', error); ⋮---- // Submit a limit order ⋮---- console.log('Limit order result', response); ⋮---- console.error('Limit order error', error); ================ File: examples/apidoc/V5/Trade/README.md ================ # V5 - REST - Trade https://bybit-exchange.github.io/docs/v5/order/create-order ================ File: examples/apidoc/V5/Trade/set-dcp.js ================ const client = new RestClientV5({ ⋮---- .setDisconnectCancelAllWindow('option', 40) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/create-sub-uid-api-key.js ================ const client = new RestClientV5({ ⋮---- .createSubUIDAPIKey({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/create-sub-uid.js ================ const client = new RestClientV5({ ⋮---- .createSubMember({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/delete-master-api-key.js ================ const client = new RestClientV5({ ⋮---- .deleteMasterApiKey() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/delete-sub-api-key.js ================ const client = new RestClientV5({ ⋮---- .deleteSubApiKey() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/delete-sub-uid.js ================ // https://api.bybit.com/v5/user/del-submember ⋮---- const client = new RestClientV5({ ⋮---- .deleteSubMember({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/freeze-sub-uid.js ================ const client = new RestClientV5({ ⋮---- .setSubUIDFrozenState(53888001, 1) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/get-api-key-info.js ================ const client = new RestClientV5({ ⋮---- .getQueryApiKey() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/get-sub-all-api-keys.js ================ // https://api.bybit.com/v5/user/sub-apikeys ⋮---- const client = new RestClientV5({ ⋮---- .getSubAccountAllApiKeys({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/get-sub-uid-list-unlimited.js ================ const client = new RestClientV5({ ⋮---- .getSubUIDListUnlimited() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/get-sub-uid-list.js ================ const client = new RestClientV5({ ⋮---- .getSubUIDList() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/get-uid-wallet-type.js ================ // https://api.bybit.com/v5/user/get-member-type ⋮---- const client = new RestClientV5({ ⋮---- .getUIDWalletType({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/modify-master-api-key.js ================ const client = new RestClientV5({ ⋮---- .updateMasterApiKey({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/modify-sub-api-key.js ================ const client = new RestClientV5({ ⋮---- .updateSubApiKey({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/User/README.md ================ # V5 - REST - User https://bybit-exchange.github.io/docs/v5/user/create-subuid ================ File: examples/apidoc/README.md ================ # API Doc Examples These are per-endpoint JavaScript examples also found in Bybit's API documentation website, demonstrating how to interact with each endpoint with the Node.js SDK. ================ File: examples/apidoc/typescripttest.ts ================ import { RestClientV5 } from '../../src'; ================ 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: 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-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-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; } ================ 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; } ================ 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-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; } ⋮---- 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/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/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) { ⋮---- path: path.resolve(__dirname, '../dist'), ⋮---- // 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'. ⋮---- new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) ⋮---- new BundleAnalyzerPlugin({ ⋮---- module.exports = generateConfig('bybitapi'); ================ 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/apidoc/V5/Account/set-limit-price-behaviour.js ================ const client = new RestClientV5({ ⋮---- .setLimitPriceAction({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/adjust-collateral-amount.js ================ const client = new RestClientV5({ ⋮---- .adjustCollateralAmount({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/borrow.js ================ const client = new RestClientV5({ ⋮---- .borrowCryptoLoan({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-account-borrow-collateral-limit.js ================ const client = new RestClientV5({ ⋮---- .getAccountBorrowCollateralLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-borrowable-coins.js ================ const client = new RestClientV5({ ⋮---- .getBorrowableCoins({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-collateral-coins.js ================ const client = new RestClientV5({ ⋮---- .getCollateralCoins({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-completed-loan-order-history.js ================ const client = new RestClientV5({ ⋮---- .getCompletedLoanOrderHistory({ orderId: '1794267532472646144' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-loan-LTV-adjustment-history.js ================ const client = new RestClientV5({ ⋮---- .getLoanLTVAdjustmentHistory({ adjustId: '1794271131730737664' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-max-allowed-reduction-collateral-amount.js ================ const client = new RestClientV5({ ⋮---- .getMaxAllowedReductionCollateralAmount({ orderId: '1794267532472646144' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-repayment-transaction-history.js ================ const client = new RestClientV5({ ⋮---- .getRepaymentHistory({ repayId: '1794271131730737664' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/get-unpaid-loan-orders.js ================ const client = new RestClientV5({ ⋮---- .getUnpaidLoanOrders({ orderId: '1793683005081680384' }) .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-Legacy/repay.js ================ const client = new RestClientV5({ ⋮---- .repayCryptoLoan({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/cancel-borrow-order.js ================ const client = new RestClientV5({ ⋮---- async function cancelBorrowOrder() { ⋮---- const response = await client.cancelBorrowOrderFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- cancelBorrowOrder(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/cancel-supply-order.js ================ const client = new RestClientV5({ ⋮---- async function cancelSupplyOrder() { ⋮---- const response = await client.cancelSupplyOrderFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- cancelSupplyOrder(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/create-borrow-order.js ================ const client = new RestClientV5({ ⋮---- async function createBorrowOrder() { ⋮---- const response = await client.createBorrowOrderFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- createBorrowOrder(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/create-supply-order.js ================ const client = new RestClientV5({ ⋮---- async function createSupplyOrder() { ⋮---- const response = await client.createSupplyOrderFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- createSupplyOrder(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-borrow-contract-info.js ================ const client = new RestClientV5({ ⋮---- async function getBorrowContractInfo() { ⋮---- const response = await client.getBorrowContractInfoFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getBorrowContractInfo(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-borrow-order-info.js ================ const client = new RestClientV5({ ⋮---- async function getBorrowOrderInfo() { ⋮---- const response = await client.getBorrowOrderInfoFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getBorrowOrderInfo(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-borrow-order-quote.js ================ const client = new RestClientV5({ ⋮---- async function getBorrowOrderQuote() { ⋮---- const response = await client.getBorrowOrderQuoteFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getBorrowOrderQuote(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-repayment-history.js ================ const client = new RestClientV5({ ⋮---- async function getRepaymentHistory() { ⋮---- const response = await client.getRepaymentHistoryFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getRepaymentHistory(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-supply-contract-info.js ================ const client = new RestClientV5({ ⋮---- async function getSupplyContractInfo() { ⋮---- const response = await client.getSupplyContractInfoFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getSupplyContractInfo(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-supply-order-info.js ================ const client = new RestClientV5({ ⋮---- async function getSupplyOrderInfo() { ⋮---- const response = await client.getSupplyOrderInfoFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getSupplyOrderInfo(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/get-supply-order-quote.js ================ const client = new RestClientV5({ ⋮---- async function getSupplyOrderQuote() { ⋮---- const response = await client.getSupplyOrderQuoteFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getSupplyOrderQuote(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Fixed-Loan/repay.js ================ const client = new RestClientV5({ ⋮---- async function repayFixed() { ⋮---- const response = await client.repayFixed({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- repayFixed(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/borrow.js ================ const client = new RestClientV5({ ⋮---- async function borrowFlexible() { ⋮---- const response = await client.borrowFlexible({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- borrowFlexible(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-borrow-history.js ================ const client = new RestClientV5({ ⋮---- async function getBorrowHistory() { ⋮---- const response = await client.getBorrowHistoryFlexible({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getBorrowHistory(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-ongoing-flexible-loans.js ================ const client = new RestClientV5({ ⋮---- async function getOngoingFlexibleLoans() { ⋮---- const response = await client.getOngoingFlexibleLoans({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getOngoingFlexibleLoans(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/get-repayment-history.js ================ const client = new RestClientV5({ ⋮---- async function getRepaymentHistory() { ⋮---- const response = await client.getRepaymentHistoryFlexible({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getRepaymentHistory(); ================ File: examples/apidoc/V5/Crypto-Loan-New/Flexible-Loan/repay.ts ================ import { RestClientV5 } from 'bybit-api'; ⋮---- async function repayFlexible() ================ File: examples/apidoc/V5/Crypto-Loan-New/adjust-collateral-amount.js ================ const client = new RestClientV5({ ⋮---- async function adjustCollateralAmount() { ⋮---- const response = await client.adjustCollateralAmountNew({ ⋮---- direction: '1', // 0: add collateral; 1: reduce collateral ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- adjustCollateralAmount(); ================ File: examples/apidoc/V5/Crypto-Loan-New/get-borrowable-coins.js ================ const client = new RestClientV5({ ⋮---- async function getBorrowableCoins() { ⋮---- const response = await client.getBorrowableCoinsNew({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getBorrowableCoins(); ================ File: examples/apidoc/V5/Crypto-Loan-New/get-collateral-adjustment-history.js ================ const client = new RestClientV5({ ⋮---- async function getCollateralAdjustmentHistory() { ⋮---- const response = await client.getCollateralAdjustmentHistoryNew({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getCollateralAdjustmentHistory(); ================ File: examples/apidoc/V5/Crypto-Loan-New/get-collateral-coins.js ================ const client = new RestClientV5({ ⋮---- async function getCollateralCoins() { ⋮---- const response = await client.getCollateralCoinsNew({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getCollateralCoins(); ================ File: examples/apidoc/V5/Crypto-Loan-New/get-crypto-loan-position.js ================ const client = new RestClientV5({ ⋮---- async function getCryptoLoanPosition() { ⋮---- const response = await client.getCryptoLoanPositionNew(); ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getCryptoLoanPosition(); ================ File: examples/apidoc/V5/Crypto-Loan-New/get-max-collateral-amount.js ================ const client = new RestClientV5({ ⋮---- async function getMaxCollateralAmount() { ⋮---- const response = await client.getMaxCollateralAmountNew({ ⋮---- console.log(response); ⋮---- console.error('Error:', error); ⋮---- getMaxCollateralAmount(); ================ File: examples/apidoc/V5/Market/get-order-price-limit.js ================ const client = new RestClientV5({ ⋮---- .getOrderPriceLimit({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/P2P/get-account-information.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Call the function ⋮---- .getP2PUserInfo() .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-ad-detail.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- itemId: '1898988222063644672', // Replace with your ad ID ⋮---- // Call the function ⋮---- .getP2PAdDetail(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-all-orders.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- status: null, // Optional: filter by order status beginTime: null, // Optional: filter by start time endTime: null, // Optional: filter by end time tokenId: null, // Optional: filter by token ID side: null, // Optional: filter by side (0: Buy, 1: Sell) page: 1, // Required: page number size: 1, // Required: rows per page ⋮---- // Call the function ⋮---- .getP2POrders(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-chat-message.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- orderId: '1898976123321221120', // Replace with your order ID size: '1', // Number of messages per page currentPage: '1', // Optional: current page number ⋮---- // Call the function ⋮---- .getP2POrderMessages(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-coin-balance.js ================ // Create a client const client = new RestClientV5({ ⋮---- // Get account coins balance ⋮---- .getP2PAccountCoinsBalance({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/P2P/get-counterparty-user-info.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- originalUid: '290118', // Replace with the counterparty user ID orderId: '1900004704665923584', // Replace with your order ID ⋮---- // Call the function ⋮---- .getP2PCounterpartyUserInfo(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-market-online-ads-list.js ================ // Create a client const client = new RestClientV5({ ⋮---- // Get market online ads list ⋮---- .getP2POnlineAds({ ⋮---- side: '0', // 0: buy; 1: sell ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/P2P/get-my-ads-list.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters for getting personal P2P ads ⋮---- itemId: '123456789', // Optional: Specific advertisement ID status: 1, // Optional: Advertisement status (1: active, 2: completed, 3: cancelled) side: 1, // Optional: 0: buy; 1: sell tokenId: 'USDT', // Optional: Token ID page: 1, // Optional: Page number size: 20, // Optional: Page size currencyId: 'USD' // Optional: Currency ID ⋮---- // Get personal P2P ads client.getP2PPersonalAds(params) .then(response => { console.log('Response:', response); ⋮---- .catch(error => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-order-detail.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- orderId: '1900004704665923584', // Replace with your order ID ⋮---- // Call the function ⋮---- .getP2POrderDetail(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-pending-orders.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- status: 10, // waiting for buy pay beginTime: '1741831397000', // Optional: filter by start time endTime: '1741831424861', // Optional: filter by end time tokenId: 'USDT', // Optional: filter by token side: [0, 1], // Optional: filter by side (0: Buy, 1: Sell) ⋮---- // Call the function ⋮---- .getP2PPendingOrders(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/get-user-payment.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Call the function ⋮---- .getP2PUserPayments() .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/mark-order-as-paid.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- orderId: '1899736339155943424', // Replace with your order ID paymentType: '14', // Payment method used paymentId: '7110', // Payment method ID used ⋮---- // Call the function ⋮---- .markP2POrderAsPaid(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/post-new-ad.js ================ // Create a client const client = new RestClientV5({ ⋮---- // Create new P2P advertisement ⋮---- .createP2PAd({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/P2P/release-digital-asset.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- orderId: '1899736339155943424', // Replace with your order ID ⋮---- // Call the function ⋮---- .releaseP2POrder(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/remove-my-ad.js ================ // Create a client const client = new RestClientV5({ ⋮---- // Cancel P2P advertisement ⋮---- .cancelP2PAd({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/P2P/send-chat-message.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Example parameters ⋮---- orderId: '1898976123321221120', // Replace with your order ID // Optional parameters: // msgUuid: 'your-message-uuid', // fileName: 'example.pdf' ⋮---- // Call the function ⋮---- .sendP2POrderMessage(params) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ File: examples/apidoc/V5/P2P/update-relist-my-ad.js ================ // Create a client const client = new RestClientV5({ ⋮---- // Update P2P advertisement ⋮---- .updateP2PAd({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Position/get-closed-options-positions.js ================ const client = new RestClientV5({ ⋮---- .getClosedOptionsPositions({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/amend-spread-order.js ================ const client = new RestClientV5({ ⋮---- .amendSpreadOrder({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/cancel-all-spread-orders.js ================ const client = new RestClientV5({ ⋮---- .cancelAllSpreadOrders() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/cancel-spread-order.js ================ const client = new RestClientV5({ ⋮---- .cancelSpreadOrder({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/create-spread-order.js ================ const client = new RestClientV5({ ⋮---- .submitSpreadOrder({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-instruments-info.js ================ const client = new RestClientV5({ ⋮---- .getSpreadInstrumentsInfo() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-open-orders.js ================ const client = new RestClientV5({ ⋮---- .getSpreadOpenOrders() .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-order-history.js ================ const client = new RestClientV5({ ⋮---- .getSpreadOrderHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-orderbook.js ================ const client = new RestClientV5({ ⋮---- .getSpreadOrderbook({ ⋮---- limit: 1, // Show 5 levels of depth ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-tickers.js ================ const client = new RestClientV5({ ⋮---- .getSpreadTickers({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Spread-Trading/get-spread-trade-history.js ================ const client = new RestClientV5({ ⋮---- .getSpreadTradeHistory({ ⋮---- .then((response) => { console.log(response); ⋮---- .catch((error) => { console.error(error); ================ File: examples/apidoc/V5/Trade/pre-check-order.js ================ const client = new RestClientV5({ ⋮---- // Submit a market order ⋮---- .preCheckOrder({ ⋮---- .then((response) => { console.log('Market order result', response); ⋮---- .catch((error) => { console.error('Market order error', error); ================ 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-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-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; startTime?: number; endTime?: number; limit?: number; cursor?: string; } ⋮---- 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; } ================ 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-earn.ts ================ export interface SubmitStakeRedeemParamsV5 { category: string; orderType: 'Stake' | 'Redeem'; accountType: 'FUND' | 'UNIFIED'; amount: string; coin: string; productId: string; orderLinkId: string; } ⋮---- export interface GetEarnOrderHistoryParamsV5 { category: string; orderId?: string; orderLinkId?: string; } ⋮---- export interface GetEarnPositionParamsV5 { category: string; productId?: string; coin?: 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; status?: InstrumentStatusV5; baseCoin?: string; limit?: number; cursor?: string; } ⋮---- export interface GetOrderbookParamsV5 { category: CategoryV5; symbol: string; limit?: number; } ⋮---- 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-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-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'; 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-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/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; } ⋮---- 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/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-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; } ⋮---- export interface EarnPositionV5 { coin: string; productId: string; amount: string; totalPnl: string; claimableYield: 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/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; } ================ File: src/types/websockets/index.ts ================ ================ 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: .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 ================ File: examples/apidoc/V5/P2P/upload-chat-file.js ================ // Initialize the client with testnet mode const client = new RestClientV5({ ⋮---- // Create form data const formData = new FormData(); formData.append('upload_file', fs.createReadStream('path/to/your/file.jpg')); // Replace with your file path ⋮---- // Call the function ⋮---- .uploadP2PChatFile(formData) .then((response) => { console.log('Response:', response); ⋮---- .catch((error) => { console.error('Error:', error); ================ 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: 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 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/response/index.ts ================ ================ File: src/types/index.ts ================ ================ 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/index.ts ================ ================ 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; } ⋮---- 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; } ================ 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; 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; displayName: string; } ⋮---- export interface OptionInstrumentInfoV5 { symbol: string; optionsType: OptionTypeV5; status: InstrumentStatusV5; baseCoin: string; quoteCoin: string; settleCoin: string; launchTime: string; deliveryTime: string; deliveryFeeRate: string; priceFilter: { minPrice: string; maxPrice: string; tickSize: string; }; lotSizeFilter: { maxOrderQty: string; minOrderQty: string; qtyStep: string; }; displayName: string; } ⋮---- export interface SpotInstrumentInfoV5 { symbol: string; baseCoin: string; quoteCoin: string; innovation: '0' | '1'; status: InstrumentStatusV5; marginTrading: MarginTradingV5; stTag: '0' | '1'; lotSizeFilter: { basePrecision: string; quotePrecision: string; minOrderQty: string; maxOrderQty: string; minOrderAmt: string; maxOrderAmt: string; }; priceFilter: { tickSize: string; }; riskParameters: { priceLimitRatioX: string; priceLimitRatioY: string; }; } ⋮---- type InstrumentInfoV5Mapping = { linear: LinearInverseInstrumentInfoV5[]; inverse: LinearInverseInstrumentInfoV5[]; option: OptionInstrumentInfoV5[]; spot: SpotInstrumentInfoV5[]; }; ⋮---- export type InstrumentInfoResponseV5 = 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; } ⋮---- 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; 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; } ⋮---- /** * * - 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; } ================ 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; 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; } ⋮---- 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-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) } ⋮---- 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; } ⋮---- export interface SpreadTradeLegV5 { symbol: string; side: 'Buy' | 'Sell'; execPrice: string; execTime: string; execValue: string; execType: string; category: 'linear' | 'spot'; execQty: string; execFee: string; execId: string; } ⋮---- 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: 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'; ⋮---- /** 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 */ ⋮---- 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'; ⋮---- 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: 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 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-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; } ⋮---- 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/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 GetBorrowableCoinsNewParamsV5 { vipLevel?: string; currency?: string; } ⋮---- export interface GetCollateralCoinsNewParamsV5 { currency?: string; } ⋮---- export interface GetMaxCollateralAmountNewParamsV5 { currency: string; } ⋮---- export interface AdjustCollateralAmountNewParamsV5 { currency: string; amount: string; direction: '0' | '1'; } ⋮---- export interface GetCollateralAdjustmentHistoryNewParamsV5 { 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 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; collateralList?: { currency: string; amount: string; }[]; } ⋮---- 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 GetRepaymentHistoryFixedParamsV5 { repayId?: string; loanCurrency?: 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 BorrowableCoinNewV5 { 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 CollateralDataNewV5 { collateralRatioConfigList: CollateralRatioConfigV5[]; currencyLiquidationList: CurrencyLiquidationV5[]; } ⋮---- export interface MaxCollateralAmountNewV5 { maxCollateralAmount: string; } ⋮---- // Additional New Crypto Loan Types ⋮---- export interface AdjustCollateralAmountNewV5 { adjustId: number; } ⋮---- export interface CollateralAdjustmentHistoryNewV5 { adjustId: number; adjustTime: number; afterLTV: string; amount: string; collateralCurrency: string; direction: number; preLTV: string; status: number; } ⋮---- export interface BorrowListNewV5 { fixedTotalDebt: string; fixedTotalDebtUSD: string; flexibleHourlyInterestRate: string; flexibleTotalDebt: string; flexibleTotalDebtUSD: string; loanCurrency: string; } ⋮---- export interface CollateralListNewV5 { amount: string; amountUSD: string; currency: string; ltv: string; } ⋮---- export interface SupplyListNewV5 { amount: string; amountUSD: string; currency: string; } ⋮---- export interface CryptoLoanPositionNewV5 { borrowList: BorrowListNewV5[]; collateralList: CollateralListNewV5[]; supplyList: SupplyListNewV5[]; 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; } ⋮---- 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; borrowCurrency: string; borrowTime: string; interestPaid: string; loanId: string; orderId: string; repaymentTime: string; residualPenaltyInterest: string; residualPrincipal: string; status: number; term: string; } ⋮---- 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; } ⋮---- 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; } ================ 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 */ ================ 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/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 ⋮---- // 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)[], wsKey?: 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: src/types/websockets/ws-events.ts ================ import WebSocket from 'isomorphic-ws'; ⋮---- 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; } ⋮---- 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; 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; } ⋮---- 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; } ⋮---- 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; } ⋮---- 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; 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; } ⋮---- 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 type WSSystemStatusEventV5 = WSPublicTopicEventV5< 'system.status', 'snapshot', SystemStatusItemV5[] >; ================ 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) ## 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. --- ### 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/rest-client-v5.ts ================ /* eslint-disable max-len */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { AccountBorrowCollateralLimitV5, AccountCoinBalanceV5, AccountInfoV5, AccountMarginModeV5, AccountOrderV5, AccountTypeV5, AddOrReduceMarginParamsV5, AddOrReduceMarginResultV5, AdjustCollateralAmountNewParamsV5, AdjustCollateralAmountNewV5, AffiliateUserInfoV5, AffiliateUserListItemV5, AllCoinsBalanceV5, AllowedDepositCoinInfoV5, AmendOrderParamsV5, AmendSpreadOrderParamsV5, ApiKeyInfoV5, APIResponseV3, APIResponseV3WithTime, AssetInfoV5, BatchAmendOrderParamsV5, BatchAmendOrderResultV5, BatchCancelOrderParamsV5, BatchCancelOrderResultV5, BatchCreateOrderResultV5, BatchOrderParamsV5, BatchOrdersRetExtInfoV5, // New Crypto Loan Types BorrowableCoinNewV5, BorrowContractInfoFixedV5, BorrowCryptoLoanParamsV5, // Flexible Loan Types BorrowFlexibleParamsV5, BorrowFlexibleV5, BorrowHistoryFlexibleV5, BorrowHistoryRecordV5, BorrowOrderInfoFixedV5, BorrowOrderQuoteFixedV5, BrokerIssuedVoucherV5, BrokerVoucherSpecV5, CancelAllOrdersParamsV5, CancelBorrowOrderFixedParamsV5, CancelOrderParamsV5, CancelSupplyOrderFixedParamsV5, CategoryCursorListV5, CategoryListV5, CategorySymbolListV5, CategoryV5, ClosedOptionsPositionV5, ClosedPnLV5, CoinExchangeRecordV5, CoinGreeksV5, CoinInfoV5, CollateralAdjustmentHistoryNewV5, CollateralDataNewV5, CollateralInfoV5, CompletedLoanOrderV5, ConfirmNewRiskLimitParamsV5, ConvertCoinsParamsV5, ConvertCoinSpecV5, ConvertHistoryRecordV5, ConvertQuoteV5, ConvertStatusV5, CreateBorrowOrderFixedParamsV5, CreateBorrowOrderFixedV5, CreateP2PAdParamsV5, CreateSubApiKeyParamsV5, CreateSubApiKeyResultV5, CreateSubMemberParamsV5, CreateSubMemberResultV5, CreateSupplyOrderFixedParamsV5, CreateSupplyOrderFixedV5, CryptoLoanPositionNewV5, CursorListV5, CursorRowsV5, DCPInfoV5, DeleteSubMemberParamsV5, DeliveryPriceV5, DeliveryRecordV5, DepositAddressChainV5, DepositRecordV5, EarnOrderHistoryV5, EarnPositionV5, EarnProductV5, ExchangeBrokerAccountInfoV5, ExchangeBrokerEarningResultV5, ExchangeBrokerSubAccountDepositRecordV5, ExecutionV5, FeeRateV5, FundingRateHistoryResponseV5, GetAccountCoinBalanceParamsV5, GetAccountHistoricOrdersParamsV5, GetAccountOrdersParamsV5, GetAllCoinsBalanceParamsV5, GetAllowedDepositCoinInfoParamsV5, GetAssetInfoParamsV5, GetBorrowableCoinsNewParamsV5, // Additional Fixed Loan Types GetBorrowContractInfoFixedParamsV5, GetBorrowHistoryFlexibleParamsV5, GetBorrowHistoryParamsV5, GetBorrowOrderInfoFixedParamsV5, GetBorrowOrderQuoteFixedParamsV5, GetBrokerIssuedVoucherParamsV5, GetBrokerSubAccountDepositsV5, GetClassicTransactionLogsParamsV5, GetClosedOptionsPositionsParamsV5, GetClosedPnLParamsV5, GetCoinExchangeRecordParamsV5, GetCollateralAdjustmentHistoryNewParamsV5, GetCollateralCoinsNewParamsV5, GetCompletedLoanOrderHistoryParamsV5, GetConvertHistoryParamsV5, GetDeliveryPriceParamsV5, GetDeliveryRecordParamsV5, GetDepositRecordParamsV5, GetEarnOrderHistoryParamsV5, GetEarnPositionParamsV5, GetExchangeBrokerEarningsParamsV5, GetExecutionListParamsV5, GetFeeRateParamsV5, GetFundingRateHistoryParamsV5, GetHistoricalVolatilityParamsV5, GetIndexPriceKlineParamsV5, GetInstrumentsInfoParamsV5, GetInsuranceParamsV5, GetInternalDepositRecordParamsV5, GetInternalTransferParamsV5, GetKlineParamsV5, GetLoanLTVAdjustmentHistoryParamsV5, GetLongShortRatioParamsV5, GetMarkPriceKlineParamsV5, GetMaxCollateralAmountNewParamsV5, GetMovePositionHistoryParamsV5, GetOngoingFlexibleLoansParamsV5, GetOpenInterestParamsV5, GetOptionDeliveryPriceParamsV5, GetOrderbookParamsV5, GetP2PAccountCoinsBalanceParamsV5, GetP2PCounterpartyUserInfoParamsV5, GetP2POnlineAdsParamsV5, GetP2POrderMessagesParamsV5, GetP2POrdersParamsV5, GetP2PPendingOrdersParamsV5, GetP2PPersonalAdsParamsV5, GetPremiumIndexPriceKlineParamsV5, GetPreUpgradeClosedPnlParamsV5, GetPreUpgradeOptionDeliveryRecordParamsV5, GetPreUpgradeOrderHistoryParamsV5, GetPreUpgradeTradeHistoryParamsV5, GetPreUpgradeTransactionLogParamsV5, GetPreUpgradeUSDCSessionParamsV5, GetPublicTradingHistoryParamsV5, GetRepaymentHistoryFixedParamsV5, GetRepaymentHistoryFlexibleParamsV5, GetRepaymentHistoryParamsV5, GetRiskLimitParamsV5, GetSettlementRecordParamsV5, GetSpreadInstrumentsInfoParamsV5, GetSpreadOpenOrdersParamsV5, GetSpreadOrderHistoryParamsV5, GetSpreadTradeHistoryParamsV5, GetSubAccountAllApiKeysParamsV5, GetSubAccountDepositRecordParamsV5, GetSupplyContractInfoFixedParamsV5, GetSupplyOrderInfoFixedParamsV5, // Fixed Loan Types GetSupplyOrderQuoteFixedParamsV5, GetSystemStatusParamsV5, GetTickersParamsV5, GetTransactionLogParamsV5, GetUniversalTransferRecordsParamsV5, GetUnpaidLoanOrdersParamsV5, GetVIPMarginDataParamsV5, GetWalletBalanceParamsV5, GetWithdrawalRecordsParamsV5, HistoricalVolatilityV5, InstrumentInfoResponseV5, InsuranceResponseV5, InternalDepositRecordV5, InternalTransferRecordV5, IssueVoucherParamsV5, LoanLTVAdjustmentHistoryV5, LongShortRatioV5, MarkP2POrderAsPaidParamsV5, MaxCollateralAmountNewV5, 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, RepayFixedParamsV5, RepayFixedV5, RepayFlexibleParamsV5, RepayFlexibleV5, RepayLiabilityParamsV5, RepayLiabilityResultV5, RepaymentHistoryFixedV5, RepaymentHistoryFlexibleV5, RepaymentHistoryV5, RequestConvertQuoteParamsV5, RiskLimitV5, SendP2POrderMessageParamsV5, SetAutoAddMarginParamsV5, SetCollateralCoinParamsV5, SetLeverageParamsV5, SetLimitPriceActionParamsV5, SetRiskLimitParamsV5, SetRiskLimitResultV5, 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, WithdrawalRecordV5, WithdrawParamsV5, } from './types'; ⋮---- // New Crypto Loan Types ⋮---- // Flexible Loan Types ⋮---- // Additional Fixed Loan Types ⋮---- // Fixed Loan 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> ⋮---- 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>> ⋮---- getLongShortRatio( params: GetLongShortRatioParamsV5, ): Promise>> ⋮---- getOrderPriceLimit(params: { symbol: string; category: 'spot' | 'linear' | 'inverse'; }): 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); ⋮---- /** * 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>> ⋮---- /** * 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> ⋮---- /** * 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 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> ⋮---- /** * ****** 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 */ 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" */ getAccountBorrowCollateralLimit(params: { loanCurrency: string; collateralCurrency: string; }): Promise> ⋮---- /** * Borrow Crypto Loan * * 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 * * 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 * * 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 * * 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 * * 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 * * 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. * * 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 * * 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 * */ getBorrowableCoinsNew(params?: GetBorrowableCoinsNewParamsV5): Promise< APIResponseV3WithTime<{ list: BorrowableCoinNewV5[]; }> > { return this.get('/v5/crypto-loan-common/loanable-data', params); ⋮---- /** * Get Collateral Coins New * */ getCollateralCoinsNew( params?: GetCollateralCoinsNewParamsV5, ): Promise> ⋮---- /** * Get Max. Allowed Collateral Reduction Amount New * */ getMaxCollateralAmountNew( params: GetMaxCollateralAmountNewParamsV5, ): Promise> ⋮---- /** * Adjust Collateral Amount New * You can increase or reduce your collateral amount. When you reduce, please obey the Get Max. Allowed Collateral Reduction Amount */ adjustCollateralAmountNew( params: AdjustCollateralAmountNewParamsV5, ): Promise> ⋮---- /** * Get Collateral Adjustment History New * Query for your LTV adjustment history. * */ getCollateralAdjustmentHistoryNew( params?: GetCollateralAdjustmentHistoryNewParamsV5, ): Promise< APIResponseV3WithTime<{ list: CollateralAdjustmentHistoryNewV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-common/adjustment-history', params); ⋮---- /** * Get Crypto Loan Position New * */ getCryptoLoanPositionNew(): 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> ⋮---- /** * Get Flexible Loans * Query for your ongoing loans * */ getOngoingFlexibleLoans(params?: GetOngoingFlexibleLoansParamsV5): Promise< APIResponseV3WithTime<{ list: OngoingFlexibleLoanV5[]; }> > { 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> ⋮---- /** * Get Repayment History * */ getRepaymentHistoryFixed(params?: GetRepaymentHistoryFixedParamsV5): Promise< APIResponseV3WithTime<{ list: RepaymentHistoryFixedV5[]; nextPageCursor: string; }> > { return this.getPrivate('/v5/crypto-loan-fixed/repayment-history', 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: Either orderId or orderLinkId is required. If both are passed, * make sure they're matched, otherwise returning empty result */ getEarnOrderHistory(params: GetEarnOrderHistoryParamsV5): Promise< APIResponseV3WithTime<{ list: EarnOrderHistoryV5[]; }> > { 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); ⋮---- /** * ****** 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 */ uploadP2PChatFile(params: { upload_file: File; // Only supports: jpg, png, jpeg, pdf, mp4 }): Promise> ⋮---- upload_file: File; // Only supports: jpg, png, jpeg, pdf, mp4 ⋮---- /** * 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> ================ File: package.json ================ { "name": "bybit-api", "version": "4.2.1", "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.7.9", "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" } ================================================================ End of Codebase ================================================================