From e5845a734612e415ba5386092799b79b1f9dbfcf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 26 Oct 2026 08:16:02 +0000 Subject: [PATCH 1/2] feat: portfolio income pagination and margin listen key v2 (v3.6.10) - Remove page from portfolio UM and CM income queries. Paginate with startTime and endTime (effective 2026-10-28). - Deprecate stable-rate crypto loan history methods retired 2026-10-16. Those routes return HTTP 404. Flexible Rate v2 is unchanged. - Add Margin user data stream v2 listen key create, keepalive and close (POST/PUT/DELETE /sapi/v2/margin/listen-key). - Document the shared 100 requests per month limit on USD-M and COIN-M GET income/asyn download ids. - Add a short spot user data stream snippet near the top of the README. Co-authored-by: Jerko J --- README.md | 11 ++++++++- package-lock.json | 4 ++-- package.json | 2 +- src/coinm-client.ts | 5 ++++ src/main-client.ts | 44 +++++++++++++++++++++++++++++++++++ src/portfolio-client.ts | 8 +++++++ src/types/portfolio-margin.ts | 12 ++++++++-- src/usdm-client.ts | 5 ++++ 8 files changed, 85 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b77db0fe..cefb37a4 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,16 @@ > [!TIP] > Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. -Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets: +Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets. + +Spot user data stream (listen key is created and kept alive for you): + +```javascript +import { WebsocketClient } from 'binance'; +const ws = new WebsocketClient({ api_key: 'key', api_secret: 'secret' }); +ws.on('formattedMessage', (data) => console.log(data)); +ws.subscribeSpotUserDataStream(); +``` - Professional, robust & performant Binance SDK with leading trading volume in production (livenet). - Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. diff --git a/package-lock.json b/package-lock.json index a9627eab..d4005f80 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "binance", - "version": "3.6.9", + "version": "3.6.10", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "binance", - "version": "3.6.9", + "version": "3.6.10", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index c788508a..1c162421 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "binance", - "version": "3.6.9", + "version": "3.6.10", "description": "Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/coinm-client.ts b/src/coinm-client.ts index c257dd57..4bee526f 100644 --- a/src/coinm-client.ts +++ b/src/coinm-client.ts @@ -499,6 +499,11 @@ export class CoinMClient extends BaseRestClient { return this.getPrivate('dapi/v1/income', params); } + /** + * Get a download id for futures transaction history (`GET /dapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. + */ getDownloadIdForFuturesTransactionHistory(params: { startTime: number; endTime: number; diff --git a/src/main-client.ts b/src/main-client.ts index 719b156b..a03929a8 100644 --- a/src/main-client.ts +++ b/src/main-client.ts @@ -3468,6 +3468,10 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/loan/collateral/data', params); } + /** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/income` returns HTTP 404. Flexible Rate v2 is unaffected. + */ getCryptoLoansIncomeHistory( params: GetCryptoLoansIncomeHistoryParams, ): Promise { @@ -3533,6 +3537,10 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/loan/ongoing/orders', params); } + /** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/borrow/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise<{ rows: LoanBorrowHistory[]; total: number; @@ -3540,6 +3548,10 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/loan/borrow/history', params); } + /** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/ltv/adjustment/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ getCryptoLoanLTVAdjustmentHistory( params: GetLoanLTVAdjustmentHistoryParams, ): Promise<{ @@ -3549,6 +3561,10 @@ export class MainClient extends BaseRestClient { return this.getPrivate('sapi/v1/loan/ltv/adjustment/history', params); } + /** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/repay/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ getCryptoLoanRepaymentHistory( params: GetLoanRepaymentHistoryParams, ): Promise { @@ -4986,6 +5002,34 @@ export class MainClient extends BaseRestClient { return this.delete('sapi/v1/margin/listen-key'); } + /** + * Start a Margin user data stream (`POST /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. + * + * New and migrated accounts receive -3086 from + * `POST /sapi/v1/margin/listen-key` and `POST /sapi/v1/userListenToken`. + * Connect with `wss://fstream.binance.com/private/ws/`. + */ + getMarginUserDataListenKeyV2(): Promise<{ listenKey: string }> { + return this.post('sapi/v2/margin/listen-key'); + } + + /** + * Keepalive a Margin user data stream (`PUT /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. `listenKey` is a query parameter. + */ + keepAliveMarginUserDataListenKeyV2(listenKey: string): Promise { + return this.put(`sapi/v2/margin/listen-key?listenKey=${listenKey}`); + } + + /** + * Close a Margin user data stream (`DELETE /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. The listen key is not a parameter. + */ + closeMarginUserDataListenKeyV2(): Promise { + return this.delete('sapi/v2/margin/listen-key'); + } + getMarginUtaUserDataListenKey(): Promise<{ listenKey: string }> { return this.post('sapi/v2/margin/uta/listen-key'); } diff --git a/src/portfolio-client.ts b/src/portfolio-client.ts index 8b615096..775c0066 100644 --- a/src/portfolio-client.ts +++ b/src/portfolio-client.ts @@ -790,12 +790,20 @@ export class PortfolioClient extends BaseRestClient { return this.postPrivate('papi/v1/bnb-transfer', params); } + /** + * Query UM income history (`GET /papi/v1/um/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ getUMIncomeHistory( params?: QueryPortfolioUMIncomeReq, ): Promise { return this.getPrivate('papi/v1/um/income', params); } + /** + * Query CM income history (`GET /papi/v1/cm/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ getCMIncomeHistory( params?: QueryPortfolioCMIncomeReq, ): Promise { diff --git a/src/types/portfolio-margin.ts b/src/types/portfolio-margin.ts index b5e1f10b..bcb501e1 100644 --- a/src/types/portfolio-margin.ts +++ b/src/types/portfolio-margin.ts @@ -1367,12 +1367,16 @@ export type UMIncomeType = | 'COIN_SWAP_WITHDRAW' | 'POSITION_LIMIT_INCREASE_FEE'; +/** + * UM income history query for `GET /papi/v1/um/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ export interface QueryPortfolioUMIncomeReq { symbol?: string; incomeType?: UMIncomeType; startTime?: number; endTime?: number; - page?: number; limit?: number; // Default 100; max 1000 } @@ -1396,12 +1400,16 @@ export type CMIncomeType = | 'INSURANCE_CLEAR' | 'DELIVERED_SETTELMENT'; +/** + * CM income history query for `GET /papi/v1/cm/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ export interface QueryPortfolioCMIncomeReq { symbol?: string; incomeType?: CMIncomeType; startTime?: number; endTime?: number; - page?: number; limit?: number; // Default 100; max 1000 } diff --git a/src/usdm-client.ts b/src/usdm-client.ts index 70ed3811..a028e118 100644 --- a/src/usdm-client.ts +++ b/src/usdm-client.ts @@ -600,6 +600,11 @@ export class USDMClient extends BaseRestClient { return this.getPrivate('fapi/v1/apiTradingStatus', params); } + /** + * Get a download id for futures transaction history (`GET /fapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. + */ getFuturesTransactionHistoryDownloadId(params: { startTime: number; endTime: number; From dc6a6d4a73954b39823a1fb66634f9b4616710b5 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 26 Oct 2026 09:17:15 +0100 Subject: [PATCH 2/2] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 525 +- .../closeMarginUserDataListenKeyV2.js | 22 + .../getMarginUserDataListenKeyV2.js | 22 + .../keepAliveMarginUserDataListenKeyV2.js | 22 + llms.txt | 43589 ++++++++-------- 5 files changed, 22161 insertions(+), 22019 deletions(-) create mode 100644 examples/apidoc/MainClient/closeMarginUserDataListenKeyV2.js create mode 100644 examples/apidoc/MainClient/getMarginUserDataListenKeyV2.js create mode 100644 examples/apidoc/MainClient/keepAliveMarginUserDataListenKeyV2.js diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index c9a21dd0..3838288f 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -387,200 +387,203 @@ This table includes all endpoints from the official Exchange API docs and corres | [getCryptoLoanLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3446) | :closed_lock_with_key: | GET | `sapi/v1/loan/loanable/data` | | [getCryptoLoanCollateralRepayRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3453) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/collateral/rate` | | [getCryptoLoanCollateralAssetsData()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3462) | :closed_lock_with_key: | GET | `sapi/v1/loan/collateral/data` | -| [getCryptoLoansIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3471) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | -| [borrowCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3486) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | -| [repayCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3495) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | -| [adjustCryptoLoanLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3504) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | -| [customizeCryptoLoanMarginCall()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3513) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | -| [getCryptoLoanOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3529) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | -| [getCryptoLoanBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3536) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | -| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3543) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | -| [getCryptoLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3552) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | -| [getSimpleEarnAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3564) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | -| [getFlexibleSavingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3568) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | -| [getSimpleEarnLockedProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3575) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | -| [getFlexibleProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3584) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | -| [getLockedProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3593) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | -| [getFlexiblePersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3602) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | -| [getLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3611) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | -| [purchaseFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3626) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | -| [subscribeSimpleEarnLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3632) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | -| [redeemFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3638) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | -| [redeemLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3644) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | -| [setFlexibleAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3650) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | -| [setLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3659) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | -| [getFlexibleSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3668) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | -| [getLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3677) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | -| [setLockedProductRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3686) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | -| [getFlexibleSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3704) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | -| [getLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3716) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | -| [getFlexibleRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3728) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | -| [getLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3740) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | -| [getFlexibleRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3750) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | -| [getLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3760) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | -| [getCollateralRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3770) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | -| [getRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3780) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | -| [getVipBorrowInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3796) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | -| [getVipLoanInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3802) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | -| [getVipLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3811) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | -| [getVipCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3818) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | -| [getVipLoanOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3831) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | -| [getVipLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3838) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | -| [checkVipCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3847) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | -| [getVipApplicationStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3854) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | -| [renewVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3867) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | -| [repayVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3871) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | -| [borrowVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3875) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | -| [getVipLoanFixedRateMarket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3879) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | -| [borrowVipLoanFixedRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3886) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | -| [getDualInvestmentProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3898) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | -| [subscribeDualInvestmentProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3913) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | -| [getDualInvestmentPositions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3919) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | -| [getDualInvestmentAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3928) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | -| [getVipLoanAccruedInterest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3932) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | -| [updateAutoCompoundStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3946) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | -| [createGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3961) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | -| [createDualTokenGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3965) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | -| [redeemGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3969) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | -| [verifyGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3973) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | -| [getTokenLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3977) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | -| [getRsaPublicKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3981) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | -| [getNftTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3991) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | -| [getNftDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3998) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | -| [getNftWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4005) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | -| [getNftAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4012) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | -| [getC2CTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4025) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | -| [getFiatOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4040) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | -| [getFiatPaymentsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4046) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | -| [fiatWithdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4052) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | -| [fiatDeposit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4056) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | -| [getFiatOrderDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4060) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | -| [getSpotRebateHistoryRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4072) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | -| [getPortfolioMarginIndexPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4085) | | GET | `sapi/v1/portfolio/asset-index-price` | -| [getPortfolioMarginAssetLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4091) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | -| [getPortfolioMarginProCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4097) | | GET | `sapi/v1/portfolio/collateralRate` | -| [getPortfolioMarginProTieredCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4103) | | GET | `sapi/v2/portfolio/collateralRate` | -| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4114) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | -| [getPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4118) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/delta-mode` | -| [switchPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4122) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/delta-mode` | -| [setPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4128) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | -| [getPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4134) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | -| [deletePortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4138) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | -| [bnbTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4142) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | -| [submitPortfolioMarginProFullTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4148) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | -| [submitPortfolioMarginProSpecificTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4161) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | -| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4171) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | -| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4179) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | -| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4183) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | -| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4189) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | -| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4195) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | -| [getPortfolioMarginProInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4201) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | -| [getPortfolioMarginProSpanAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4207) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | -| [getPortfolioMarginProAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4211) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | -| [mintPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4221) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | -| [redeemPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4231) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | -| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4239) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | -| [transferLDUSDTPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4254) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | -| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4267) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | -| [getFuturesTickLevelOrderbookDataLink()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4284) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | -| [getBlvtInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4298) | | GET | `sapi/v1/blvt/tokenInfo` | -| [subscribeBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4302) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | -| [getBlvtSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4306) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | -| [redeemBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4312) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | -| [getBlvtRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4316) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | -| [getBlvtUserLimitInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4322) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | -| [getPayTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4333) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | -| [getInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4343) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | -| [closeInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4349) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | -| [addInstLoanCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4353) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | -| [getActiveInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | -| [getClosedInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4363) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | -| [getInstLoanForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4375) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | -| [transferInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4389) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | -| [getInstitutionalLoanMaxBorrowable()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4401) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | -| [borrowInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4407) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | -| [getInstLoanInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4413) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | -| [repayInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4422) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | -| [getInstLoanBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4428) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | -| [getMarginInterestRebateBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4434) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | -| [getMarginInterestRebateBalanceRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4438) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | -| [getAlphaTokenList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4453) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | -| [getAlphaExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4460) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | -| [getAlphaAggTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4467) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | -| [getAlphaKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4475) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | -| [getAlphaTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4483) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | -| [getAlphaFullDepth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4491) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | -| [createBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4507) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [getBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4513) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | -| [enableMarginBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4519) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | -| [createApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4525) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | -| [changePermissionApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4531) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [changeComissionBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4537) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | -| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4543) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | -| [updateIpRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4552) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | -| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4566) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | -| [deleteApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4582) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | -| [getSubAccountBrokerIpRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4588) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | -| [getApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4604) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | -| [getBrokerInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4610) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | -| [updateSubAccountBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4614) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | -| [updateSubAccountMarginInterestBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4624) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | -| [getSubAccountBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4637) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | -| [deleteBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4653) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | -| [transferBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4663) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | -| [getBrokerSubAccountHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4669) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | -| [submitBrokerSubFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4675) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | -| [getSubAccountFuturesTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4690) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | -| [getBrokerSubDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4702) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | -| [getBrokerSubAccountSpotAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4708) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | -| [getSubAccountMarginAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4717) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | -| [querySubAccountFuturesAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4726) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | -| [universalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4735) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | -| [getUniversalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4742) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | -| [updateBrokerSubAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4754) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | -| [updateBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4760) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | -| [getBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4769) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | -| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4778) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4787) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | -| [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4796) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | -| [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4802) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | -| [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4839) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | -| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4850) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | -| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4869) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | -| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4879) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | -| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4920) | | POST | `api/v3/userDataStream` | -| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4924) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | -| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4928) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | -| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4935) | | POST | `sapi/v1/userDataStream` | -| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4939) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4943) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | -| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4948) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4956) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4965) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | -| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4977) | | POST | `sapi/v1/margin/listen-key` | -| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4981) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | -| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4985) | | DELETE | `sapi/v1/margin/listen-key` | -| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4989) | | POST | `sapi/v2/margin/uta/listen-key` | -| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4993) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | -| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4997) | | DELETE | `sapi/v2/margin/uta/listen-key` | -| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5005) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | -| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5027) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | -| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5034) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | -| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5043) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | -| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5052) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | -| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5067) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | -| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5076) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | -| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5090) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | -| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5100) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | -| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5109) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | -| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5118) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | -| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5125) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | -| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5132) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | -| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5139) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | -| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5146) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | -| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5163) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | -| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5171) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | -| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5178) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | +| [getCryptoLoansIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3475) | :closed_lock_with_key: | GET | `sapi/v1/loan/income` | +| [borrowCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3490) | :closed_lock_with_key: | POST | `sapi/v1/loan/borrow` | +| [repayCryptoLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3499) | :closed_lock_with_key: | POST | `sapi/v1/loan/repay` | +| [adjustCryptoLoanLTV()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3508) | :closed_lock_with_key: | POST | `sapi/v1/loan/adjust/ltv` | +| [customizeCryptoLoanMarginCall()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3517) | :closed_lock_with_key: | POST | `sapi/v1/loan/customize/margin_call` | +| [getCryptoLoanOngoingOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3533) | :closed_lock_with_key: | GET | `sapi/v1/loan/ongoing/orders` | +| [getCryptoLoanBorrowHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3544) | :closed_lock_with_key: | GET | `sapi/v1/loan/borrow/history` | +| [getCryptoLoanLTVAdjustmentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3555) | :closed_lock_with_key: | GET | `sapi/v1/loan/ltv/adjustment/history` | +| [getCryptoLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3568) | :closed_lock_with_key: | GET | `sapi/v1/loan/repay/history` | +| [getSimpleEarnAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3580) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/account` | +| [getFlexibleSavingProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3584) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/list` | +| [getSimpleEarnLockedProductList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3591) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/list` | +| [getFlexibleProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3600) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/position` | +| [getLockedProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3609) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/position` | +| [getFlexiblePersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3618) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/personalLeftQuota` | +| [getLockedPersonalLeftQuota()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3627) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/personalLeftQuota` | +| [purchaseFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3642) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/subscribe` | +| [subscribeSimpleEarnLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3648) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/subscribe` | +| [redeemFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3654) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/redeem` | +| [redeemLockedProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3660) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/redeem` | +| [setFlexibleAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3666) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/flexible/setAutoSubscribe` | +| [setLockedAutoSubscribe()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3675) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setAutoSubscribe` | +| [getFlexibleSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3684) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/subscriptionPreview` | +| [getLockedSubscriptionPreview()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3693) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/subscriptionPreview` | +| [setLockedProductRedeemOption()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3702) | :closed_lock_with_key: | POST | `sapi/v1/simple-earn/locked/setRedeemOption` | +| [getFlexibleSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3720) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/subscriptionRecord` | +| [getLockedSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3732) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/subscriptionRecord` | +| [getFlexibleRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3744) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/redemptionRecord` | +| [getLockedRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3756) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/redemptionRecord` | +| [getFlexibleRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3766) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rewardsRecord` | +| [getLockedRewardsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3776) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/locked/history/rewardsRecord` | +| [getCollateralRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3786) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/collateralRecord` | +| [getRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3796) | :closed_lock_with_key: | GET | `sapi/v1/simple-earn/flexible/history/rateHistory` | +| [getVipBorrowInterestRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3812) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/interestRate` | +| [getVipLoanInterestRateHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3818) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/interestRateHistory` | +| [getVipLoanableAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3827) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/loanable/data` | +| [getVipCollateralAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3834) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/data` | +| [getVipLoanOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3847) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/ongoing/orders` | +| [getVipLoanRepaymentHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3854) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/repay/history` | +| [checkVipCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3863) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/collateral/account` | +| [getVipApplicationStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3870) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/request/data` | +| [renewVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3883) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/renew` | +| [repayVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3887) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/repay` | +| [borrowVipLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3891) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/borrow` | +| [getVipLoanFixedRateMarket()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3895) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/fixed/market` | +| [borrowVipLoanFixedRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3902) | :closed_lock_with_key: | POST | `sapi/v1/loan/vip/fixed/borrow` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3914) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/list` | +| [subscribeDualInvestmentProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3929) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/subscribe` | +| [getDualInvestmentPositions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3935) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/positions` | +| [getDualInvestmentAccounts()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3944) | :closed_lock_with_key: | GET | `sapi/v1/dci/product/accounts` | +| [getVipLoanAccruedInterest()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3948) | :closed_lock_with_key: | GET | `sapi/v1/loan/vip/accruedInterest` | +| [updateAutoCompoundStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3962) | :closed_lock_with_key: | POST | `sapi/v1/dci/product/auto_compound/edit-status` | +| [createGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3977) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/createCode` | +| [createDualTokenGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3981) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/buyCode` | +| [redeemGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3985) | :closed_lock_with_key: | POST | `sapi/v1/giftcard/redeemCode` | +| [verifyGiftCard()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3989) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/verify` | +| [getTokenLimit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3993) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/buyCode/token-limit` | +| [getRsaPublicKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L3997) | :closed_lock_with_key: | GET | `sapi/v1/giftcard/cryptography/rsa-public-key` | +| [getNftTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4007) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/transactions` | +| [getNftDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4014) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/deposit` | +| [getNftWithdrawHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4021) | :closed_lock_with_key: | GET | `sapi/v1/nft/history/withdraw` | +| [getNftAsset()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4028) | :closed_lock_with_key: | GET | `sapi/v1/nft/user/getAsset` | +| [getC2CTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4041) | :closed_lock_with_key: | GET | `sapi/v1/c2c/orderMatch/listUserOrderHistory` | +| [getFiatOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4056) | :closed_lock_with_key: | GET | `sapi/v1/fiat/orders` | +| [getFiatPaymentsHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4062) | :closed_lock_with_key: | GET | `sapi/v1/fiat/payments` | +| [fiatWithdraw()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4068) | :closed_lock_with_key: | POST | `/sapi/v2/fiat/withdraw` | +| [fiatDeposit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4072) | :closed_lock_with_key: | POST | `sapi/v1/fiat/deposit` | +| [getFiatOrderDetail()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4076) | :closed_lock_with_key: | GET | `sapi/v1/fiat/get-order-detail` | +| [getSpotRebateHistoryRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4088) | :closed_lock_with_key: | GET | `sapi/v1/rebate/taxQuery` | +| [getPortfolioMarginIndexPrice()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4101) | | GET | `sapi/v1/portfolio/asset-index-price` | +| [getPortfolioMarginAssetLeverage()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4107) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-asset-leverage` | +| [getPortfolioMarginProCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4113) | | GET | `sapi/v1/portfolio/collateralRate` | +| [getPortfolioMarginProTieredCollateralRate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4119) | | GET | `sapi/v2/portfolio/collateralRate` | +| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4130) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/account` | +| [getPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4134) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/delta-mode` | +| [switchPortfolioDeltaMode()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4138) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/delta-mode` | +| [setPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4144) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/margin-call-level` | +| [getPortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4150) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/margin-call-level` | +| [deletePortfolioMarginMarginCallLevel()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4154) | :closed_lock_with_key: | DELETE | `sapi/v1/portfolio/margin-call-level` | +| [bnbTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4158) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/bnb-transfer` | +| [submitPortfolioMarginProFullTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4164) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/auto-collection` | +| [submitPortfolioMarginProSpecificTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4177) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/asset-collection` | +| [repayPortfolioMarginProBankruptcyLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4187) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay` | +| [getPortfolioMarginProBankruptcyLoanAmount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4195) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan` | +| [repayFuturesNegativeBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4199) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-negative-balance` | +| [updateAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4205) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/repay-futures-switch` | +| [getAutoRepayFuturesStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4211) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/repay-futures-switch` | +| [getPortfolioMarginProInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4217) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/interest-history` | +| [getPortfolioMarginProSpanAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4223) | :closed_lock_with_key: | GET | `sapi/v2/portfolio/account` | +| [getPortfolioMarginProAccountBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4227) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/balance` | +| [mintPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4237) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/mint` | +| [redeemPortfolioMarginBFUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4247) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/redeem` | +| [getPortfolioMarginBankruptcyLoanRepayHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4255) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/pmLoan-history` | +| [transferLDUSDTPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4270) | :closed_lock_with_key: | POST | `sapi/v1/portfolio/earn-asset-transfer` | +| [getTransferableEarnAssetBalanceForPortfolioMargin()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4283) | :closed_lock_with_key: | GET | `sapi/v1/portfolio/earn-asset-balance` | +| [getFuturesTickLevelOrderbookDataLink()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4300) | :closed_lock_with_key: | GET | `sapi/v1/futures/histDataLink` | +| [getBlvtInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4314) | | GET | `sapi/v1/blvt/tokenInfo` | +| [subscribeBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4318) | :closed_lock_with_key: | POST | `sapi/v1/blvt/subscribe` | +| [getBlvtSubscriptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4322) | :closed_lock_with_key: | GET | `sapi/v1/blvt/subscribe/record` | +| [redeemBlvt()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4328) | :closed_lock_with_key: | POST | `sapi/v1/blvt/redeem` | +| [getBlvtRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4332) | :closed_lock_with_key: | GET | `sapi/v1/blvt/redeem/record` | +| [getBlvtUserLimitInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4338) | :closed_lock_with_key: | GET | `sapi/v1/blvt/userLimit` | +| [getPayTransactions()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4349) | :closed_lock_with_key: | GET | `sapi/v1/pay/transactions` | +| [getInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4359) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/ltv-details` | +| [closeInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4365) | :closed_lock_with_key: | DELETE | `sapi/v1/margin/loan-group` | +| [addInstLoanCollateralAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4369) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/edit-member` | +| [getActiveInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4375) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/activated` | +| [getClosedInstLoanRiskUnits()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4379) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-groups/closed` | +| [getInstLoanForceLiquidationRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4391) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/force-liquidation` | +| [transferInstLoanRiskUnit()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4405) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/transfer-out` | +| [getInstitutionalLoanMaxBorrowable()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4417) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/max-borrowable` | +| [borrowInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4423) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/borrow` | +| [getInstLoanInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4429) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-history` | +| [repayInstitutionalLoan()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4438) | :closed_lock_with_key: | POST | `sapi/v1/margin/loan-group/repay` | +| [getInstLoanBorrowRepayRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4444) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/borrow-repay` | +| [getMarginInterestRebateBalance()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4450) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance` | +| [getMarginInterestRebateBalanceRecords()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4454) | :closed_lock_with_key: | GET | `sapi/v1/margin/loan-group/interest-rebate-balance/records` | +| [getAlphaTokenList()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4469) | | GET | `bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/all/token/list` | +| [getAlphaExchangeInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4476) | | GET | `bapi/defi/v1/public/alpha-trade/get-exchange-info` | +| [getAlphaAggTrades()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4483) | | GET | `bapi/defi/v1/public/alpha-trade/agg-trades` | +| [getAlphaKlines()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4491) | | GET | `bapi/defi/v1/public/alpha-trade/klines` | +| [getAlphaTicker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4499) | | GET | `bapi/defi/v1/public/alpha-trade/ticker` | +| [getAlphaFullDepth()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4507) | | GET | `bapi/defi/v1/public/alpha-trade/fullDepth` | +| [createBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4523) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [getBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4529) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount` | +| [enableMarginBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4535) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/futures` | +| [createApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4541) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi` | +| [changePermissionApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4547) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [changeComissionBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4553) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission` | +| [enableUniversalTransferApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4559) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/permission/universalTransfer` | +| [updateIpRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4568) | :closed_lock_with_key: | POST | `sapi/v2/broker/subAccountApi/ipRestriction` | +| [deleteIPRestrictionForSubAccountApiKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4582) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi/ipRestriction/ipList` | +| [deleteApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4598) | :closed_lock_with_key: | DELETE | `sapi/v1/broker/subAccountApi` | +| [getSubAccountBrokerIpRestriction()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4604) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/ipRestriction` | +| [getApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4620) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi` | +| [getBrokerInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4626) | :closed_lock_with_key: | GET | `sapi/v1/broker/info` | +| [updateSubAccountBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4630) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/spot` | +| [updateSubAccountMarginInterestBNBBurn()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4640) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/bnbBurn/marginInterest` | +| [getSubAccountBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4653) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/bnbBurn/status` | +| [deleteBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4669) | :closed_lock_with_key: | DELETE | `/sapi/v1/broker/subAccount` | +| [transferBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4679) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer` | +| [getBrokerSubAccountHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4685) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer` | +| [submitBrokerSubFuturesTransfer()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4691) | :closed_lock_with_key: | POST | `sapi/v1/broker/transfer/futures` | +| [getSubAccountFuturesTransferHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4706) | :closed_lock_with_key: | GET | `sapi/v1/broker/transfer/futures` | +| [getBrokerSubDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4718) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/depositHist` | +| [getBrokerSubAccountSpotAssets()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4724) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/spotSummary` | +| [getSubAccountMarginAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4733) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccount/marginSummary` | +| [querySubAccountFuturesAssetInfo()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4742) | :closed_lock_with_key: | GET | `sapi/v3/broker/subAccount/futuresSummary` | +| [universalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4751) | :closed_lock_with_key: | POST | `sapi/v1/broker/universalTransfer` | +| [getUniversalTransferBroker()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4758) | :closed_lock_with_key: | GET | `sapi/v1/broker/universalTransfer` | +| [updateBrokerSubAccountCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4770) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission` | +| [updateBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4776) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/futures` | +| [getBrokerSubAccountFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4785) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/futures` | +| [updateBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4794) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSubAccountCoinFuturesCommission()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4803) | :closed_lock_with_key: | GET | `sapi/v1/broker/subAccountApi/commission/coinFutures` | +| [getBrokerSpotCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4812) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/recentRecord` | +| [getBrokerFuturesCommissionRebate()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4818) | :closed_lock_with_key: | GET | `sapi/v1/broker/rebate/futures/recentRecord` | +| [getBrokerIfNewSpotUser()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4855) | :closed_lock_with_key: | GET | `sapi/v1/apiReferral/ifNewUser` | +| [getBrokerSubAccountDepositHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4866) | :closed_lock_with_key: | GET | `sapi/v1/bv1/apiReferral/ifNewUser` | +| [enableFuturesBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4885) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount` | +| [enableMarginApiKeyBrokerSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4895) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/margin` | +| [getSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4936) | | POST | `api/v3/userDataStream` | +| [keepAliveSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4940) | | PUT | `api/v3/userDataStream?listenKey=${listenKey}` | +| [closeSpotUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4944) | | DELETE | `api/v3/userDataStream?listenKey=${listenKey}` | +| [getMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4951) | | POST | `sapi/v1/userDataStream` | +| [keepAliveMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4955) | | PUT | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [closeMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4959) | | DELETE | `sapi/v1/userDataStream?listenKey=${listenKey}` | +| [getIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4964) | | POST | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [keepAliveIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4972) | | PUT | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [closeIsolatedMarginUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4981) | | DELETE | `sapi/v1/userDataStream/isolated?${serialiseParams(params` | +| [getMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4993) | | POST | `sapi/v1/margin/listen-key` | +| [keepAliveMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L4997) | | PUT | `sapi/v1/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginRiskUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5001) | | DELETE | `sapi/v1/margin/listen-key` | +| [getMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5013) | | POST | `sapi/v2/margin/listen-key` | +| [keepAliveMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5021) | | PUT | `sapi/v2/margin/listen-key?listenKey=${listenKey}` | +| [closeMarginUserDataListenKeyV2()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5029) | | DELETE | `sapi/v2/margin/listen-key` | +| [getMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5033) | | POST | `sapi/v2/margin/uta/listen-key` | +| [keepAliveMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5037) | | PUT | `sapi/v2/margin/uta/listen-key?listenKey=${listenKey}` | +| [closeMarginUtaUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5041) | | DELETE | `sapi/v2/margin/uta/listen-key` | +| [getMarginListenToken()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5049) | :closed_lock_with_key: | POST | `sapi/v1/userListenToken` | +| [getBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5071) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidity` | +| [addBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5078) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityAdd` | +| [removeBSwapLiquidity()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5087) | :closed_lock_with_key: | POST | `sapi/v1/bswap/liquidityRemove` | +| [getBSwapOperations()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5096) | :closed_lock_with_key: | GET | `sapi/v1/bswap/liquidityOps` | +| [getLeftDailyPurchaseQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5111) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userLeftQuota` | +| [getLeftDailyRedemptionQuotaFlexibleProduct()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5120) | :closed_lock_with_key: | GET | `sapi/v1/lending/daily/userRedemptionQuota` | +| [purchaseFixedAndActivityProject()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5134) | :closed_lock_with_key: | POST | `sapi/v1/lending/customizedFixed/purchase` | +| [getFixedAndActivityProjects()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5144) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/list` | +| [getFixedAndActivityProductPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5153) | :closed_lock_with_key: | GET | `sapi/v1/lending/project/position/list` | +| [getLendingAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5162) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/account` | +| [getPurchaseRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5169) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/purchaseRecord` | +| [getRedemptionRecord()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5176) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/redemptionRecord` | +| [getInterestHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5183) | :closed_lock_with_key: | GET | `sapi/v1/lending/union/interestHistory` | +| [changeFixedAndActivityPositionToDailyPosition()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5190) | :closed_lock_with_key: | POST | `sapi/v1/lending/positionChanged` | +| [enableConvertSubAccount()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5207) | :closed_lock_with_key: | POST | `sapi/v1/broker/subAccount/convert` | +| [convertBUSD()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5215) | :closed_lock_with_key: | POST | `sapi/v1/asset/convert-transfer` | +| [getConvertBUSDHistory()](https://github.com/sieblyio/binance/blob/master/src/main-client.ts#L5222) | :closed_lock_with_key: | GET | `sapi/v1/asset/convert-transfer/queryByPage` | # usdm-client.ts @@ -659,38 +662,38 @@ This table includes all endpoints from the official Exchange API docs and corres | [getCurrentPositionMode()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L585) | :closed_lock_with_key: | GET | `fapi/v1/positionSide/dual` | | [getIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L593) | :closed_lock_with_key: | GET | `fapi/v1/income` | | [getApiQuantitativeRulesIndicators()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L597) | :closed_lock_with_key: | GET | `fapi/v1/apiTradingStatus` | -| [getFuturesTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L603) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn` | -| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L610) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn/id` | -| [getFuturesOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L616) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn` | -| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L623) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn/id` | -| [getFuturesTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L629) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn` | -| [getFuturesTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L636) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn/id` | -| [setBNBBurnEnabled()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L642) | :closed_lock_with_key: | POST | `fapi/v1/feeBurn` | -| [getBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L648) | :closed_lock_with_key: | GET | `fapi/v1/feeBurn` | -| [signTradFiPerpsAgreement()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L654) | :closed_lock_with_key: | POST | `fapi/v1/stock/contract` | -| [testOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L658) | :closed_lock_with_key: | POST | `fapi/v1/order/test` | -| [submitNewAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L670) | :closed_lock_with_key: | POST | `fapi/v1/algoOrder` | -| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L677) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOrder` | -| [cancelAllAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L683) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOpenOrders` | -| [getAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L689) | :closed_lock_with_key: | GET | `fapi/v1/algoOrder` | -| [getOpenAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L695) | :closed_lock_with_key: | GET | `fapi/v1/openAlgoOrders` | -| [getAllAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L701) | :closed_lock_with_key: | GET | `fapi/v1/allAlgoOrders` | -| [getAllConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L713) | | GET | `fapi/v1/convert/exchangeInfo` | -| [submitConvertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L720) | :closed_lock_with_key: | POST | `fapi/v1/convert/getQuote` | -| [acceptConvertQuote()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L726) | :closed_lock_with_key: | POST | `fapi/v1/convert/acceptQuote` | -| [getConvertOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L734) | :closed_lock_with_key: | GET | `fapi/v1/convert/orderStatus` | -| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L747) | :closed_lock_with_key: | GET | `fapi/v1/pmAccountInfo` | -| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L764) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/ifNewUser` | -| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L777) | :closed_lock_with_key: | POST | `fapi/v1/apiReferral/customization` | -| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L790) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/customization` | -| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L807) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/userCustomization` | -| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L816) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/overview` | -| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L825) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/tradeVol` | -| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L842) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/rebateVol` | -| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L859) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/traderSummary` | -| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L881) | | POST | `fapi/v1/listenKey` | -| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L885) | | PUT | `fapi/v1/listenKey` | -| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L889) | | DELETE | `fapi/v1/listenKey` | +| [getFuturesTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L608) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn` | +| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L615) | :closed_lock_with_key: | GET | `fapi/v1/income/asyn/id` | +| [getFuturesOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L621) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn` | +| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L628) | :closed_lock_with_key: | GET | `fapi/v1/order/asyn/id` | +| [getFuturesTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L634) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn` | +| [getFuturesTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L641) | :closed_lock_with_key: | GET | `fapi/v1/trade/asyn/id` | +| [setBNBBurnEnabled()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L647) | :closed_lock_with_key: | POST | `fapi/v1/feeBurn` | +| [getBNBBurnStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L653) | :closed_lock_with_key: | GET | `fapi/v1/feeBurn` | +| [signTradFiPerpsAgreement()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L659) | :closed_lock_with_key: | POST | `fapi/v1/stock/contract` | +| [testOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L663) | :closed_lock_with_key: | POST | `fapi/v1/order/test` | +| [submitNewAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L675) | :closed_lock_with_key: | POST | `fapi/v1/algoOrder` | +| [cancelAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L682) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOrder` | +| [cancelAllAlgoOpenOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L688) | :closed_lock_with_key: | DELETE | `fapi/v1/algoOpenOrders` | +| [getAlgoOrder()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L694) | :closed_lock_with_key: | GET | `fapi/v1/algoOrder` | +| [getOpenAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L700) | :closed_lock_with_key: | GET | `fapi/v1/openAlgoOrders` | +| [getAllAlgoOrders()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L706) | :closed_lock_with_key: | GET | `fapi/v1/allAlgoOrders` | +| [getAllConvertPairs()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L718) | | GET | `fapi/v1/convert/exchangeInfo` | +| [submitConvertQuoteRequest()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L725) | :closed_lock_with_key: | POST | `fapi/v1/convert/getQuote` | +| [acceptConvertQuote()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L731) | :closed_lock_with_key: | POST | `fapi/v1/convert/acceptQuote` | +| [getConvertOrderStatus()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L739) | :closed_lock_with_key: | GET | `fapi/v1/convert/orderStatus` | +| [getPortfolioMarginProAccountInfo()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L752) | :closed_lock_with_key: | GET | `fapi/v1/pmAccountInfo` | +| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L769) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/ifNewUser` | +| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L782) | :closed_lock_with_key: | POST | `fapi/v1/apiReferral/customization` | +| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L795) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/customization` | +| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L812) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/userCustomization` | +| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L821) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/overview` | +| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L830) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/tradeVol` | +| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L847) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/rebateVol` | +| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L864) | :closed_lock_with_key: | GET | `fapi/v1/apiReferral/traderSummary` | +| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L886) | | POST | `fapi/v1/listenKey` | +| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L890) | | PUT | `fapi/v1/listenKey` | +| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/usdm-client.ts#L894) | | DELETE | `fapi/v1/listenKey` | # coinm-client.ts @@ -755,25 +758,25 @@ This table includes all endpoints from the official Exchange API docs and corres | [getNotionalAndLeverageBrackets()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L481) | :closed_lock_with_key: | GET | `dapi/v2/leverageBracket` | | [getCurrentPositionMode()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L490) | :closed_lock_with_key: | GET | `dapi/v1/positionSide/dual` | | [getIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L498) | :closed_lock_with_key: | GET | `dapi/v1/income` | -| [getDownloadIdForFuturesTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L502) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn` | -| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L512) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn/id` | -| [getDownloadIdForFuturesOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L518) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn` | -| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L528) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn/id` | -| [getDownloadIdForFuturesTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L534) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn` | -| [getFuturesTradeHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L544) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn/id` | -| [getClassicPortfolioMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L556) | :closed_lock_with_key: | GET | `dapi/v1/pmAccountInfo` | -| [getClassicPortfolioMarginNotionalLimits()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L565) | :closed_lock_with_key: | GET | `dapi/v1/pmExchangeInfo` | -| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L584) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/ifNewUser` | -| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L597) | :closed_lock_with_key: | POST | `dapi/v1/apiReferral/customization` | -| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L610) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/customization` | -| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L627) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/userCustomization` | -| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L636) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/overview` | -| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L645) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/tradeVol` | -| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L662) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/rebateVol` | -| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L679) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/traderSummary` | -| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L699) | | POST | `dapi/v1/listenKey` | -| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L703) | | PUT | `dapi/v1/listenKey` | -| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L707) | | DELETE | `dapi/v1/listenKey` | +| [getDownloadIdForFuturesTransactionHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L507) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn` | +| [getFuturesTransactionHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L517) | :closed_lock_with_key: | GET | `dapi/v1/income/asyn/id` | +| [getDownloadIdForFuturesOrderHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L523) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn` | +| [getFuturesOrderHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L533) | :closed_lock_with_key: | GET | `dapi/v1/order/asyn/id` | +| [getDownloadIdForFuturesTradeHistory()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L539) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn` | +| [getFuturesTradeHistoryDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L549) | :closed_lock_with_key: | GET | `dapi/v1/trade/asyn/id` | +| [getClassicPortfolioMarginAccount()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L561) | :closed_lock_with_key: | GET | `dapi/v1/pmAccountInfo` | +| [getClassicPortfolioMarginNotionalLimits()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L570) | :closed_lock_with_key: | GET | `dapi/v1/pmExchangeInfo` | +| [getBrokerIfNewFuturesUser()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L589) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/ifNewUser` | +| [setBrokerCustomIdForClient()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L602) | :closed_lock_with_key: | POST | `dapi/v1/apiReferral/customization` | +| [getBrokerClientCustomIds()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L615) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/customization` | +| [getBrokerUserCustomId()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L632) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/userCustomization` | +| [getBrokerRebateDataOverview()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L641) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/overview` | +| [getBrokerUserTradeVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L650) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/tradeVol` | +| [getBrokerRebateVolume()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L667) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/rebateVol` | +| [getBrokerTradeDetail()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L684) | :closed_lock_with_key: | GET | `dapi/v1/apiReferral/traderSummary` | +| [getFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L704) | | POST | `dapi/v1/listenKey` | +| [keepAliveFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L708) | | PUT | `dapi/v1/listenKey` | +| [closeFuturesUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/coinm-client.ts#L712) | | DELETE | `dapi/v1/listenKey` | # portfolio-client.ts @@ -872,22 +875,22 @@ This table includes all endpoints from the official Exchange API docs and corres | [autoCollectFunds()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L761) | :closed_lock_with_key: | POST | `papi/v1/auto-collection` | | [transferAssetFuturesMargin()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L774) | :closed_lock_with_key: | POST | `papi/v1/asset-collection` | | [transferBNB()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L784) | :closed_lock_with_key: | POST | `papi/v1/bnb-transfer` | -| [getUMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L793) | :closed_lock_with_key: | GET | `papi/v1/um/income` | -| [getCMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L799) | :closed_lock_with_key: | GET | `papi/v1/cm/income` | -| [getUMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L805) | :closed_lock_with_key: | GET | `papi/v1/um/account` | -| [getCMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L812) | :closed_lock_with_key: | GET | `papi/v1/cm/account` | -| [getUMAccountConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L819) | :closed_lock_with_key: | GET | `papi/v1/um/accountConfig` | -| [getUMSymbolConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L823) | :closed_lock_with_key: | GET | `papi/v1/um/symbolConfig` | -| [getUMAccountV2()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L829) | :closed_lock_with_key: | GET | `papi/v2/um/account` | -| [getUMTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L836) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn` | -| [getUMTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L846) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn/id` | -| [getUMOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L852) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn` | -| [getUMOrderDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L862) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn/id` | -| [getUMTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L868) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn` | -| [getUMTransactionDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L878) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn/id` | -| [getPMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L917) | | POST | `papi/v1/listenKey` | -| [keepAlivePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L921) | | PUT | `papi/v1/listenKey` | -| [closePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L925) | | DELETE | `papi/v1/listenKey` | +| [getUMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L797) | :closed_lock_with_key: | GET | `papi/v1/um/income` | +| [getCMIncomeHistory()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L807) | :closed_lock_with_key: | GET | `papi/v1/cm/income` | +| [getUMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L813) | :closed_lock_with_key: | GET | `papi/v1/um/account` | +| [getCMAccount()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L820) | :closed_lock_with_key: | GET | `papi/v1/cm/account` | +| [getUMAccountConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L827) | :closed_lock_with_key: | GET | `papi/v1/um/accountConfig` | +| [getUMSymbolConfig()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L831) | :closed_lock_with_key: | GET | `papi/v1/um/symbolConfig` | +| [getUMAccountV2()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L837) | :closed_lock_with_key: | GET | `papi/v2/um/account` | +| [getUMTradeHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L844) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn` | +| [getUMTradeDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L854) | :closed_lock_with_key: | GET | `papi/v1/um/trade/asyn/id` | +| [getUMOrderHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L860) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn` | +| [getUMOrderDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L870) | :closed_lock_with_key: | GET | `papi/v1/um/order/asyn/id` | +| [getUMTransactionHistoryDownloadId()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L876) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn` | +| [getUMTransactionDownloadLink()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L886) | :closed_lock_with_key: | GET | `papi/v1/um/income/asyn/id` | +| [getPMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L925) | | POST | `papi/v1/listenKey` | +| [keepAlivePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L929) | | PUT | `papi/v1/listenKey` | +| [closePMUserDataListenKey()](https://github.com/sieblyio/binance/blob/master/src/portfolio-client.ts#L933) | | DELETE | `papi/v1/listenKey` | # websocket-api-client.ts diff --git a/examples/apidoc/MainClient/closeMarginUserDataListenKeyV2.js b/examples/apidoc/MainClient/closeMarginUserDataListenKeyV2.js new file mode 100644 index 00000000..5a07b987 --- /dev/null +++ b/examples/apidoc/MainClient/closeMarginUserDataListenKeyV2.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v2/margin/listen-key +// METHOD: DELETE +// PUBLIC: YES + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.closeMarginUserDataListenKeyV2(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/getMarginUserDataListenKeyV2.js b/examples/apidoc/MainClient/getMarginUserDataListenKeyV2.js new file mode 100644 index 00000000..2ad2cdc4 --- /dev/null +++ b/examples/apidoc/MainClient/getMarginUserDataListenKeyV2.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v2/margin/listen-key +// METHOD: POST +// PUBLIC: YES + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.getMarginUserDataListenKeyV2(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/examples/apidoc/MainClient/keepAliveMarginUserDataListenKeyV2.js b/examples/apidoc/MainClient/keepAliveMarginUserDataListenKeyV2.js new file mode 100644 index 00000000..4221436d --- /dev/null +++ b/examples/apidoc/MainClient/keepAliveMarginUserDataListenKeyV2.js @@ -0,0 +1,22 @@ +import { MainClient } from 'binance'; +// or, if require is preferred: +// const { MainClient } = require('binance'); + +// This example shows how to call this Binance API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "binance" for Binance exchange +// This Binance API SDK is available on npm via "npm install binance" +// ENDPOINT: sapi/v2/margin/listen-key?listenKey=${listenKey} +// METHOD: PUT +// PUBLIC: YES + +const client = new MainClient({ + api_key: 'insert_api_key_here', + api_secret: 'insert_api_secret_here', +}); + +client.keepAliveMarginUserDataListenKeyV2(params) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.error(error); + }); diff --git a/llms.txt b/llms.txt index d75d6186..8bd28118 100644 --- a/llms.txt +++ b/llms.txt @@ -3234,15 +3234,6 @@ High level summary for some of the available examples, but check the folder for - `rest-usdm-order.ts` Creates a single entry order using `submitNewOrder`. - `rest-usdm-order-sl.ts` Modifies a Hedge Mode LONG stop-loss order using Algo Service orders. -================ -File: examples/Rest/Futures/rest-future-bracket-order.ts -================ -import { - FuturesNewAlgoOrderParams, - NewFuturesOrderParams, - USDMClient, -} from '../../../src/index'; - ================ File: src/types/websockets/ws-api.ts ================ @@ -4195,24996 +4186,25078 @@ export interface WebsocketClientOptions extends WSClientConfigurableOptions { } ================ -File: src/types/portfolio-margin.ts +File: examples/Rest/Futures/rest-future-bracket-order.ts ================ -// Enums -export type PMStrategyType = - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; +import { + FuturesNewAlgoOrderParams, + NewFuturesOrderParams, + USDMClient, +} from '../../../src/index'; + +================ +File: src/websocket-api-client.ts +================ +import { + ExchangeInfo, + SpotAmendKeepPriorityResult, + SpotExecutionRulesResponse, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, +} from './types/spot'; +import { + WSAPIResponse, + WSAPIUserDataListenKeyRequest, +} from './types/websockets/ws-api'; +import { + WSAPIAccountCommissionWSAPIRequest, + WSAPIAccountInformationRequest, + WSAPIAllOrderListsRequest, + WSAPIAllOrdersRequest, + WSAPIAvgPriceRequest, + WSAPIBlockTradesHistoricalRequest, + WSAPIExchangeInfoRequest, + WSAPIExecutionRulesRequest, + WSAPIFuturesAlgoOrderCancelRequest, + WSAPIFuturesOrderBookRequest, + WSAPIFuturesOrderCancelRequest, + WSAPIFuturesOrderModifyRequest, + WSAPIFuturesOrderStatusRequest, + WSAPIFuturesPositionRequest, + WSAPIFuturesPositionV2Request, + WSAPIFuturesTickerBookRequest, + WSAPIFuturesTickerPriceRequest, + WSAPIKlinesRequest, + WSAPIMyAllocationsRequest, + WSAPIMyPreventedMatchesRequest, + WSAPIMyTradesRequest, + WSAPINewFuturesAlgoOrderRequest, + WSAPINewFuturesOrderRequest, + WSAPINewSpotOrderRequest, + WSAPIOpenOrdersCancelAllRequest, + WSAPIOpenOrdersStatusRequest, + WSAPIOrderAmendKeepPriorityRequest, + WSAPIOrderBookRequest, + WSAPIOrderCancelReplaceRequest, + WSAPIOrderCancelRequest, + WSAPIOrderListCancelRequest, + WSAPIOrderListPlaceOCORequest, + WSAPIOrderListPlaceOPOCORequest, + WSAPIOrderListPlaceOPORequest, + WSAPIOrderListPlaceOTOCORequest, + WSAPIOrderListPlaceOTORequest, + WSAPIOrderListPlaceRequest, + WSAPIOrderListStatusRequest, + WSAPIOrderStatusRequest, + WSAPIOrderTestRequest, + WSAPIRecvWindowTimestamp, + WSAPIReferencePriceCalculationRequest, + WSAPIReferencePriceRequest, + WSAPISOROrderPlaceRequest, + WSAPISOROrderTestRequest, + WSAPITicker24hrRequest, + WSAPITickerBookRequest, + WSAPITickerPriceRequest, + WSAPITickerRequest, + WSAPITickerTradingDayRequest, + WSAPITradesAggregateRequest, + WSAPITradesHistoricalRequest, + WSAPITradesRecentRequest, +} from './types/websockets/ws-api-requests'; +import { + WSAPIAccountCommission, + WSAPIAccountInformation, + WSAPIAggregateTrade, + WSAPIAllocation, + WSAPIAvgPrice, + WSAPIBlockTrade, + WSAPIBookTicker, + WSAPIFullTicker, + WSAPIFuturesAccountBalanceItem, + WSAPIFuturesAccountStatus, + WSAPIFuturesAlgoOrder, + WSAPIFuturesAlgoOrderCancelResponse, + WSAPIFuturesBookTicker, + WSAPIFuturesOrder, + WSAPIFuturesOrderBook, + WSAPIFuturesPosition, + WSAPIFuturesPositionV2, + WSAPIFuturesPriceTicker, + WSAPIKline, + WSAPIMiniTicker, + WSAPIOrder, + WSAPIOrderBook, + WSAPIOrderCancel, + WSAPIOrderCancelReplaceResponse, + WSAPIOrderListCancelResponse, + WSAPIOrderListPlaceResponse, + WSAPIOrderListStatusResponse, + WSAPIOrderTestResponse, + WSAPIOrderTestWithCommission, + WSAPIPreventedMatch, + WSAPIPriceTicker, + WSAPIRateLimit, + WSAPIServerTime, + WSAPISessionStatus, + WSAPISOROrderPlaceResponse, + WSAPISOROrderTestResponse, + WSAPISOROrderTestResponseWithCommission, + WSAPISpotOrderResponse, + WSAPITrade, +} from './types/websockets/ws-api-responses'; +import { WSClientConfigurableOptions } from './types/websockets/ws-general'; +import { DefaultLogger } from './util/logger'; +import { + isWSAPIWsKey, + isWsEventStreamTerminatedRaw, + neverGuard, +} from './util/typeGuards'; +import { + getTestnetWsKey, + WS_KEY_MAP, + WS_LOGGER_CATEGORY, + WSAPIWsKey, + WSAPIWsKeyFutures, + WSAPIWsKeyMain, + WsKey, +} from './util/websockets/websocket-util'; +import { WSConnectedResult } from './util/websockets/WsStore.types'; +import { WebsocketClient } from './websocket-client'; ⋮---- -export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures ⋮---- -export type PMPriceMatch = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; +/** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true + * + * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + */ + resubscribeUserDataStreamAfterReconnect: boolean; + + /** + * Default: 2 seconds + * + * Delay automatic userdata resubscribe by x seconds. + */ + resubscribeUserDataStreamDelaySeconds: number; + + /** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ + attachEventListeners: boolean; + + /** + * Default: false + * + * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. + * + * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. + */ + muteLatencyWarning: boolean; + + /** + * Default: true + * + * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. + */ + keepMarginListenTokenRefreshed: boolean; +} ⋮---- -export type PMSelfTradePreventionMode = - | 'NONE' - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH'; +/** + * Default: true + * + * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + */ ⋮---- -export type PMMarginOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; +/** + * Default: 2 seconds + * + * Delay automatic userdata resubscribe by x seconds. + */ ⋮---- -export type PMMarginSideEffectType = - | 'NO_SIDE_EFFECT' - | 'MARGIN_BUY' - | 'AUTO_REPAY' - | 'AUTO_BORROW_REPAY'; +/** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ ⋮---- -export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; +/** + * Default: false + * + * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. + * + * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. + */ ⋮---- -export interface NewPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; // Cannot be sent in Hedge Mode - price?: string; - newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ - newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK - priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD +/** + * Default: true + * + * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. + */ +⋮---- +/** + * Used to track that a connection had an active user data stream before it disconnected. + * + * Note: This is not the same as the "listenKey" WS API workflow (the listenKey workflow is deprecated). + * + * This does not return a listen key. This also does not require a regular "ping" on the listen key. + */ +interface ActiveUserDataStreamState { + subscribedAt: Date; + subscribeAttempt: number; + respawnTimeout?: ReturnType; + /** + * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. + */ + refreshTimeout?: ReturnType; + /** + * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream + */ + userDataStreamParameters?: unknown; } ⋮---- -positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode +/** + * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. + */ ⋮---- -reduceOnly?: boolean; // Cannot be sent in Hedge Mode +/** + * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream + */ ⋮---- -newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ -newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK -priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders +/** + * 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/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 + */ +export class WebsocketAPIClient ⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD +/** + * Minimal state store around automating sticky "userDataStream.subscribe" sessions + */ ⋮---- -export interface NewPortfolioUMOrderResponse { - clientOrderId: string; - cumQty: string; - cumQuote?: string; - executedQty: string; - orderId: number; - avgPrice?: string; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; - updateTime: number; - priceMatch: PMPriceMatch; -} +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -export interface NewPortfolioUMConditionalOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - strategyType: PMStrategyType; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - workingType?: PMWorkingType; - priceProtect?: boolean; - newClientStrategyId?: string; - stopPrice?: string; - activationPrice?: string; - callbackRate?: string; - priceMatch?: PMPriceMatch; - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; -} +public getWSClient(): WebsocketClient ⋮---- -export interface NewPortfolioConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate?: number; - priceMatch: PMPriceMatch; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -export type PortfolioUMAlgoType = 'CONDITIONAL'; +public async disconnectAll(): Promise ⋮---- -export interface NewPortfolioUMAlgoOrderReq { - algoType: PortfolioUMAlgoType; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - type: PMStrategyType; - timeInForce?: string; - quantity?: string; - price?: string; - triggerPrice?: string; - workingType?: PMWorkingType; - priceMatch?: PMPriceMatch; - closePosition?: string; - priceProtect?: string; - reduceOnly?: string; - activatePrice?: string; - callbackRate?: string; - clientAlgoId?: string; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: PMSelfTradePreventionMode; - goodTillDate?: number; -} +/* + * + * SPOT - General requests + * + */ ⋮---- -export interface PortfolioUMAlgoOrder { - algoId: number; - clientAlgoId: string; - algoType: string; - orderType: string; - symbol: string; - side: string; - positionSide: string; - timeInForce: string; - quantity: string; - algoStatus: string; - triggerPrice: string; - price: string; - icebergQuantity: string | null; - selfTradePreventionMode: string; - workingType: string; - priceMatch: string; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - activatePrice: string; - callbackRate: string; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; - actualOrderId?: string; - actualPrice?: string; - tpTriggerPrice?: string; - tpPrice?: string; - slTriggerPrice?: string; - slPrice?: string; - tpOrderType?: string; -} +/** + * Test connectivity to the WebSocket API + */ +testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> ⋮---- -export interface CancelPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; -} +/** + * Test connectivity to the WebSocket API and get the current server time + */ +getSpotServerTime( + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} +/** + * Query current exchange trading rules, rate limits, and symbol information + */ +getSpotExchangeInfo( + params?: WSAPIExchangeInfoRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { - code: number; - msg: string; -} +/* + * + * SPOT - Market data requests + * + */ ⋮---- -export interface QueryPortfolioUMAlgoOrderReq { - algoId?: number; - clientAlgoId?: string; -} +/** + * Get current order book + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getSpotOrderBook( + params: WSAPIOrderBookRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioAllUMAlgoOrdersReq { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface NewPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT'; -} +/** + * Get recent trades + * Note: If you need access to real-time trading activity, consider using WebSocket Streams + */ +getSpotRecentTrades( + params: WSAPITradesRecentRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioCMOrderResponse { - clientOrderId: string; - cumQty: string; - cumBase?: string; - executedQty: string; - orderId: number; - avgPrice?: string; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - pair: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +/** + * Get historical trades + * Note: If fromId is not specified, the most recent trades are returned + */ +getSpotHistoricalTrades( + params: WSAPITradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioCMConditionalOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - strategyType: PMStrategyType; - timeInForce?: string; - quantity?: string; - reduceOnly?: boolean; - price?: string; - workingType?: PMWorkingType; - priceProtect?: boolean; - newClientStrategyId?: string; - stopPrice?: string; - activationPrice?: string; - callbackRate?: string; -} +/** + * Get historical block trades + */ +getSpotHistoricalBlockTrades( + params: WSAPIBlockTradesHistoricalRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioCMConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - pair: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; -} +/** + * Get aggregate trades + * Note: An aggregate trade represents one or more individual trades that fill at the same time + */ +getSpotAggregateTrades( + params: WSAPITradesAggregateRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface MarginOrderFill { - price: string; - qty: string; - commission: string; - commissionAsset: string; -} +/** + * Get klines (candlestick bars) + * Note: If you need access to real-time kline updates, consider using WebSocket Streams + */ +getSpotKlines( + params: WSAPIKlinesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioMarginOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - type: PMMarginOrderType; - quantity?: string; - quoteOrderQty?: string; - price?: string; - stopPrice?: string; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - icebergQty?: string; - sideEffectType?: PMMarginSideEffectType; - timeInForce?: string; - selfTradePreventionMode?: PMSelfTradePreventionMode; - autoRepayAtCancel?: boolean; -} +/** + * Get klines (candlestick bars) optimized for presentation + * Note: This request is similar to klines, having the same parameters and response + */ +getSpotUIKlines( + params: WSAPIKlinesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioMarginOrderResponse { - symbol: string; - orderId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; - marginBuyBorrowAmount?: string; - marginBuyBorrowAsset?: string; - fills: MarginOrderFill[]; -} +/** + * Get current average price for a symbol + */ +getSpotAveragePrice( + params: WSAPIAvgPriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginOCOOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +/** + * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. + */ +getSpotExecutionRules( + params?: WSAPIExecutionRulesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginOCOOrderReport { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: 'BUY' | 'SELL'; - stopPrice?: string; -} +/** + * Query reference price for a symbol. + */ +getSpotReferencePrice( + params: WSAPIReferencePriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioMarginOCOReq { - symbol: string; - listClientOrderId?: string; - side: 'BUY' | 'SELL'; - quantity: string; - limitClientOrderId?: string; - price: string; - limitIcebergQty?: string; - stopClientOrderId?: string; - stopPrice: string; - stopLimitPrice?: string; - stopIcebergQty?: string; - stopLimitTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - sideEffectType?: PMMarginSideEffectType; -} +/** + * Query how reference price is calculated for a symbol. + */ +getSpotReferencePriceCalculation( + params: WSAPIReferencePriceCalculationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface NewPortfolioMarginOCOResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - marginBuyBorrowAmount?: string; - marginBuyBorrowAsset?: string; - orders: PortfolioMarginOCOOrder[]; - orderReports: PortfolioMarginOCOOrderReport[]; -} +/** + * Get 24-hour rolling window price change statistics + * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams + */ +getSpot24hrTicker( + params?: WSAPITicker24hrRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker.24hr', + params, + { authIsOptional: true }, + ); ⋮---- -// Add new interfaces for canceling UM orders -export interface CancelPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Get price change statistics for a trading day + */ +getSpotTradingDayTicker( + params: WSAPITickerTradingDayRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker.tradingDay', + params, + { authIsOptional: true }, + ); ⋮---- -export interface PortfolioUMCancelOrderResponse { - avgPrice?: string; - clientOrderId: string; - cumQty: string; - cumQuote?: string; - executedQty: string; - orderId: number; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +/** + * Get rolling window price change statistics with a custom window + * Note: Window size precision is limited to 1 minute + */ +getSpotTicker( + params: WSAPITickerRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'ticker', + params, + { authIsOptional: true }, + ); ⋮---- -export interface CancelPortfolioUMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/** + * Get the latest market price for a symbol + * Note: If you need access to real-time price updates, consider using WebSocket Streams + */ +getSpotSymbolPriceTicker( + params?: WSAPITickerPriceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMCancelConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +/** + * Get the current best price and quantity on the order book + * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams + */ +getSpotSymbolOrderBookTicker( + params?: WSAPITickerBookRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface CancelPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/* + * + * SPOT - Session authentication requests + * + * Note: authentication is automatic + * + */ ⋮---- -export interface PortfolioCMCancelOrderResponse { - avgPrice?: string; - clientOrderId: string; - cumQty: string; - cumBase?: string; - executedQty: string; - orderId: number; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - status: string; - symbol: string; - pair: string; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +getSpotSessionStatus( + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface CancelPortfolioCMConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/* + * + * SPOT - Trading requests + * + */ ⋮---- -export interface PortfolioCMCancelConditionalOrderResponse { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - timeInForce: string; - activatePrice?: string; - priceRate?: string; - bookTime: number; - updateTime: number; - workingType: PMWorkingType; - priceProtect: boolean; -} +/** + * Submit a spot order + */ +submitNewSpotOrder( + params: WSAPINewSpotOrderRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface CancelPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; -} +/** + * Test order placement + * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine + */ +testSpotOrder( + params: WSAPIOrderTestRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'order.test', + params, + ); ⋮---- -export interface PortfolioMarginCancelOrderResponse { - symbol: string; - orderId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; -} +/** + * Check execution status of an order + * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + */ +getSpotOrderStatus( + params: WSAPIOrderStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface CancelPortfolioMarginOCOReq { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; -} +/** + * Cancel an active order + * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + */ +cancelSpotOrder( + params: WSAPIOrderCancelRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginOCOCancelOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +/** + * Cancel an existing order and immediately place a new order + * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used + */ +cancelReplaceSpotOrder( + params: WSAPIOrderCancelReplaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginOCOCancelOrderReport { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: 'STOP_LOSS_LIMIT' | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; -} -⋮---- -export interface PortfolioMarginOCOCancelResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginOCOCancelOrderReport[]; -} +/** + * Reduce the quantity of an existing open order. + * + * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority + */ +amendSpotOrderKeepPriority( + params: WSAPIOrderAmendKeepPriorityRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginCancelAllOrdersOrderReport { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: PMMarginOrderType; - side: 'BUY' | 'SELL'; - stopPrice?: string; - icebergQty?: string; -} +/** + * Query execution status of all open orders + * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams + */ +getSpotOpenOrders( + params: WSAPIOpenOrdersStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioMarginCancelAllOrdersOCOReport { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOCancelOrder[]; - orderReports: PortfolioMarginCancelAllOrdersOrderReport[]; -} +/** + * Cancel all open orders on a symbol + * Note: This includes orders that are part of an order list + */ +cancelAllSpotOpenOrders( + params: WSAPIOpenOrdersCancelAllRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'openOrders.cancelAll', + params, + ); ⋮---- -export type PortfolioMarginCancelAllOrdersResponse = - | PortfolioMarginCancelAllOrdersOrderReport - | PortfolioMarginCancelAllOrdersOCOReport; +/** + * Place a new order list + * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead + */ +placeSpotOrderList( + params: WSAPIOrderListPlaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface ModifyPortfolioUMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - priceMatch?: PMPriceMatch; - modifyId?: number; -} +/** + * Place a new OCO (One-Cancels-the-Other) order list + * Note: Activation of one order immediately cancels the other + */ +placeSpotOCOOrderList( + params: WSAPIOrderListPlaceOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMModifyOrderResponse { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice?: string; - origQty: string; - executedQty: string; - cumQty: string; - cumQuote?: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - origType: 'LIMIT'; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - updateTime: number; - priceMatch: PMPriceMatch; - modifyId?: number; -} +/** + * Place a new OTO (One-Triggers-the-Other) order list + * Note: The pending order is placed only when the working order is fully filled + */ +placeSpotOTOOrderList( + params: WSAPIOrderListPlaceOTORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface ModifyPortfolioCMOrderReq { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: string; - price: string; - orderId?: number; - origClientOrderId?: string; - modifyId?: number; -} +/** + * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list + * Note: The pending orders are placed only when the working order is fully filled + */ +placeSpotOTOCOOrderList( + params: WSAPIOrderListPlaceOTOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioCMModifyOrderResponse { - orderId: number; - symbol: string; - pair: string; - status: string; - clientOrderId: string; - price: string; - avgPrice?: string; - origQty: string; - executedQty: string; - cumQty: string; - cumBase?: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - origType: 'LIMIT'; - updateTime: number; - modifyId?: number; -} +/** + * Place a new OPO (One-Pays-the-Other) order list + * Note: One order pays for the other - when the working order is filled, the pending order is placed + */ +placeSpotOPOOrderList( + params: WSAPIOrderListPlaceOPORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioUMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Place a new OPOCO (One-Pays-One-Cancels-the-Other) order list + * Note: Combines OPO and OCO - working order pays for two pending orders, one cancels the other + */ +placeSpotOPOCOOrderList( + params: WSAPIOrderListPlaceOPOCORequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMOrder { - avgPrice: string; - clientOrderId: string; - cumQuote: string; - executedQty: string; - orderId: number; - origQty: string; - origType: 'LIMIT' | 'MARKET'; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - status: string; - symbol: string; - time: number; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} +/** + * Check execution status of an order list + * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used + */ +getSpotOrderListStatus( + params: WSAPIOrderListStatusRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioAllUMOrdersReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Cancel an active order list + * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used + */ +cancelSpotOrderList( + params: WSAPIOrderListCancelRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioUMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Query execution status of all open order lists + * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams + */ +getSpotOpenOrderLists( + params: WSAPIRecvWindowTimestamp, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioAllUMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface PortfolioUMConditionalOrder { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'LONG' | 'SHORT' | 'BOTH'; - stopPrice?: string; - symbol: string; - orderId?: number; - status?: string; - bookTime: number; - updateTime: number; - triggerTime?: number; - timeInForce: string; - type?: 'MARKET' | 'LIMIT'; - activatePrice?: string; - priceRate?: string; - selfTradePreventionMode: PMSelfTradePreventionMode; - goodTillDate: number; - priceMatch: PMPriceMatch; -} -⋮---- -export interface QueryPortfolioUMOpenConditionalOrderReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/** + * Place a new order using Smart Order Routing (SOR) + * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported + */ +placeSpotSOROrder( + params: WSAPISOROrderPlaceRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioUMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/** + * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) + * Note: Creates and validates a new order but does not send it into the matching engine + */ +testSpotSOROrder( + params: WSAPISOROrderTestRequest, + wsKey?: WSAPIWsKeyMain, + ): Promise< + WSAPIResponse< + WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission + > + > { + return this.wsClient.sendWSAPIRequest( + wsKey || WS_KEY_MAP.mainWSAPI, + 'sor.order.test', + params, + ); ⋮---- -export interface QueryPortfolioCMOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/* + * + * SPOT - Account requests + * + */ ⋮---- -export interface PortfolioCMOrder { - avgPrice: string; - clientOrderId: string; - cumBase: string; - executedQty: string; - orderId: number; - origQty: string; - origType: 'LIMIT' | 'MARKET'; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - status: string; - symbol: string; - pair: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - time: number; - timeInForce: string; - type: 'LIMIT' | 'MARKET'; - updateTime: number; -} +/** + * Query information about your account, including balances + * Note: Weight: 20 + */ +getSpotAccountInformation( + params: WSAPIAccountInformationRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioAllCMOrdersReq { - symbol: string; - pair?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Query your current unfilled order count for all intervals + * Note: Weight: 40 + */ +getSpotOrderRateLimits( + params: WSAPIRecvWindowTimestamp, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioCMOpenOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/** + * Query information about all your orders – active, canceled, filled – filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrders( + params: WSAPIAllOrdersRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioAllCMConditionalOrdersReq { - symbol?: string; - strategyId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Query information about all your order lists, filtered by time range + * Note: Weight: 20 + */ +getSpotAllOrderLists( + params: WSAPIAllOrderListsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioCMConditionalOrder { - newClientStrategyId: string; - strategyId: number; - strategyStatus: string; - strategyType: PMStrategyType; - origQty: string; - price: string; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - stopPrice?: string; - symbol: string; - orderId?: number; - status?: string; - bookTime: number; - updateTime: number; - triggerTime?: number; - timeInForce: string; - type?: 'MARKET' | 'LIMIT'; - activatePrice?: string; - priceRate?: string; - workingType: PMWorkingType; - priceProtect: boolean; -} +/** + * Query information about all your trades, filtered by time range + * Note: Weight: 20 + */ +getSpotMyTrades( + params: WSAPIMyTradesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioCMConditionalOrderHistoryReq { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -} +/** + * Displays the list of orders that were expired due to STP + * Note: Weight varies based on query type (2-20) + */ +getSpotPreventedMatches( + params: WSAPIMyPreventedMatchesRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioCMConditionalHistoryOrder - extends PortfolioCMConditionalOrder { - priceMatch: PMPriceMatch; -} +/** + * Retrieves allocations resulting from SOR order placement + * Note: Weight: 20 + */ +getSpotAllocations( + params: WSAPIMyAllocationsRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface QueryPortfolioUMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Get current account commission rates + * Note: Weight: 20 + */ +getSpotAccountCommission( + params: WSAPIAccountCommissionWSAPIRequest, + wsKey?: WSAPIWsKeyMain, +): Promise> ⋮---- -export interface PortfolioUMForceOrder { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQuote: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - origType: 'LIMIT'; - time: number; - updateTime: number; -} +/* + * + * FUTURES - Market data requests + * + */ ⋮---- -export interface QueryPortfolioCMForceOrdersReq { - symbol?: string; - autoCloseType?: PMAutoCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Get current order book for futures + * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + */ +getFuturesOrderBook( + params: WSAPIFuturesOrderBookRequest, +): Promise> ⋮---- -export interface PortfolioCMForceOrder { - orderId: number; - symbol: string; - pair: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumBase: string; - timeInForce: string; - type: 'LIMIT'; - reduceOnly: boolean; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - origType: 'LIMIT'; - time: number; - updateTime: number; -} -⋮---- -export interface QueryPortfolioUMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Get latest price for a futures symbol or symbols + * Note: If symbol is not provided, prices for all symbols will be returned + */ +getFuturesSymbolPriceTicker( + params?: WSAPIFuturesTickerPriceRequest, + ): Promise< + WSAPIResponse + > { + return this.wsClient.sendWSAPIRequest( + WS_KEY_MAP.usdmWSAPI, + 'ticker.price', + params, + { authIsOptional: true }, + ); ⋮---- -export interface PortfolioUMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +/** + * Get best price/qty on the order book for a futures symbol or symbols + * Note: If symbol is not provided, bookTickers for all symbols will be returned + */ +getFuturesSymbolOrderBookTicker( + params?: WSAPIFuturesTickerBookRequest, +): Promise> ⋮---- -export interface PortfolioUMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioUMOrderAmendment; - priceMatch: PMPriceMatch; - modifyId?: number; -} +/* + * + * FUTURES - Trading requests + * + */ ⋮---- -export interface QueryPortfolioCMOrderAmendmentReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +/** + * Submit a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +submitNewFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPINewFuturesOrderRequest, +): Promise> ⋮---- -export interface PortfolioCMOrderAmendment { - price: { - before: string; - after: string; - }; - origQty: { - before: string; - after: string; - }; - count: number; -} +/** + * Modify an existing futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +modifyFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderModifyRequest, +): Promise> ⋮---- -export interface PortfolioCMOrderModificationHistory { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: PortfolioCMOrderAmendment; - modifyId?: number; -} +/** + * Cancel a futures order + * + * This endpoint is used for both USDM and COINM futures. + */ +cancelFuturesOrder( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderCancelRequest, +): Promise> ⋮---- -export interface QueryPortfolioMarginForceOrdersReq { - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 -} +/** + * Query futures order status + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesOrderStatus( + market: 'usdm' | 'coinm', + params: WSAPIFuturesOrderStatusRequest, +): Promise> ⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 +/** + * Get current position information (V2) + * Note: Only symbols that have positions or open orders will be returned + */ +getFuturesPositionV2( + params: WSAPIFuturesPositionV2Request, +): Promise> ⋮---- -export interface PortfolioMarginForceOrder { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - updatedTime: number; -} +/** + * Get current position information + * Note: Only symbols that have positions or open orders will be returned + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesPosition( + market: 'usdm' | 'coinm', + params: WSAPIFuturesPositionRequest, +): Promise> ⋮---- -export interface QueryPortfolioUMTradesReq { - symbol: string; - startTime?: number; - endTime?: number; - fromId?: number; // Trade id to fetch from. Default gets most recent trades - limit?: number; // Default 500; max 1000 -} +/** + * Send in a new algo order + * + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Algo-Order + */ +submitNewFuturesAlgoOrder( + params: WSAPINewFuturesAlgoOrderRequest, +): Promise> ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +/** + * Cancel an active algo order. + * + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order + * @param params + */ +cancelFuturesAlgoOrder( + params: WSAPIFuturesAlgoOrderCancelRequest, +): Promise> ⋮---- -export interface PortfolioUMTrade { - symbol: string; - id: number; - orderId: number; - side: 'BUY' | 'SELL'; - price: string; - qty: string; - realizedPnl: string; - quoteQty: string; - commission: string; - commissionAsset: string; - time: number; - buyer: boolean; - maker: boolean; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - pair?: string; - baseQty?: string; - marginAsset?: string; -} +/* + * + * FUTURES - Account requests + * + */ ⋮---- -export interface QueryPortfolioCMTradesReq { - symbol?: string; - pair?: string; - startTime?: number; - endTime?: number; - fromId?: number; // Trade id to fetch from. Default gets most recent trades - limit?: number; // Default 50; max 1000 -} +/** + * Get account balance information (V2) + * Note: Returns balance information for all assets + */ +getFuturesAccountBalanceV2( + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- -fromId?: number; // Trade id to fetch from. Default gets most recent trades -limit?: number; // Default 50; max 1000 +/** + * Get account balance information + * Note: Returns balance information for all assets + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesAccountBalance( + market: 'usdm' | 'coinm', + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- -export interface PortfolioCMTrade { - symbol: string; - id: number; - orderId: number; - pair: string; - side: 'BUY' | 'SELL'; - price: string; - qty: string; - realizedPnl: string; - marginAsset: string; - baseQty: string; - commission: string; - commissionAsset: string; - time: number; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - buyer: boolean; - maker: boolean; - quoteQty?: string; -} -⋮---- -export interface PortfolioADLQuantile { - LONG: number; - SHORT: number; - BOTH?: number; // For one-way mode or isolated margin in hedge mode - HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) -} +/** + * Get account information (V2) + * Note: Returns detailed account information including positions and assets + */ +getFuturesAccountStatusV2( + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- -BOTH?: number; // For one-way mode or isolated margin in hedge mode -HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) +/** + * Get account information + * Note: Returns detailed account information including positions and assets + * + * This endpoint is used for both USDM and COINM futures. + */ +getFuturesAccountStatus( + market: 'usdm' | 'coinm', + params: WSAPIRecvWindowTimestamp, +): Promise> ⋮---- -export interface QueryPortfolioMarginOrderReq { - symbol: string; - orderId?: number; - origClientOrderId?: string; -} +/* + * + * User data stream requests + * + */ ⋮---- -export interface PortfolioMarginOrder { - clientOrderId: string; - cummulativeQuoteQty: string; - executedQty: string; - icebergQty: string; - isWorking: boolean; - orderId: number; - origQty: string; - price: string; - side: 'BUY' | 'SELL'; - status: string; - stopPrice: string; - symbol: string; - time: number; - timeInForce: string; - type: PMMarginOrderType; - updateTime: number; - accountId: number; - selfTradePreventionMode: PMSelfTradePreventionMode; - preventedMatchId: number | null; - preventedQuantity: string | null; -} +/** + * Start the user data stream for an apiKey (passed as param). + * + * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. + * + * @param params + * @param wsKey + * @returns listenKey + */ +startUserDataStreamForKey( + params: { apiKey: string }, + wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, +): Promise> ⋮---- -limit?: number; // Default 500; max 500 +/** + * Stop the user data stream listen key. + * + * @param params + * @param wsKey + * @returns + */ +stopUserDataStreamForKey( + params: WSAPIUserDataListenKeyRequest, + wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, +): Promise> ⋮---- -export interface QueryPortfolioMarginOCOReq { - orderListId?: number; // Either orderListId or origClientOrderId must be provided - origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided -} +/** + * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. + * + * @param wsKey + */ +clearUserDataStreamTimers(wsKey: WSAPIWsKey) ⋮---- -orderListId?: number; // Either orderListId or origClientOrderId must be provided -origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +// Just in case the refresh timer is still running +// Harmless given one connection, but still unnecessary ⋮---- -export interface PortfolioMarginOCOQueryOrder { - symbol: string; - orderId: number; - clientOrderId: string; -} +/** + * Request user data stream subscription on the currently authenticated connection. + * + * If reconnected, this will automatically resubscribe unless you unsubscribe manually. + */ +async subscribeUserDataStream( + wsKey: WSAPIWsKey, + isRefreshingToken: boolean = false, +): Promise | WSConnectedResult | undefined> ⋮---- -export interface PortfolioMarginOCO { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: PortfolioMarginOCOQueryOrder[]; -} +// User data stream works differently for margin, since Feb 2026, via a listen token mechanic ⋮---- -export interface QueryPortfolioMarginAllOCOReq { - fromId?: number; // If supplied, neither startTime or endTime can be provided - startTime?: number; - endTime?: number; - limit?: number; // Default 500; max 500 -} +// validity: 30 * 1000, // milliseconds (30 secs) +// validity: 5 * 60 * 1000, // milliseconds (5 mins ) ⋮---- -fromId?: number; // If supplied, neither startTime or endTime can be provided +// Set respawn timer, to automatically fetch and sub to new token before expiry. Should be seamless on existing connection. ⋮---- -limit?: number; // Default 500; max 500 +// try to respawn 30 seconds before expiration ⋮---- -export interface QueryPortfolioMarginTradesReq { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; // TradeId to fetch from. Default gets most recent trades - limit?: number; // Default 500; max 1000 -} +// for Ed25519 keys, no signature is needed, we should already be authenticated in session ⋮---- -fromId?: number; // TradeId to fetch from. Default gets most recent trades -limit?: number; // Default 500; max 1000 +// for HMAC & RSA keys, request will be signed and sent to a dedicated topic ⋮---- -export interface PortfolioMarginTrade { - commission: string; - commissionAsset: string; - id: number; - isBestMatch: boolean; - isBuyer: boolean; - isMaker: boolean; - orderId: number; - price: string; - qty: string; - symbol: string; - time: number; -} +// Used to track whether this connection had the general "userDataStream.subscribe" called. +// Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. ⋮---- -export interface PortfolioMarginRepayDebtReq { - asset: string; - amount?: string; - specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas -} +/** + * Unsubscribe from the user data stream subscription on the currently authenticated connection. + * + * If reconnected, this will also stop it from automatically resubscribing after reconnect. + */ +unsubscribeUserDataStream( + wsKey: WSAPIWsKey, +): Promise void; + onpong?: (event: unknown) => void; + wsKey?: WsKey | string; +}; ⋮---- -export interface GetMarginInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; // Currently querying page. Start from 1. Default: 1 - size?: number; // Default: 10, Max: 100 - archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +export declare interface WebsocketClientV1 { + on(event: 'reply', listener: (event: WsResponse) => void): this; + + on(event: 'message', listener: (event: WsRawMessage) => void): this; + + on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; + + on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; + + on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; + + on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; + + on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; } ⋮---- -current?: number; // Currently querying page. Start from 1. Default: 1 -size?: number; // Default: 10, Max: 100 -archived?: boolean; // Default: false. Set to true for archived data from 6 months ago -⋮---- -export type PMInterestType = - | 'PERIODIC' // interest charged per hour - | 'ON_BORROW' // first interest charged on borrow - | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB - | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB - | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest +on(event: 'reply', listener: (event: WsResponse) ⋮---- -| 'PERIODIC' // interest charged per hour -| 'ON_BORROW' // first interest charged on borrow -| 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB -| 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB -| 'PORTFOLIO'; // Portfolio Margin negative balance daily interest +on(event: 'message', listener: (event: WsRawMessage) ⋮---- -export interface PortfolioMarginInterestRecord { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset: string; - principal: string; - interest: string; - interestRate: string; - type: PMInterestType; -} +on( + event: 'formattedMessage', + listener: (event: WsFormattedMessage) => void, + ): this; ⋮---- -export interface GetPortfolioInterestHistoryReq { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; // Default: 10, Max: 100 -} +on( + event: 'formattedUserDataMessage', + listener: (event: WsUserDataEvents) => void, + ): this; ⋮---- -size?: number; // Default: 10, Max: 100 +on( + event: 'error', + listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, + ): this; ⋮---- -export interface PortfolioNegativeBalanceInterestRecord { - asset: string; - interest: string; // interest amount - interestAccuredTime: number; - interestRate: string; // daily interest rate - principal: string; -} +on( + event: 'open' | 'reconnected', + listener: (event: { + wsKey: WsKey; + ws: WebSocket.Event; + event?: any; + }) => void, + ): this; ⋮---- -interest: string; // interest amount +on( + event: 'reconnecting' | 'close', + listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, + ): this; ⋮---- -interestRate: string; // daily interest rate +/** + * @deprecated This legacy websocket client creates one websocket connection per topic. + * + * If subscribing to a lot of topics, consider using the new multiplex `WebsocketClient`. + * + * To split your topics into smaller groups (one connection per group), simply make multiple multiplex WebsocketClient instances. + */ +export class WebsocketClientV1 extends EventEmitter ⋮---- -export type UMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'SPECIAL_FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR' - | 'REFERRAL_KICKBACK' - | 'COMMISSION_REBATE' - | 'API_REBATE' - | 'CONTEST_REWARD' - | 'CROSS_COLLATERAL_TRANSFER' - | 'OPTIONS_PREMIUM_FEE' - | 'OPTIONS_SETTLE_PROFIT' - | 'INTERNAL_TRANSFER' - | 'AUTO_EXCHANGE' - | 'DELIVERED_SETTELMENT' - | 'COIN_SWAP_DEPOSIT' - | 'COIN_SWAP_WITHDRAW' - | 'POSITION_LIMIT_INCREASE_FEE'; +constructor( + options: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, +) ⋮---- -export interface QueryPortfolioUMIncomeReq { - symbol?: string; - incomeType?: UMIncomeType; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 100; max 1000 -} +// Some defaults: ⋮---- -limit?: number; // Default 100; max 1000 +// Automatically send an authentication op/request after a connection opens, for private connections. ⋮---- -export interface PortfolioUMIncome { - symbol: string; // trade symbol, if existing - incomeType: UMIncomeType; - income: string; // income amount - asset: string; // income asset - info: string; // extra information - time: number; - tranId: string; // transaction id - tradeId: string; // trade id, if existing -} +// Individual requests require a signature ⋮---- -symbol: string; // trade symbol, if existing +// add default error handling so this doesn't crash node (if the user didn't set a handler) ⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information +private getRestClientOptions(): RestClientOptions ⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing +public connectToWsUrl( + url: string, + wsKey?: WsKey | string, + forceNewConnection?: boolean, +): WebSocket ⋮---- -export type CMIncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'FUNDING_FEE' - | 'REALIZED_PNL' - | 'COMMISSION' - | 'INSURANCE_CLEAR' - | 'DELIVERED_SETTELMENT'; +// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node ⋮---- -export interface QueryPortfolioCMIncomeReq { - symbol?: string; - incomeType?: CMIncomeType; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 100; max 1000 -} +// Add ws connection with key to store ⋮---- -limit?: number; // Default 100; max 1000 +public tryWsSend(wsKey: WsKey | string, wsMessage: string) ⋮---- -export interface PortfolioCMIncome { - symbol: string; // trade symbol, if existing - incomeType: CMIncomeType; - income: string; // income amount - asset: string; // income asset - info: string; // extra information - time: number; - tranId: string; // transaction id - tradeId: string; // trade id, if existing -} +public tryWsPing(wsKey: WsKey | string) ⋮---- -symbol: string; // trade symbol, if existing +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -income: string; // income amount -asset: string; // income asset -info: string; // extra information +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -tranId: string; // transaction id -tradeId: string; // trade id, if existing +private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) ⋮---- -export interface PortfolioUMAccountAsset { - asset: string; // asset name - crossWalletBalance: string; // wallet balance - crossUnPnl: string; // unrealized profit - maintMargin: string; // maintenance margin required - initialMargin: string; // total initial margin required with current mark price - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - updateTime: number; // last update time -} +private onWsClose( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + wsUrl: string, +) ⋮---- -asset: string; // asset name -crossWalletBalance: string; // wallet balance -crossUnPnl: string; // unrealized profit -maintMargin: string; // maintenance margin required -initialMargin: string; // total initial margin required with current mark price -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -updateTime: number; // last update time +// Clear any timers before we initiate revival ⋮---- -export interface PortfolioUMAccountPosition { - symbol: string; // symbol name - initialMargin: string; // initial margin required with current mark price - maintMargin: string; // maintenance margin required - unrealizedProfit: string; // unrealized profit - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - leverage: string; // current initial leverage - entryPrice: string; // average entry price - maxNotional: string; // maximum available notional with current leverage - bidNotional: string; // bids notional - askNotional: string; // ask notional - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side - positionAmt: string; // position amount - updateTime: number; // last update time -} +// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states ⋮---- -symbol: string; // symbol name -initialMargin: string; // initial margin required with current mark price -maintMargin: string; // maintenance margin required -unrealizedProfit: string; // unrealized profit -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -leverage: string; // current initial leverage -entryPrice: string; // average entry price -maxNotional: string; // maximum available notional with current leverage -bidNotional: string; // bids notional -askNotional: string; // ask notional -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side -positionAmt: string; // position amount -updateTime: number; // last update time +private onWsMessage( + event: WebSocket.MessageEvent, + wsKey: WsKey | string, + source: WsEventInternalSrc, +) ⋮---- -export interface PortfolioCMAccountAsset { - asset: string; // asset name - crossWalletBalance: string; // total wallet balance - crossUnPnl: string; // unrealized profit or loss - maintMargin: string; // maintenance margin - initialMargin: string; // total initial margin required with the latest mark price - positionInitialMargin: string; // positions' margin required with the latest mark price - openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price - updateTime: number; // last update time -} +// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e ⋮---- -asset: string; // asset name -crossWalletBalance: string; // total wallet balance -crossUnPnl: string; // unrealized profit or loss -maintMargin: string; // maintenance margin -initialMargin: string; // total initial margin required with the latest mark price -positionInitialMargin: string; // positions' margin required with the latest mark price -openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price -updateTime: number; // last update time +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn ⋮---- -export interface PortfolioCMAccountPosition { - symbol: string; // symbol name - positionAmt: string; // position amount - initialMargin: string; - maintMargin: string; - unrealizedProfit: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - leverage: string; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode - entryPrice: string; - maxQty: string; // maximum quantity of base asset - updateTime: number; -} +// emit a separate event for user data messages ⋮---- -symbol: string; // symbol name -positionAmt: string; // position amount +private sendPing(wsKey: WsKey | string, wsUrl: string) ⋮---- -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode +private onWsPing( + event: any, + wsKey: WsKey | string, + ws: WebSocket, + source: WsEventInternalSrc, +) ⋮---- -maxQty: string; // maximum quantity of base asset +private onWsPong( + event: any, + wsKey: WsKey | string, + source: WsEventInternalSrc, +) ⋮---- -export interface PortfolioUMAccountConfig { - feeTier: number; // account commission tier - canTrade: boolean; // if can trade - canDeposit: boolean; // if can transfer in asset - canWithdraw: boolean; // if can transfer out asset - dualSidePosition: boolean; - updateTime: number; // reserved property - multiAssetsMargin: boolean; - tradeGroupId: number; -} +/** + * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. + * If closed, trigger a reconnect immediately + */ +private executeReconnectableClose( + wsKey: WsKey | string, + reason: string, + wsUrl: string, +) ⋮---- -feeTier: number; // account commission tier -canTrade: boolean; // if can trade -canDeposit: boolean; // if can transfer in asset -canWithdraw: boolean; // if can transfer out asset +public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) ⋮---- -updateTime: number; // reserved property +public closeAll(shouldReconnectAfterClose?: boolean) ⋮---- -export interface PortfolioUMSymbolConfig { - symbol: string; - marginType: 'CROSSED' | 'ISOLATED'; - isAutoAddMargin: string; // "true" or "false" as string - leverage: number; - maxNotionalValue: string; -} +public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) ⋮---- -isAutoAddMargin: string; // "true" or "false" as string +private parseWsError( + context: string, + error: any, + wsKey: WsKey | string, + wsUrl: string, +) ⋮---- -export interface PortfolioUMAccountAssetV2 { - asset: string; // asset name - crossWalletBalance: string; // wallet balance - crossUnPnl: string; // unrealized profit - maintMargin: string; // maintenance margin required - initialMargin: string; // total initial margin required with current mark price - positionInitialMargin: string; // initial margin required for positions with current mark price - openOrderInitialMargin: string; // initial margin required for open orders with current mark price - updateTime: number; // last update time -} +private reconnectWithDelay( + wsKey: WsKey | string, + connectionDelayMs: number, + wsUrl: string, +) ⋮---- -asset: string; // asset name -crossWalletBalance: string; // wallet balance -crossUnPnl: string; // unrealized profit -maintMargin: string; // maintenance margin required -initialMargin: string; // total initial margin required with current mark price -positionInitialMargin: string; // initial margin required for positions with current mark price -openOrderInitialMargin: string; // initial margin required for open orders with current mark price -updateTime: number; // last update time +// We'll set a new one once the new stream respawns, with a diff listenKey in the key ⋮---- -export interface PortfolioUMAccountPositionV2 { - symbol: string; // symbol name - initialMargin: string; // initial margin required with current mark price - maintMargin: string; // maintenance margin required - unrealizedProfit: string; // unrealized profit - positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side - positionAmt: string; // position amount - updateTime: number; // last update time - notional: string; // position notional value -} +private clearTimers(wsKey: WsKey | string) ⋮---- -symbol: string; // symbol name -initialMargin: string; // initial margin required with current mark price -maintMargin: string; // maintenance margin required -unrealizedProfit: string; // unrealized profit -positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side -positionAmt: string; // position amount -updateTime: number; // last update time -notional: string; // position notional value +// Send a ping at intervals +private clearPingTimer(wsKey: WsKey | string) ⋮---- -export interface DownloadLinkResponse { - downloadId: string; - status: 'completed' | 'processing'; // Enum: completed, processing - url: string; // The link is mapped to download id - s3Link: string | null; - notified: boolean; // ignore - expirationTimestamp: number; // The link would expire after this timestamp - isExpired: boolean | null; -} +// Expect a pong within a time limit +private clearPongTimer(wsKey: WsKey | string) ⋮---- -status: 'completed' | 'processing'; // Enum: completed, processing -url: string; // The link is mapped to download id +// Timer tracking that a reconnect is about to happen / in progress +private clearReconnectTimer(wsKey: WsKey | string) ⋮---- -notified: boolean; // ignore -expirationTimestamp: number; // The link would expire after this timestamp +// eslint-disable-next-line @typescript-eslint/no-unused-vars +private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string ⋮---- -export interface PortfolioTradFiPerpsContractSignResponse { - code: number; - msg: string; -} - -================ -File: src/websocket-api-client.ts -================ -import { - ExchangeInfo, - SpotAmendKeepPriorityResult, - SpotExecutionRulesResponse, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, -} from './types/spot'; -import { - WSAPIResponse, - WSAPIUserDataListenKeyRequest, -} from './types/websockets/ws-api'; -import { - WSAPIAccountCommissionWSAPIRequest, - WSAPIAccountInformationRequest, - WSAPIAllOrderListsRequest, - WSAPIAllOrdersRequest, - WSAPIAvgPriceRequest, - WSAPIBlockTradesHistoricalRequest, - WSAPIExchangeInfoRequest, - WSAPIExecutionRulesRequest, - WSAPIFuturesAlgoOrderCancelRequest, - WSAPIFuturesOrderBookRequest, - WSAPIFuturesOrderCancelRequest, - WSAPIFuturesOrderModifyRequest, - WSAPIFuturesOrderStatusRequest, - WSAPIFuturesPositionRequest, - WSAPIFuturesPositionV2Request, - WSAPIFuturesTickerBookRequest, - WSAPIFuturesTickerPriceRequest, - WSAPIKlinesRequest, - WSAPIMyAllocationsRequest, - WSAPIMyPreventedMatchesRequest, - WSAPIMyTradesRequest, - WSAPINewFuturesAlgoOrderRequest, - WSAPINewFuturesOrderRequest, - WSAPINewSpotOrderRequest, - WSAPIOpenOrdersCancelAllRequest, - WSAPIOpenOrdersStatusRequest, - WSAPIOrderAmendKeepPriorityRequest, - WSAPIOrderBookRequest, - WSAPIOrderCancelReplaceRequest, - WSAPIOrderCancelRequest, - WSAPIOrderListCancelRequest, - WSAPIOrderListPlaceOCORequest, - WSAPIOrderListPlaceOPOCORequest, - WSAPIOrderListPlaceOPORequest, - WSAPIOrderListPlaceOTOCORequest, - WSAPIOrderListPlaceOTORequest, - WSAPIOrderListPlaceRequest, - WSAPIOrderListStatusRequest, - WSAPIOrderStatusRequest, - WSAPIOrderTestRequest, - WSAPIRecvWindowTimestamp, - WSAPIReferencePriceCalculationRequest, - WSAPIReferencePriceRequest, - WSAPISOROrderPlaceRequest, - WSAPISOROrderTestRequest, - WSAPITicker24hrRequest, - WSAPITickerBookRequest, - WSAPITickerPriceRequest, - WSAPITickerRequest, - WSAPITickerTradingDayRequest, - WSAPITradesAggregateRequest, - WSAPITradesHistoricalRequest, - WSAPITradesRecentRequest, -} from './types/websockets/ws-api-requests'; -import { - WSAPIAccountCommission, - WSAPIAccountInformation, - WSAPIAggregateTrade, - WSAPIAllocation, - WSAPIAvgPrice, - WSAPIBlockTrade, - WSAPIBookTicker, - WSAPIFullTicker, - WSAPIFuturesAccountBalanceItem, - WSAPIFuturesAccountStatus, - WSAPIFuturesAlgoOrder, - WSAPIFuturesAlgoOrderCancelResponse, - WSAPIFuturesBookTicker, - WSAPIFuturesOrder, - WSAPIFuturesOrderBook, - WSAPIFuturesPosition, - WSAPIFuturesPositionV2, - WSAPIFuturesPriceTicker, - WSAPIKline, - WSAPIMiniTicker, - WSAPIOrder, - WSAPIOrderBook, - WSAPIOrderCancel, - WSAPIOrderCancelReplaceResponse, - WSAPIOrderListCancelResponse, - WSAPIOrderListPlaceResponse, - WSAPIOrderListStatusResponse, - WSAPIOrderTestResponse, - WSAPIOrderTestWithCommission, - WSAPIPreventedMatch, - WSAPIPriceTicker, - WSAPIRateLimit, - WSAPIServerTime, - WSAPISessionStatus, - WSAPISOROrderPlaceResponse, - WSAPISOROrderTestResponse, - WSAPISOROrderTestResponseWithCommission, - WSAPISpotOrderResponse, - WSAPITrade, -} from './types/websockets/ws-api-responses'; -import { WSClientConfigurableOptions } from './types/websockets/ws-general'; -import { DefaultLogger } from './util/logger'; -import { - isWSAPIWsKey, - isWsEventStreamTerminatedRaw, - neverGuard, -} from './util/typeGuards'; -import { - getTestnetWsKey, - WS_KEY_MAP, - WS_LOGGER_CATEGORY, - WSAPIWsKey, - WSAPIWsKeyFutures, - WSAPIWsKeyMain, - WsKey, -} from './util/websockets/websocket-util'; -import { WSConnectedResult } from './util/websockets/WsStore.types'; -import { WebsocketClient } from './websocket-client'; -⋮---- -function getFuturesMarketWsKey(market: 'usdm' | 'coinm'): WSAPIWsKeyFutures +public getWs(wsKey: WsKey | string): WebSocket | undefined ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected - */ - resubscribeUserDataStreamAfterReconnect: boolean; - - /** - * Default: 2 seconds - * - * Delay automatic userdata resubscribe by x seconds. - */ - resubscribeUserDataStreamDelaySeconds: number; - - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; - - /** - * Default: false - * - * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. - * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. - */ - muteLatencyWarning: boolean; - - /** - * Default: true - * - * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. - */ - keepMarginListenTokenRefreshed: boolean; -} +private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) ⋮---- /** - * Default: true - * - * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected + * Send WS message to subscribe to topics. Use subscribe() to call this. */ +private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) ⋮---- /** - * Default: 2 seconds - * - * Delay automatic userdata resubscribe by x seconds. + * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. */ +private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) ⋮---- /** - * 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(....)`. + * Send WS message to unsubscribe from topics. */ +public requestListSubscriptions(wsKey: WsKey, requestId: number) ⋮---- /** - * Default: false - * - * If true, suppress the latency warning when using HMAC/RSA keys, which require per-request signing and therefore may have higher latency than Ed25519 keys. This warning is only relevant if you are making WS API requests, and not relevant if you are only using the user data stream. - * - * If you are latency sensitive, consider using Ed25519 keys instead. For more information refer to the readme. + * Send WS message to set property state */ +public requestSetProperty( + wsKey: WsKey, + property: 'combined' | string, + value: any, + requestId: number, +) ⋮---- /** - * Default: true - * - * If true, the SDK will proactively refresh the margin listen token before it expires, to help ensure a more seamless experience for users who want to maintain a continuous user data stream connection in margin mode. + * Send WS message to get property state */ +public requestGetProperty( + wsKey: WsKey, + property: 'combined' | string, + requestId: number, +) ⋮---- /** - * Used to track that a connection had an active user data stream before it disconnected. - * - * Note: This is not the same as the "listenKey" WS API workflow (the listenKey workflow is deprecated). - * - * This does not return a listen key. This also does not require a regular "ping" on the listen key. - */ -interface ActiveUserDataStreamState { - subscribedAt: Date; - subscribeAttempt: number; - respawnTimeout?: ReturnType; - /** - * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. - */ - refreshTimeout?: ReturnType; - /** - * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream - */ - userDataStreamParameters?: unknown; -} + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ ⋮---- -/** - * Timer to proactively refresh the listen key / token before it expires. Only intended for margin & futures user data streams. - */ +private setKeepAliveListenKeyTimer( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, +) ⋮---- -/** - * Optional parameters, e.g. how isolated margin mode accepts a symbol to initiate a per-symbol stream - */ +// Set timer to keep WS alive every 50 minutes ⋮---- -/** - * 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/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 - */ -export class WebsocketAPIClient +// 1000 * 60 ⋮---- -/** - * Minimal state store around automating sticky "userDataStream.subscribe" sessions - */ +private sendKeepAliveForMarket( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, +) ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, +private async checkKeepAliveListenKey( + listenKey: string, + market: WsMarket, + ws: WebSocket, + wsKey: WsKey, + symbol?: string, + isTestnet?: boolean, ) ⋮---- -public getWSClient(): WebsocketClient +// Simple way to test keep alive failure handling: +// throw new Error(`Fake keep alive failure`); ⋮---- -public setTimeOffsetMs(newOffset: number): void +// code: -1125, +// message: 'This listenKey does not exist.', ⋮---- -public async disconnectAll(): Promise +// If max failurees reached, tear down and respawn if allowed ⋮---- -/* - * - * SPOT - General requests - * - */ +// reconnect follows a less automatic workflow since this is tied to a listen key (which may need a new one). +// Kill connection first, with instruction NOT to reconnect automatically +⋮---- +// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +⋮---- +private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +⋮---- +private async respawnUserDataStream( + market: WsMarket, + symbol?: string, + isTestnet?: boolean, + respawnAttempt?: number, +): Promise +⋮---- +// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key +⋮---- +// This timer should probably be tracked/singleton ⋮---- /** - * Test connectivity to the WebSocket API - */ -testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise> + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- + **/ ⋮---- /** - * Test connectivity to the WebSocket API and get the current server time + * Subscribe to a universal market websocket stream */ -getSpotServerTime( - wsKey?: WSAPIWsKeyMain, -): Promise> +⋮---- +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Query current exchange trading rules, rate limits, and symbol information + * Subscribe to aggregate trades for a symbol in a market category */ -getSpotExchangeInfo( - params?: WSAPIExchangeInfoRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- -/* - * - * SPOT - Market data requests - * +/** + * Subscribe to trades for a symbol in a market category + * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning */ +public subscribeTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get current order book - * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams + * Subscribe to block trades for a symbol in spot markets. */ -getSpotOrderBook( - params: WSAPIOrderBookRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeBlockTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get recent trades - * Note: If you need access to real-time trading activity, consider using WebSocket Streams + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. */ -getSpotRecentTrades( - params: WSAPITradesRecentRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- /** - * Get historical trades - * Note: If fromId is not specified, the most recent trades are returned + * Subscribe to mark price for a symbol in a market category */ -getSpotHistoricalTrades( - params: WSAPITradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeMarkPrice( + symbol: string, + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get historical block trades + * Subscribe to mark price for all symbols in a market category */ -getSpotHistoricalBlockTrades( - params: WSAPIBlockTradesHistoricalRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get aggregate trades - * Note: An aggregate trade represents one or more individual trades that fill at the same time + * Subscribe to klines(candles) for a symbol in a market category */ -getSpotAggregateTrades( - params: WSAPITradesAggregateRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get klines (candlestick bars) - * Note: If you need access to real-time kline updates, consider using WebSocket Streams + * Subscribe to continuous contract klines(candles) for a symbol futures */ -getSpotKlines( - params: WSAPIKlinesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeContinuousContractKlines( + symbol: string, + contractType: 'perpetual' | 'current_quarter' | 'next_quarter', + interval: KlineInterval, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get klines (candlestick bars) optimized for presentation - * Note: This request is similar to klines, having the same parameters and response + * Subscribe to index klines(candles) for a symbol in a coinm futures */ -getSpotUIKlines( - params: WSAPIKlinesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get current average price for a symbol + * Subscribe to index klines(candles) for a symbol in a coinm futures */ -getSpotAveragePrice( - params: WSAPIAvgPriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Query execution rules (e.g. PRICE_RANGE) for symbol(s) or by symbol status. + * Subscribe to mini 24hr ticker for a symbol in market category. */ -getSpotExecutionRules( - params?: WSAPIExecutionRulesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Query reference price for a symbol. + * Subscribe to mini 24hr mini ticker in market category. */ -getSpotReferencePrice( - params: WSAPIReferencePriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Query how reference price is calculated for a symbol. + * Subscribe to 24hr ticker for a symbol in any market. */ -getSpotReferencePriceCalculation( - params: WSAPIReferencePriceCalculationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get 24-hour rolling window price change statistics - * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams + * Subscribe to 24hr ticker in any market. */ -getSpot24hrTicker( - params?: WSAPITicker24hrRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.24hr', - params, - { authIsOptional: true }, - ); +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get price change statistics for a trading day + * Subscribe to rolling window ticker statistics for all market symbols, + * computed over multiple windows. Note that only tickers that have + * changed will be present in the array. + * + * Notes: + * - Supported window sizes: 1h,4h,1d. + * - Supported markets: spot */ -getSpotTradingDayTicker( - params: WSAPITickerTradingDayRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker.tradingDay', - params, - { authIsOptional: true }, - ); +public subscribeAllRollingWindowTickers( + market: 'spot', + windowSize: '1h' | '4h' | '1d', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get rolling window price change statistics with a custom window - * Note: Window size precision is limited to 1 minute + * Subscribe to best bid/ask for symbol in spot markets. */ -getSpotTicker( - params: WSAPITickerRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[] - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'ticker', - params, - { authIsOptional: true }, - ); +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get the latest market price for a symbol - * Note: If you need access to real-time price updates, consider using WebSocket Streams + * Subscribe to best bid/ask for all symbols in spot markets. */ -getSpotSymbolPriceTicker( - params?: WSAPITickerPriceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeAllBookTickers( + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Get the current best price and quantity on the order book - * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams + * Subscribe to best bid/ask for symbol in spot markets. */ -getSpotSymbolOrderBookTicker( - params?: WSAPITickerBookRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> -⋮---- -/* - * - * SPOT - Session authentication requests +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket +⋮---- +/** + * Subscribe to partial book depths (snapshots). * - * Note: authentication is automatic + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs * + * Use getContextFromWsKey(data.wsKey) to extract symbol from events */ +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- -getSpotSessionStatus( - wsKey?: WSAPIWsKeyMain, -): Promise> -⋮---- -/* +/** + * Subscribe to orderbook depth updates to locally manage an order book. * - * SPOT - Trading requests + * Note that the updatems parameter depends on which market you're trading + * + * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams * + * Use getContextFromWsKey(data.wsKey) to extract symbol from events */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Submit a spot order + * Subscribe to best bid/ask for all symbols in spot markets. */ -submitNewSpotOrder( - params: WSAPINewSpotOrderRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Test order placement - * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine - */ -testSpotOrder( - params: WSAPIOrderTestRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'order.test', - params, - ); + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- /** - * Check execution status of an order - * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + * Subscribe to aggregate trades for a symbol in spot markets. */ -getSpotOrderStatus( - params: WSAPIOrderStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotAggregateTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Cancel an active order - * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used + * Subscribe to trades for a symbol in spot markets. */ -cancelSpotOrder( - params: WSAPIOrderCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Cancel an existing order and immediately place a new order - * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used + * Subscribe to block trades for a symbol in spot markets. */ -cancelReplaceSpotOrder( - params: WSAPIOrderCancelReplaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotBlockTrades( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Reduce the quantity of an existing open order. - * - * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority + * Subscribe to candles for a symbol in spot markets. */ -amendSpotOrderKeepPriority( - params: WSAPIOrderAmendKeepPriorityRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Query execution status of all open orders - * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams + * Subscribe to mini 24hr ticker for a symbol in spot markets. */ -getSpotOpenOrders( - params: WSAPIOpenOrdersStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Cancel all open orders on a symbol - * Note: This includes orders that are part of an order list + * Subscribe to mini 24hr mini ticker in spot markets. */ -cancelAllSpotOpenOrders( - params: WSAPIOpenOrdersCancelAllRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]> - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'openOrders.cancelAll', - params, - ); +public subscribeSpotAllMini24hrTickers( + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Place a new order list - * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead + * Subscribe to 24hr ticker for a symbol in spot markets. */ -placeSpotOrderList( - params: WSAPIOrderListPlaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotSymbol24hrTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Place a new OCO (One-Cancels-the-Other) order list - * Note: Activation of one order immediately cancels the other + * Subscribe to 24hr ticker in spot markets. */ -placeSpotOCOOrderList( - params: WSAPIOrderListPlaceOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** - * Place a new OTO (One-Triggers-the-Other) order list - * Note: The pending order is placed only when the working order is fully filled + * Subscribe to best bid/ask for symbol in spot markets. */ -placeSpotOTOOrderList( - params: WSAPIOrderListPlaceOTORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotSymbolBookTicker( + symbol: string, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list - * Note: The pending orders are placed only when the working order is fully filled + * Subscribe to best bid/ask for all symbols in spot markets. */ -placeSpotOTOCOOrderList( - params: WSAPIOrderListPlaceOTOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket ⋮---- /** - * Place a new OPO (One-Pays-the-Other) order list - * Note: One order pays for the other - when the working order is filled, the pending order is placed + * Subscribe to top bid/ask levels for symbol in spot markets. */ -placeSpotOPOOrderList( - params: WSAPIOrderListPlaceOPORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotPartialBookDepth( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Place a new OPOCO (One-Pays-One-Cancels-the-Other) order list - * Note: Combines OPO and OCO - working order pays for two pending orders, one cancels the other + * Subscribe to spot orderbook depth updates to locally manage an order book. */ -placeSpotOPOCOOrderList( - params: WSAPIOrderListPlaceOPOCORequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + forceNewConnection?: boolean, +): WebSocket ⋮---- /** - * Check execution status of an order list - * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. */ -getSpotOrderListStatus( - params: WSAPIOrderListStatusRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public subscribeSpotUserDataStreamWithListenKey( + listenKey: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): WebSocket | undefined +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * Cancel an active order list - * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used + * Subscribe to spot user data stream - listen key is automaticallyr generated. Calling multiple times only opens one connection. */ -cancelSpotOrderList( - params: WSAPIOrderListCancelRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public async subscribeSpotUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- /** - * Query execution status of all open order lists - * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams + * Subscribe to margin user data stream - listen key is automatically generated. */ -getSpotOpenOrderLists( - params: WSAPIRecvWindowTimestamp, - wsKey?: WSAPIWsKeyMain, -): Promise> +public async subscribeMarginUserDataStream( + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise +⋮---- +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * Place a new order using Smart Order Routing (SOR) - * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported + * Subscribe to isolated margin user data stream - listen key is automatically generated. */ -placeSpotSOROrder( - params: WSAPISOROrderPlaceRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> -⋮---- -/** - * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) - * Note: Creates and validates a new order but does not send it into the matching engine - */ -testSpotSOROrder( - params: WSAPISOROrderTestRequest, - wsKey?: WSAPIWsKeyMain, - ): Promise< - WSAPIResponse< - WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission - > - > { - return this.wsClient.sendWSAPIRequest( - wsKey || WS_KEY_MAP.mainWSAPI, - 'sor.order.test', - params, - ); +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -/* - * - * SPOT - Account requests - * - */ +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * Query information about your account, including balances - * Note: Weight: 20 - */ -getSpotAccountInformation( - params: WSAPIAccountInformationRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- /** - * Query your current unfilled order count for all intervals - * Note: Weight: 40 + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. */ -getSpotOrderRateLimits( - params: WSAPIRecvWindowTimestamp, - wsKey?: WSAPIWsKeyMain, -): Promise> +public async subscribeUsdFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -/** - * Query information about all your orders – active, canceled, filled – filtered by time range - * Note: Weight: 20 - */ -getSpotAllOrders( - params: WSAPIAllOrdersRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +// Necessary so client knows this is a reconnect ⋮---- -/** - * Query information about all your order lists, filtered by time range - * Note: Weight: 20 - */ -getSpotAllOrderLists( - params: WSAPIAllOrderListsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +// Start & store timer to keep alive listen key (and handle expiration) ⋮---- /** - * Query information about all your trades, filtered by time range - * Note: Weight: 20 + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. */ -getSpotMyTrades( - params: WSAPIMyTradesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +public async subscribeCoinFuturesUserDataStream( + isTestnet?: boolean, + forceNewConnection?: boolean, + isReconnecting?: boolean, +): Promise ⋮---- -/** - * Displays the list of orders that were expired due to STP - * Note: Weight varies based on query type (2-20) - */ -getSpotPreventedMatches( - params: WSAPIMyPreventedMatchesRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +// Necessary so client knows this is a reconnect ⋮---- -/** - * Retrieves allocations resulting from SOR order placement - * Note: Weight: 20 - */ -getSpotAllocations( - params: WSAPIMyAllocationsRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +// Start & store timer to keep alive listen key (and handle expiration) + +================ +File: .nvmrc +================ +v24.18.0 + +================ +File: src/types/portfolio-margin.ts +================ +// Enums +export type PMStrategyType = + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; ⋮---- -/** - * Get current account commission rates - * Note: Weight: 20 - */ -getSpotAccountCommission( - params: WSAPIAccountCommissionWSAPIRequest, - wsKey?: WSAPIWsKeyMain, -): Promise> +export type PMWorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; ⋮---- -/* - * - * FUTURES - Market data requests - * - */ +export type PMPriceMatch = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; ⋮---- -/** - * Get current order book for futures - * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams - */ -getFuturesOrderBook( - params: WSAPIFuturesOrderBookRequest, -): Promise> +export type PMSelfTradePreventionMode = + | 'NONE' + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH'; ⋮---- -/** - * Get latest price for a futures symbol or symbols - * Note: If symbol is not provided, prices for all symbols will be returned - */ -getFuturesSymbolPriceTicker( - params?: WSAPIFuturesTickerPriceRequest, - ): Promise< - WSAPIResponse - > { - return this.wsClient.sendWSAPIRequest( - WS_KEY_MAP.usdmWSAPI, - 'ticker.price', - params, - { authIsOptional: true }, - ); +export type PMMarginOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -/** - * Get best price/qty on the order book for a futures symbol or symbols - * Note: If symbol is not provided, bookTickers for all symbols will be returned - */ -getFuturesSymbolOrderBookTicker( - params?: WSAPIFuturesTickerBookRequest, -): Promise> +export type PMMarginSideEffectType = + | 'NO_SIDE_EFFECT' + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'AUTO_BORROW_REPAY'; ⋮---- -/* - * - * FUTURES - Trading requests - * - */ +export type PMAutoCloseType = 'LIQUIDATION' | 'ADL'; ⋮---- -/** - * Submit a futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -submitNewFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPINewFuturesOrderRequest, -): Promise> +export interface NewPortfolioUMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; // Cannot be sent in Hedge Mode + price?: string; + newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ + newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK + priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD +} ⋮---- -/** - * Modify an existing futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -modifyFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderModifyRequest, -): Promise> +positionSide?: 'BOTH' | 'LONG' | 'SHORT'; // Default BOTH for One-way Mode ⋮---- -/** - * Cancel a futures order - * - * This endpoint is used for both USDM and COINM futures. - */ -cancelFuturesOrder( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderCancelRequest, -): Promise> +reduceOnly?: boolean; // Cannot be sent in Hedge Mode ⋮---- -/** - * Query futures order status - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesOrderStatus( - market: 'usdm' | 'coinm', - params: WSAPIFuturesOrderStatusRequest, -): Promise> +newClientOrderId?: string; // Must match: ^[\.A-Z\:/a-z0-9_-]{1,32}$ +newOrderRespType?: 'ACK' | 'RESULT'; // Default: ACK +priceMatch?: PMPriceMatch; // Only for LIMIT/STOP/TAKE_PROFIT orders ⋮---- -/** - * Get current position information (V2) - * Note: Only symbols that have positions or open orders will be returned - */ -getFuturesPositionV2( - params: WSAPIFuturesPositionV2Request, -): Promise> +goodTillDate?: number; // Mandatory when timeInForce is GTD ⋮---- -/** - * Get current position information - * Note: Only symbols that have positions or open orders will be returned - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesPosition( - market: 'usdm' | 'coinm', - params: WSAPIFuturesPositionRequest, -): Promise> +export interface NewPortfolioUMOrderResponse { + clientOrderId: string; + cumQty: string; + cumQuote?: string; + executedQty: string; + orderId: number; + avgPrice?: string; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate?: number; + updateTime: number; + priceMatch: PMPriceMatch; +} ⋮---- -/** - * Send in a new algo order - * - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/New-Algo-Order - */ -submitNewFuturesAlgoOrder( - params: WSAPINewFuturesAlgoOrderRequest, -): Promise> +export interface NewPortfolioUMConditionalOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + strategyType: PMStrategyType; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + workingType?: PMWorkingType; + priceProtect?: boolean; + newClientStrategyId?: string; + stopPrice?: string; + activationPrice?: string; + callbackRate?: string; + priceMatch?: PMPriceMatch; + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; +} ⋮---- -/** - * Cancel an active algo order. - * - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order - * @param params - */ -cancelFuturesAlgoOrder( - params: WSAPIFuturesAlgoOrderCancelRequest, -): Promise> +export interface NewPortfolioConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; + selfTradePreventionMode: PMSelfTradePreventionMode; + goodTillDate?: number; + priceMatch: PMPriceMatch; +} ⋮---- -/* - * - * FUTURES - Account requests - * - */ +export type PortfolioUMAlgoType = 'CONDITIONAL'; ⋮---- -/** - * Get account balance information (V2) - * Note: Returns balance information for all assets - */ -getFuturesAccountBalanceV2( - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface NewPortfolioUMAlgoOrderReq { + algoType: PortfolioUMAlgoType; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + type: PMStrategyType; + timeInForce?: string; + quantity?: string; + price?: string; + triggerPrice?: string; + workingType?: PMWorkingType; + priceMatch?: PMPriceMatch; + closePosition?: string; + priceProtect?: string; + reduceOnly?: string; + activatePrice?: string; + callbackRate?: string; + clientAlgoId?: string; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: PMSelfTradePreventionMode; + goodTillDate?: number; +} ⋮---- -/** - * Get account balance information - * Note: Returns balance information for all assets - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesAccountBalance( - market: 'usdm' | 'coinm', - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface PortfolioUMAlgoOrder { + algoId: number; + clientAlgoId: string; + algoType: string; + orderType: string; + symbol: string; + side: string; + positionSide: string; + timeInForce: string; + quantity: string; + algoStatus: string; + triggerPrice: string; + price: string; + icebergQuantity: string | null; + selfTradePreventionMode: string; + workingType: string; + priceMatch: string; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + activatePrice: string; + callbackRate: string; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; + actualOrderId?: string; + actualPrice?: string; + tpTriggerPrice?: string; + tpPrice?: string; + slTriggerPrice?: string; + slPrice?: string; + tpOrderType?: string; +} ⋮---- -/** - * Get account information (V2) - * Note: Returns detailed account information including positions and assets - */ -getFuturesAccountStatusV2( - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface CancelPortfolioUMAlgoOrderReq { + algoId?: number; + clientAlgoId?: string; +} ⋮---- -/** - * Get account information - * Note: Returns detailed account information including positions and assets - * - * This endpoint is used for both USDM and COINM futures. - */ -getFuturesAccountStatus( - market: 'usdm' | 'coinm', - params: WSAPIRecvWindowTimestamp, -): Promise> +export interface PortfolioUMCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} ⋮---- -/* - * - * User data stream requests - * - */ +export interface PortfolioUMCancelAllUMAlgoOpenOrdersResponse { + code: number; + msg: string; +} ⋮---- -/** - * Start the user data stream for an apiKey (passed as param). - * - * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. - * - * @param params - * @param wsKey - * @returns listenKey - */ -startUserDataStreamForKey( - params: { apiKey: string }, - wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> +export interface QueryPortfolioAllUMAlgoOrdersReq { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Stop the user data stream listen key. - * - * @param params - * @param wsKey - * @returns - */ -stopUserDataStreamForKey( - params: WSAPIUserDataListenKeyRequest, - wsKey: WSAPIWsKey = WS_KEY_MAP.mainWSAPI, -): Promise> -⋮---- -/** - * Consolidated method to clear any timers related to user data stream subscriptions for a given wsKey, if found. - * - * @param wsKey - */ -clearUserDataStreamTimers(wsKey: WSAPIWsKey) -⋮---- -// Just in case the refresh timer is still running -// Harmless given one connection, but still unnecessary -⋮---- -/** - * Request user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will automatically resubscribe unless you unsubscribe manually. - */ -async subscribeUserDataStream( - wsKey: WSAPIWsKey, - isRefreshingToken: boolean = false, -): Promise | WSConnectedResult | undefined> -⋮---- -// User data stream works differently for margin, since Feb 2026, via a listen token mechanic -⋮---- -// validity: 30 * 1000, // milliseconds (30 secs) -// validity: 5 * 60 * 1000, // milliseconds (5 mins ) +export interface NewPortfolioCMOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT'; +} ⋮---- -// Set respawn timer, to automatically fetch and sub to new token before expiry. Should be seamless on existing connection. +export interface NewPortfolioCMOrderResponse { + clientOrderId: string; + cumQty: string; + cumBase?: string; + executedQty: string; + orderId: number; + avgPrice?: string; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + status: string; + symbol: string; + pair: string; + timeInForce: string; + type: 'LIMIT' | 'MARKET'; + updateTime: number; +} ⋮---- -// try to respawn 30 seconds before expiration +export interface NewPortfolioCMConditionalOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + strategyType: PMStrategyType; + timeInForce?: string; + quantity?: string; + reduceOnly?: boolean; + price?: string; + workingType?: PMWorkingType; + priceProtect?: boolean; + newClientStrategyId?: string; + stopPrice?: string; + activationPrice?: string; + callbackRate?: string; +} ⋮---- -// for Ed25519 keys, no signature is needed, we should already be authenticated in session +export interface NewPortfolioCMConditionalOrderResponse { + newClientStrategyId: string; + strategyId: number; + strategyStatus: string; + strategyType: PMStrategyType; + origQty: string; + price: string; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + stopPrice?: string; + symbol: string; + pair: string; + timeInForce: string; + activatePrice?: string; + priceRate?: string; + bookTime: number; + updateTime: number; + workingType: PMWorkingType; + priceProtect: boolean; +} ⋮---- -// for HMAC & RSA keys, request will be signed and sent to a dedicated topic +export interface MarginOrderFill { + price: string; + qty: string; + commission: string; + commissionAsset: string; +} ⋮---- -// Used to track whether this connection had the general "userDataStream.subscribe" called. -// Used as part of `resubscribeUserDataStreamAfterReconnect` to know which connections to resub. +export interface NewPortfolioMarginOrderReq { + symbol: string; + side: 'BUY' | 'SELL'; + type: PMMarginOrderType; + quantity?: string; + quoteOrderQty?: string; + price?: string; + stopPrice?: string; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: string; + sideEffectType?: PMMarginSideEffectType; + timeInForce?: string; + selfTradePreventionMode?: PMSelfTradePreventionMode; + autoRepayAtCancel?: boolean; +} ⋮---- -/** - * Unsubscribe from the user data stream subscription on the currently authenticated connection. - * - * If reconnected, this will also stop it from automatically resubscribing after reconnect. - */ -unsubscribeUserDataStream( - wsKey: WSAPIWsKey, -): Promise { +export interface PortfolioCMForceOrder { + orderId: number; symbol: string; - listClientOrderId?: string; - side: OrderSide; - quantity: number; - aboveType: OrderListOrderType; - aboveClientOrderId?: string; - aboveIcebergQty?: number; - abovePrice?: number; - aboveStopPrice?: number; - aboveTrailingDelta?: number; - aboveTimeInForce?: OrderTimeInForce; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: OrderListOrderType; - belowClientOrderId?: string; - belowIcebergQty?: number; - belowPrice?: number; - belowStopPrice?: number; - belowTrailingDelta?: number; - belowTimeInForce?: OrderTimeInForce; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: T; - selfTradePreventionMode?: SelfTradePreventionMode; + pair: string; + status: string; + clientOrderId: string; + price: string; + avgPrice: string; + origQty: string; + executedQty: string; + cumBase: string; + timeInForce: string; + type: 'LIMIT'; + reduceOnly: boolean; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + origType: 'LIMIT'; + time: number; + updateTime: number; } ⋮---- -export interface SymbolFromPaginatedRequestFromId { +export interface QueryPortfolioUMOrderAmendmentReq { symbol: string; - fromId?: number; + orderId?: number; + origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- -export interface GetAllOrdersParams { +export interface PortfolioUMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; +} +⋮---- +export interface PortfolioUMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioUMOrderAmendment; + priceMatch: PMPriceMatch; + modifyId?: number; +} +⋮---- +export interface QueryPortfolioCMOrderAmendmentReq { symbol: string; orderId?: number; + origClientOrderId?: string; startTime?: number; endTime?: number; limit?: number; } ⋮---- -export interface RateLimiter { - rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; - interval: 'SECOND' | 'MINUTE' | 'DAY'; - intervalNum: number; - limit: number; +export interface PortfolioCMOrderAmendment { + price: { + before: string; + after: string; + }; + origQty: { + before: string; + after: string; + }; + count: number; } ⋮---- -export interface SymbolPriceFilter { - filterType: 'PRICE_FILTER'; - minPrice: numberInString; - maxPrice: numberInString; - tickSize: numberInString; +export interface PortfolioCMOrderModificationHistory { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: PortfolioCMOrderAmendment; + modifyId?: number; } ⋮---- -export interface SymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - avgPriceMins: number; +export interface QueryPortfolioMarginForceOrdersReq { + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 } ⋮---- -export interface SymbolPercentPriceBySideFilter { - filterType: 'PERCENT_PRICE_BY_SIDE'; - bidMultiplierUp: numberInString; - bidMultiplierDown: numberInString; - askMultiplierUp: numberInString; - askMultiplierDown: numberInString; - avgPriceMins: number; -} +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 ⋮---- -export interface SymbolLegacyMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - minNotional: numberInString; - applyToMarket: boolean; - avgPriceMins: number; +export interface PortfolioMarginForceOrder { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + updatedTime: number; } ⋮---- -export interface SymbolLotSizeFilter { - filterType: 'LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; +export interface QueryPortfolioUMTradesReq { + symbol: string; + startTime?: number; + endTime?: number; + fromId?: number; // Trade id to fetch from. Default gets most recent trades + limit?: number; // Default 500; max 1000 } ⋮---- -export interface SymbolMinNotionalFilter { - filterType: 'NOTIONAL'; - minNotional: numberInString; - applyMinToMarket: boolean; - maxNotional: numberInString; - applyMaxToMarket: boolean; - avgPriceMins: number; +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 +⋮---- +export interface PortfolioUMTrade { + symbol: string; + id: number; + orderId: number; + side: 'BUY' | 'SELL'; + price: string; + qty: string; + realizedPnl: string; + quoteQty: string; + commission: string; + commissionAsset: string; + time: number; + buyer: boolean; + maker: boolean; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + pair?: string; + baseQty?: string; + marginAsset?: string; } ⋮---- -export interface SymbolIcebergPartsFilter { - filterType: 'ICEBERG_PARTS'; - limit: number; +export interface QueryPortfolioCMTradesReq { + symbol?: string; + pair?: string; + startTime?: number; + endTime?: number; + fromId?: number; // Trade id to fetch from. Default gets most recent trades + limit?: number; // Default 50; max 1000 } ⋮---- -export interface SymbolMarketLotSizeFilter { - filterType: 'MARKET_LOT_SIZE'; - minQty: numberInString; - maxQty: numberInString; - stepSize: numberInString; +fromId?: number; // Trade id to fetch from. Default gets most recent trades +limit?: number; // Default 50; max 1000 +⋮---- +export interface PortfolioCMTrade { + symbol: string; + id: number; + orderId: number; + pair: string; + side: 'BUY' | 'SELL'; + price: string; + qty: string; + realizedPnl: string; + marginAsset: string; + baseQty: string; + commission: string; + commissionAsset: string; + time: number; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + buyer: boolean; + maker: boolean; + quoteQty?: string; } ⋮---- -export interface SymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - maxNumOrders: number; +export interface PortfolioADLQuantile { + LONG: number; + SHORT: number; + BOTH?: number; // For one-way mode or isolated margin in hedge mode + HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) } ⋮---- -export interface SymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - maxNumAlgoOrders: number; +BOTH?: number; // For one-way mode or isolated margin in hedge mode +HEDGE?: number; // For cross margin in hedge mode (ignore value, just a sign) +⋮---- +export interface QueryPortfolioMarginOrderReq { + symbol: string; + orderId?: number; + origClientOrderId?: string; } ⋮---- -export interface SymbolMaxIcebergOrdersFilter { - filterType: 'MAX_NUM_ICEBERG_ORDERS'; - maxNumIcebergOrders: number; +export interface PortfolioMarginOrder { + clientOrderId: string; + cummulativeQuoteQty: string; + executedQty: string; + icebergQty: string; + isWorking: boolean; + orderId: number; + origQty: string; + price: string; + side: 'BUY' | 'SELL'; + status: string; + stopPrice: string; + symbol: string; + time: number; + timeInForce: string; + type: PMMarginOrderType; + updateTime: number; + accountId: number; + selfTradePreventionMode: PMSelfTradePreventionMode; + preventedMatchId: number | null; + preventedQuantity: string | null; } ⋮---- -export interface SymbolMaxPositionFilter { - filterType: 'MAX_POSITION'; - maxPosition: numberInString; +export interface QueryPortfolioMarginAllOrdersReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 } ⋮---- -export type SymbolFilter = - | SymbolPriceFilter - | SymbolPercentPriceFilter - | SymbolPercentPriceBySideFilter - | SymbolLegacyMinNotionalFilter - | SymbolLotSizeFilter - | SymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | SymbolMaxOrdersFilter - | SymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter; +limit?: number; // Default 500; max 500 ⋮---- -export interface ExchangeMaxNumOrdersFilter { - filterType: 'EXCHANGE_MAX_NUM_ORDERS'; - maxNumOrders: number; +export interface QueryPortfolioMarginOCOReq { + orderListId?: number; // Either orderListId or origClientOrderId must be provided + origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided } ⋮---- -export interface ExchangeMaxAlgoOrdersFilter { - filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; - maxNumAlgoOrders: number; +orderListId?: number; // Either orderListId or origClientOrderId must be provided +origClientOrderId?: string; // Either orderListId or origClientOrderId must be provided +⋮---- +export interface PortfolioMarginOCOQueryOrder { + symbol: string; + orderId: number; + clientOrderId: string; } ⋮---- -export type ExchangeFilter = - | ExchangeMaxNumOrdersFilter - | ExchangeMaxAlgoOrdersFilter; +export interface PortfolioMarginOCO { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: PortfolioMarginOCOQueryOrder[]; +} ⋮---- -export type OrderBookPrice = numberInString; -export type OrderBookAmount = numberInString; +export interface QueryPortfolioMarginAllOCOReq { + fromId?: number; // If supplied, neither startTime or endTime can be provided + startTime?: number; + endTime?: number; + limit?: number; // Default 500; max 500 +} ⋮---- -export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; +fromId?: number; // If supplied, neither startTime or endTime can be provided ⋮---- -export type OrderBookPriceFormatted = number; -export type OrderBookAmountFormatted = number; -export type OrderBookRowFormatted = [ - OrderBookPriceFormatted, - OrderBookAmountFormatted, -]; +limit?: number; // Default 500; max 500 ⋮---- -export interface GenericCodeMsgError { - code: number; - msg: string; +export interface QueryPortfolioMarginTradesReq { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; // TradeId to fetch from. Default gets most recent trades + limit?: number; // Default 500; max 1000 } ⋮---- -export interface RowsWithTotal { - rows: T[]; - total: number; +fromId?: number; // TradeId to fetch from. Default gets most recent trades +limit?: number; // Default 500; max 1000 +⋮---- +export interface PortfolioMarginTrade { + commission: string; + commissionAsset: string; + id: number; + isBestMatch: boolean; + isBuyer: boolean; + isMaker: boolean; + orderId: number; + price: string; + qty: string; + symbol: string; + time: number; } ⋮---- -export interface CoinStartEndLimit { - coin?: string; - startTime?: number; - endTime?: number; - limit?: number; +export interface PortfolioMarginRepayDebtReq { + asset: string; + amount?: string; + specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas } - -================ -File: src/coinm-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; ⋮---- -import { - ClassicPortfolioMarginAccount, - ClassicPortfolioMarginNotionalLimit, - CoinMAccountTradeParams, - CoinMOpenInterest, - CoinMPositionTrade, - CoinMSymbolOrderBookTicker, - FundingRate, - FuturesTransactionHistoryDownloadLink, - GetClassicPortfolioMarginNotionalLimitParams, - PositionRisk, -} from './types/coin'; -import { - AggregateFuturesTrade, - CancelAllOpenOrdersResult, - CancelFuturesOrderResult, - CancelMultipleOrdersParams, - CancelOrdersTimeoutParams, - ChangeStats24hr, - ContinuousContractKlinesParams, - ForceOrderResult, - FundingRateHistory, - FuturesAlgoOrderResponse, - FuturesCancelAlgoOrderParams, - FuturesCancelAlgoOrderResponse, - FuturesCoinMAccountBalance, - FuturesCoinMAccountInformation, - FuturesCoinMBasisParams, - FuturesCoinMLongShortAccountRatioParams, - FuturesCoinMTakerBuySellVolumeParams, - FuturesDataPaginatedParams, - FuturesExchangeInfo, - FuturesNewAlgoOrderParams, - FuturesOrderBook, - FuturesQueryOpenAlgoOrdersParams, - GetForceOrdersParams, - GetIncomeHistoryParams, - GetPositionMarginChangeHistoryParams, - IncomeHistory, - IndexPriceConstituents, - IndexPriceKlinesParams, - MarkPrice, - ModeChangeResult, - ModifyFuturesOrderParams, - ModifyFuturesOrderResult, - NewFuturesOrderParams, - NewOrderError, - NewOrderResult, - OrderAmendment, - OrderResult, - PositionModeParams, - PositionModeResponse, - QuarterlyContractSettlementPrice, - RawFuturesTrade, - RebateDataOverview, - SetCancelTimeoutResult, - SetIsolatedMarginParams, - SetIsolatedMarginResult, - SetLeverageParams, - SetLeverageResult, - SetMarginTypeParams, - SymbolKlinePaginatedParams, - SymbolLeverageBracketsResult, - UserCommissionRate, -} from './types/futures'; -import { - BasicSymbolPaginatedParams, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - GenericCodeMsgError, - GetAllOrdersParams, - GetOrderModifyHistoryParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - OrderBookParams, - OrderIdProperty, - RecentTradesParams, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - asArray, - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; -⋮---- -export class CoinMClient extends BaseRestClient +specifyRepayAssets?: string; // Specific asset list to repay debt; Can be added in batch, separated by commas ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +export interface PortfolioMarginRepayDebtResponse { + amount: string; + asset: string; + specifyRepayAssets: string[]; + updateTime: number; + success: boolean; +} ⋮---- /** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise + * + * DERIVATIVES - ACCOUNT endpoints + * + **/ ⋮---- -/** - * - * Market Data Endpoints - * - **/ +export type PMAccountStatus = + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; ⋮---- -testConnectivity(): Promise +export type PMIndicatorType = 'UFR' | 'IFER' | 'GCR' | 'DR' | 'TMV'; +export type PMMarginLoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- -getExchangeInfo(): Promise +export interface PortfolioTotalBalance { + asset: string; + totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance + crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked + crossMarginBorrowed: string; // principal of cross margin + crossMarginFree: string; // free asset of cross margin + crossMarginInterest: string; // interest of cross margin + crossMarginLocked: string; // lock asset of cross margin + umWalletBalance: string; // wallet balance of um + umUnrealizedPNL: string; // unrealized profit of um + cmWalletBalance: string; // wallet balance of cm + cmUnrealizedPNL: string; // unrealized profit of cm + updateTime: number; + negativeBalance: string; +} ⋮---- -getOrderBook(params: OrderBookParams): Promise +totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance +crossMarginAsset: string; // crossMarginAsset = crossMarginFree + crossMarginLocked +crossMarginBorrowed: string; // principal of cross margin +crossMarginFree: string; // free asset of cross margin +crossMarginInterest: string; // interest of cross margin +crossMarginLocked: string; // lock asset of cross margin +umWalletBalance: string; // wallet balance of um +umUnrealizedPNL: string; // unrealized profit of um +cmWalletBalance: string; // wallet balance of cm +cmUnrealizedPNL: string; // unrealized profit of cm ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +export interface PortfolioSingleBalance { + asset: string; + totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance + crossMarginBorrowed: string; // principal of cross margin + crossMarginFree: string; // free asset of cross margin + crossMarginInterest: string; // interest of cross margin + crossMarginLocked: string; // lock asset of cross margin + umWalletBalance: string; // wallet balance of um + umUnrealizedPNL: string; // unrealized profit of um + cmWalletBalance: string; // wallet balance of cm + cmUnrealizedPNL: string; // unrealized profit of cm + updateTime: number; + negativeBalance: string; +} ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, -): Promise +totalWalletBalance: string; // wallet balance = cross margin free + cross margin locked + UM wallet balance + CM wallet balance +crossMarginBorrowed: string; // principal of cross margin +crossMarginFree: string; // free asset of cross margin +crossMarginInterest: string; // interest of cross margin +crossMarginLocked: string; // lock asset of cross margin +umWalletBalance: string; // wallet balance of um +umUnrealizedPNL: string; // unrealized profit of um +cmWalletBalance: string; // wallet balance of cm +cmUnrealizedPNL: string; // unrealized profit of cm ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +export type PortfolioBalance = PortfolioBalance[] | PortfolioSingleBalance; ⋮---- -/** - * Index Price and Mark Price - */ -getMarkPrice(params?: +export interface PortfolioAccountInformation { + uniMMR: string; // Portfolio margin account maintenance margin rate + accountEquity: string; // Account equity, in USD value + actualEquity: string; // Account equity without collateral rate, in USD value + accountInitialMargin: string; + accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD + accountStatus: PMAccountStatus; + virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD + totalAvailableBalance: string; + totalMarginOpenLoss: string; // in USD margin open order + updateTime: number; // last update time +} ⋮---- -getFundingRateHistory( - params?: Partial, -): Promise +uniMMR: string; // Portfolio margin account maintenance margin rate +accountEquity: string; // Account equity, in USD value +actualEquity: string; // Account equity without collateral rate, in USD value ⋮---- -getFundingRate(params?: +accountMaintMargin: string; // Portfolio margin account maintenance margin, unit: USD ⋮---- -getKlines(params: KlinesParams): Promise +virtualMaxWithdrawAmount: string; // Portfolio margin maximum amount for transfer out in USD ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, -): Promise +totalMarginOpenLoss: string; // in USD margin open order +updateTime: number; // last update time ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +export interface PortfolioUMPosition { + symbol: string; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; + maxNotionalValue: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + notional: string; + updateTime: number; +} ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +export interface PortfolioCMPosition { + symbol: string; + positionAmt: string; + entryPrice: string; + markPrice: string; + unRealizedProfit: string; + liquidationPrice: string; + leverage: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + updateTime: number; + maxQty: string; + notionalValue: string; +} ⋮---- -getPremiumIndexKlines(params: KlinesParams): Promise +export interface PortfolioUMLeverageBracket { + bracket: number; // Notional bracket + initialLeverage: number; // Max initial leverage for this bracket + notionalCap: number; // Cap notional of this bracket + notionalFloor: number; // Notional threshold of this bracket + maintMarginRatio: number; // Maintenance ratio for this bracket + cum: number; // Auxiliary number for quick calculation +} ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; - pair?: string; -}): Promise +bracket: number; // Notional bracket +initialLeverage: number; // Max initial leverage for this bracket +notionalCap: number; // Cap notional of this bracket +notionalFloor: number; // Notional threshold of this bracket +maintMarginRatio: number; // Maintenance ratio for this bracket +cum: number; // Auxiliary number for quick calculation ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; - pair?: string; -}): Promise -⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; - pair?: string; -}): Promise +export interface PortfolioCMLeverageBracket { + bracket: number; // bracket level + initialLeverage: number; // the maximum leverage + qtyCap: number; // upper edge of base asset quantity + qtyFloor: number; // lower edge of base asset quantity + maintMarginRatio: number; // maintenance margin rate + cum: number; // Auxiliary number for quick calculation +} ⋮---- -getOpenInterest(params: +bracket: number; // bracket level +initialLeverage: number; // the maximum leverage +qtyCap: number; // upper edge of base asset quantity +qtyFloor: number; // lower edge of base asset quantity +maintMarginRatio: number; // maintenance margin rate +cum: number; // Auxiliary number for quick calculation ⋮---- -getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise +export interface PortfolioTradingIndicator { + isLocked: boolean; + plannedRecoverTime: number; + indicator: PMIndicatorType; + value: number; + triggerValue: number; +} ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesCoinMLongShortAccountRatioParams, -): Promise +export interface PortfolioTradingStatus { + indicators: { + [key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" + }; + updateTime: number; +} ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams & { pair?: string }, -): Promise +[key: string]: PortfolioTradingIndicator[]; // key can be symbol or "ACCOUNT" ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +export interface PortfolioMarginLoanRecord { + txId: number; + asset: string; + principal: string; + timestamp: number; + status: PMMarginLoanStatus; +} ⋮---- -getTakerBuySellVolume( - params: FuturesCoinMTakerBuySellVolumeParams, -): Promise +export interface GetMarginLoanRecordsReq { + asset: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} ⋮---- -getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getIndexPriceConstituents(params: { - symbol: string; -}): Promise +export interface GetMarginRepayRecordsReq { + asset: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} ⋮---- -/** - * possibly @deprecated - * Only in old documentation, not in new one - **/ -getQuarterlyContractSettlementPrices(params: { - pair: string; -}): Promise +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- -/** - * - * Trade Endpoints - * - **/ +export interface PortfolioMarginRepayRecord { + amount: string; // Total amount repaid + asset: string; + interest: string; // Interest repaid + principal: string; // Principal repaid + status: PMMarginLoanStatus; + txId: number; +} ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +amount: string; // Total amount repaid ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - * - * Known issue: `quantity` and `price` should be sent as strings - */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> +interest: string; // Interest repaid +principal: string; // Principal repaid ⋮---- -/** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue - */ -modifyOrder( - params: ModifyFuturesOrderParams, -): Promise +export interface GetMarginInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; // Currently querying page. Start from 1. Default: 1 + size?: number; // Default: 10, Max: 100 + archived?: boolean; // Default: false. Set to true for archived data from 6 months ago +} ⋮---- -/** - * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. - */ -modifyMultipleOrders( - orders: ModifyFuturesOrderParams[], -): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> +current?: number; // Currently querying page. Start from 1. Default: 1 +size?: number; // Default: 10, Max: 100 +archived?: boolean; // Default: false. Set to true for archived data from 6 months ago ⋮---- -getOrderModifyHistory( - params: GetOrderModifyHistoryParams, -): Promise +export type PMInterestType = + | 'PERIODIC' // interest charged per hour + | 'ON_BORROW' // first interest charged on borrow + | 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB + | 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB + | 'PORTFOLIO'; // Portfolio Margin negative balance daily interest ⋮---- -cancelOrder(params: CancelOrderParams): Promise +| 'PERIODIC' // interest charged per hour +| 'ON_BORROW' // first interest charged on borrow +| 'PERIODIC_CONVERTED' // interest charged per hour converted into BNB +| 'ON_BORROW_CONVERTED' // first interest charged on borrow converted into BNB +| 'PORTFOLIO'; // Portfolio Margin negative balance daily interest ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +export interface PortfolioMarginInterestRecord { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset: string; + principal: string; + interest: string; + interestRate: string; + type: PMInterestType; +} ⋮---- -cancelAllOpenOrders(params: { - symbol?: string; -}): Promise +export interface GetPortfolioInterestHistoryReq { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; // Default: 10, Max: 100 +} ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, -): Promise +size?: number; // Default: 10, Max: 100 ⋮---- -getOrder(params: GetOrderParams): Promise +export interface PortfolioNegativeBalanceInterestRecord { + asset: string; + interest: string; // interest amount + interestAccuredTime: number; + interestRate: string; // daily interest rate + principal: string; +} ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +interest: string; // interest amount ⋮---- -getAllOpenOrders(params?: +interestRate: string; // daily interest rate ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +export type UMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR' + | 'REFERRAL_KICKBACK' + | 'COMMISSION_REBATE' + | 'API_REBATE' + | 'CONTEST_REWARD' + | 'CROSS_COLLATERAL_TRANSFER' + | 'OPTIONS_PREMIUM_FEE' + | 'OPTIONS_SETTLE_PROFIT' + | 'INTERNAL_TRANSFER' + | 'AUTO_EXCHANGE' + | 'DELIVERED_SETTELMENT' + | 'COIN_SWAP_DEPOSIT' + | 'COIN_SWAP_WITHDRAW' + | 'POSITION_LIMIT_INCREASE_FEE'; ⋮---- /** - * - * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) - * Conditional orders migrate to Algo Service on COIN-M - * - **/ + * UM income history query for `GET /papi/v1/um/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ +export interface QueryPortfolioUMIncomeReq { + symbol?: string; + incomeType?: UMIncomeType; + startTime?: number; + endTime?: number; + limit?: number; // Default 100; max 1000 +} ⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, -): Promise +limit?: number; // Default 100; max 1000 ⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, -): Promise +export interface PortfolioUMIncome { + symbol: string; // trade symbol, if existing + incomeType: UMIncomeType; + income: string; // income amount + asset: string; // income asset + info: string; // extra information + time: number; + tranId: string; // transaction id + tradeId: string; // trade id, if existing +} ⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, -): Promise +symbol: string; // trade symbol, if existing ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -getAccountTrades( - params: CoinMAccountTradeParams & { orderId?: number }, -): Promise -⋮---- -getPositions(params?: { - marginAsset?: string; - pair?: string; -}): Promise +tranId: string; // transaction id +tradeId: string; // trade id, if existing ⋮---- -setPositionMode(params: PositionModeParams): Promise +export type CMIncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'FUNDING_FEE' + | 'REALIZED_PNL' + | 'COMMISSION' + | 'INSURANCE_CLEAR' + | 'DELIVERED_SETTELMENT'; ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +/** + * CM income history query for `GET /papi/v1/cm/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted + * (removed 2026-10-28). + */ +export interface QueryPortfolioCMIncomeReq { + symbol?: string; + incomeType?: CMIncomeType; + startTime?: number; + endTime?: number; + limit?: number; // Default 100; max 1000 +} ⋮---- -setLeverage(params: SetLeverageParams): Promise +limit?: number; // Default 100; max 1000 ⋮---- -getADLQuantileEstimation(params?: +export interface PortfolioCMIncome { + symbol: string; // trade symbol, if existing + incomeType: CMIncomeType; + income: string; // income amount + asset: string; // income asset + info: string; // extra information + time: number; + tranId: string; // transaction id + tradeId: string; // trade id, if existing +} ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, -): Promise +symbol: string; // trade symbol, if existing ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, -): Promise -/** - * - * Account Endpoints - * - **/ +income: string; // income amount +asset: string; // income asset +info: string; // extra information ⋮---- -getBalance(): Promise +tranId: string; // transaction id +tradeId: string; // trade id, if existing ⋮---- -getAccountCommissionRate(params: { - symbol?: string; -}): Promise +export interface PortfolioUMAccountAsset { + asset: string; // asset name + crossWalletBalance: string; // wallet balance + crossUnPnl: string; // unrealized profit + maintMargin: string; // maintenance margin required + initialMargin: string; // total initial margin required with current mark price + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + updateTime: number; // last update time +} ⋮---- -getAccountInformation(): Promise +asset: string; // asset name +crossWalletBalance: string; // wallet balance +crossUnPnl: string; // unrealized profit +maintMargin: string; // maintenance margin required +initialMargin: string; // total initial margin required with current mark price +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +updateTime: number; // last update time ⋮---- -/** - * Notional Bracket for Symbol (NOT "pair") - */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; -}): Promise +export interface PortfolioUMAccountPosition { + symbol: string; // symbol name + initialMargin: string; // initial margin required with current mark price + maintMargin: string; // maintenance margin required + unrealizedProfit: string; // unrealized profit + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + leverage: string; // current initial leverage + entryPrice: string; // average entry price + maxNotional: string; // maximum available notional with current leverage + bidNotional: string; // bids notional + askNotional: string; // ask notional + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side + positionAmt: string; // position amount + updateTime: number; // last update time +} ⋮---- -// TO ADD: dapi/v1/leverageBracket -// can use dapi/v2/leverageBracket +symbol: string; // symbol name +initialMargin: string; // initial margin required with current mark price +maintMargin: string; // maintenance margin required +unrealizedProfit: string; // unrealized profit +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +leverage: string; // current initial leverage +entryPrice: string; // average entry price +maxNotional: string; // maximum available notional with current leverage +bidNotional: string; // bids notional +askNotional: string; // ask notional +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side +positionAmt: string; // position amount +updateTime: number; // last update time ⋮---- -getCurrentPositionMode(): Promise +export interface PortfolioCMAccountAsset { + asset: string; // asset name + crossWalletBalance: string; // total wallet balance + crossUnPnl: string; // unrealized profit or loss + maintMargin: string; // maintenance margin + initialMargin: string; // total initial margin required with the latest mark price + positionInitialMargin: string; // positions' margin required with the latest mark price + openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price + updateTime: number; // last update time +} ⋮---- -/** - * Query income history (`GET /dapi/v1/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -getIncomeHistory(params?: GetIncomeHistoryParams): Promise +asset: string; // asset name +crossWalletBalance: string; // total wallet balance +crossUnPnl: string; // unrealized profit or loss +maintMargin: string; // maintenance margin +initialMargin: string; // total initial margin required with the latest mark price +positionInitialMargin: string; // positions' margin required with the latest mark price +openOrderInitialMargin: string; // open orders' initial margin required with the latest mark price +updateTime: number; // last update time ⋮---- -getDownloadIdForFuturesTransactionHistory(params: { - startTime: number; - endTime: number; -}): Promise< +export interface PortfolioCMAccountPosition { + symbol: string; // symbol name + positionAmt: string; // position amount + initialMargin: string; + maintMargin: string; + unrealizedProfit: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + leverage: string; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode + entryPrice: string; + maxQty: string; // maximum quantity of base asset + updateTime: number; +} ⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; -}): Promise +symbol: string; // symbol name +positionAmt: string; // position amount ⋮---- -getDownloadIdForFuturesOrderHistory(params: { - startTime: number; - endTime: number; -}): Promise< +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // BOTH means that it is the position of One-way Mode ⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; -}): Promise +maxQty: string; // maximum quantity of base asset ⋮---- -getDownloadIdForFuturesTradeHistory(params: { - startTime: number; - endTime: number; -}): Promise< +export interface PortfolioUMAccountConfig { + feeTier: number; // account commission tier + canTrade: boolean; // if can trade + canDeposit: boolean; // if can transfer in asset + canWithdraw: boolean; // if can transfer out asset + dualSidePosition: boolean; + updateTime: number; // reserved property + multiAssetsMargin: boolean; + tradeGroupId: number; +} ⋮---- -getFuturesTradeHistoryDownloadLink(params: { - downloadId: string; -}): Promise +feeTier: number; // account commission tier +canTrade: boolean; // if can trade +canDeposit: boolean; // if can transfer in asset +canWithdraw: boolean; // if can transfer out asset ⋮---- -/** - * - * Portfolio Margin Endpoints - * - **/ +updateTime: number; // reserved property ⋮---- -getClassicPortfolioMarginAccount(params: { - asset: string; -}): Promise +export interface PortfolioUMSymbolConfig { + symbol: string; + marginType: 'CROSSED' | 'ISOLATED'; + isAutoAddMargin: string; // "true" or "false" as string + leverage: number; + maxNotionalValue: string; +} ⋮---- -/** - * @deprecated at 6th August, 2024 - **/ -getClassicPortfolioMarginNotionalLimits( - params?: GetClassicPortfolioMarginNotionalLimitParams, -): Promise< +isAutoAddMargin: string; // "true" or "false" as string ⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ +export interface PortfolioUMAccountAssetV2 { + asset: string; // asset name + crossWalletBalance: string; // wallet balance + crossUnPnl: string; // unrealized profit + maintMargin: string; // maintenance margin required + initialMargin: string; // total initial margin required with current mark price + positionInitialMargin: string; // initial margin required for positions with current mark price + openOrderInitialMargin: string; // initial margin required for open orders with current mark price + updateTime: number; // last update time +} ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, -): Promise< +asset: string; // asset name +crossWalletBalance: string; // wallet balance +crossUnPnl: string; // unrealized profit +maintMargin: string; // maintenance margin required +initialMargin: string; // total initial margin required with current mark price +positionInitialMargin: string; // initial margin required for positions with current mark price +openOrderInitialMargin: string; // initial margin required for open orders with current mark price +updateTime: number; // last update time ⋮---- -/** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, -): Promise< +export interface PortfolioUMAccountPositionV2 { + symbol: string; // symbol name + initialMargin: string; // initial margin required with current mark price + maintMargin: string; // maintenance margin required + unrealizedProfit: string; // unrealized profit + positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side + positionAmt: string; // position amount + updateTime: number; // last update time + notional: string; // position notional value +} ⋮---- -/** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise +symbol: string; // symbol name +initialMargin: string; // initial margin required with current mark price +maintMargin: string; // maintenance margin required +unrealizedProfit: string; // unrealized profit +positionSide: 'BOTH' | 'LONG' | 'SHORT'; // position side +positionAmt: string; // position amount +updateTime: number; // last update time +notional: string; // position notional value ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +export interface DownloadLinkResponse { + downloadId: string; + status: 'completed' | 'processing'; // Enum: completed, processing + url: string; // The link is mapped to download id + s3Link: string | null; + notified: boolean; // ignore + expirationTimestamp: number; // The link would expire after this timestamp + isExpired: boolean | null; +} ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +status: 'completed' | 'processing'; // Enum: completed, processing +url: string; // The link is mapped to download id ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +notified: boolean; // ignore +expirationTimestamp: number; // The link would expire after this timestamp ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +export interface PortfolioTradFiPerpsContractSignResponse { + code: number; + msg: string; +} + +================ +File: src/types/shared.ts +================ +// Generic numeric value stored as a string. Can be parsed via parseInt or parseFloat. +// Beautifier may convert these to number, if enabled. +export type numberInString = string | number; +⋮---- +export type ExchangeSymbol = string; +⋮---- +export type BooleanString = 'true' | 'false'; +⋮---- +export type BinanceBaseUrlKey = + | 'spot' + | 'spot1' + | 'spot2' + | 'spot3' + | 'spot4' + | 'spottest' + | 'usdmtest' + | 'usdm' + | 'coinm' + | 'coinmtest' + | 'voptions' + | 'voptionstest' + | 'papi' + | 'www'; ⋮---- /** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise + * Time in force. Note: `GTE_GTC` is not officially documented, use at your own risk. + */ +export type OrderTimeInForce = + | 'GTC' + | 'IOC' + | 'FOK' + | 'GTX' + | 'GTE_GTC' + | 'GTD' + | 'RPI'; +⋮---- +export type StringBoolean = 'TRUE' | 'FALSE'; +⋮---- +export type SideEffects = + | 'MARGIN_BUY' + | 'AUTO_REPAY' + | 'NO_SIDE_EFFECT' + | 'AUTO_BORROW_REPAY' + | 'NO_SIDE_EFFECT'; ⋮---- /** - * - * User Data Stream Endpoints - * - **/ + * ACK = confirmation of order acceptance (no placement/fill information) + * RESULT = fill state + * FULL = fill state + detail on fills and other detail + */ +export type OrderResponseType = 'ACK' | 'RESULT' | 'FULL'; ⋮---- -getFuturesUserDataListenKey(): Promise< +export type OrderIdProperty = + | 'newClientOrderId' + | 'newClientStrategyId' + | 'listClientOrderId' + | 'limitClientOrderId' + | 'stopClientOrderId' + | 'clientAlgoId' + | 'aboveClientOrderId' + | 'belowClientOrderId' + | 'workingClientOrderId' + | 'pendingAboveClientOrderId' + | 'pendingBelowClientOrderId' + | 'pendingClientOrderId'; ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +export type OrderSide = 'BUY' | 'SELL'; ⋮---- -closeFuturesUserDataListenKey(): Promise +export type OrderStatus = + | 'NEW' + | 'PENDING_NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'EXPIRED_IN_MATCH'; ⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, -): void - -================ -File: src/portfolio-client.ts -================ -import { AxiosRequestConfig } from 'axios'; +export type OrderExecutionType = + | 'NEW' + | 'CANCELED' + | 'REJECTED' + | 'TRADE' + | 'EXPIRED'; ⋮---- -import { - CancelPortfolioCMConditionalOrderReq, - CancelPortfolioCMOrderReq, - CancelPortfolioMarginOCOReq, - CancelPortfolioMarginOrderReq, - CancelPortfolioUMAlgoOrderReq, - CancelPortfolioUMConditionalOrderReq, - CancelPortfolioUMOrderReq, - DownloadLinkResponse, - GetMarginInterestHistoryReq, - GetMarginLoanRecordsReq, - GetMarginRepayRecordsReq, - GetPortfolioInterestHistoryReq, - ModifyPortfolioCMOrderReq, - ModifyPortfolioUMOrderReq, - NewPortfolioCMConditionalOrderReq, - NewPortfolioCMConditionalOrderResponse, - NewPortfolioCMOrderReq, - NewPortfolioCMOrderResponse, - NewPortfolioConditionalOrderResponse, - NewPortfolioMarginOCOReq, - NewPortfolioMarginOCOResponse, - NewPortfolioMarginOrderReq, - NewPortfolioMarginOrderResponse, - NewPortfolioUMAlgoOrderReq, - NewPortfolioUMConditionalOrderReq, - NewPortfolioUMOrderReq, - NewPortfolioUMOrderResponse, - PortfolioAccountInformation, - PortfolioADLQuantile, - PortfolioBalance, - PortfolioCMAccountAsset, - PortfolioCMAccountPosition, - PortfolioCMCancelConditionalOrderResponse, - PortfolioCMCancelOrderResponse, - PortfolioCMConditionalHistoryOrder, - PortfolioCMConditionalOrder, - PortfolioCMForceOrder, - PortfolioCMIncome, - PortfolioCMLeverageBracket, - PortfolioCMModifyOrderResponse, - PortfolioCMOrder, - PortfolioCMOrderModificationHistory, - PortfolioCMPosition, - PortfolioCMTrade, - PortfolioMarginCancelAllOrdersResponse, - PortfolioMarginCancelOrderResponse, - PortfolioMarginForceOrder, - PortfolioMarginInterestRecord, - PortfolioMarginLoanRecord, - PortfolioMarginOCO, - PortfolioMarginOCOCancelResponse, - PortfolioMarginOrder, - PortfolioMarginRepayDebtReq, - PortfolioMarginRepayDebtResponse, - PortfolioMarginRepayRecord, - PortfolioMarginTrade, - PortfolioNegativeBalanceInterestRecord, - PortfolioTradFiPerpsContractSignResponse, - PortfolioTradingStatus, - PortfolioUMAccountAsset, - PortfolioUMAccountAssetV2, - PortfolioUMAccountConfig, - PortfolioUMAccountPosition, - PortfolioUMAccountPositionV2, - PortfolioUMAlgoOrder, - PortfolioUMCancelAlgoOrderResponse, - PortfolioUMCancelAllUMAlgoOpenOrdersResponse, - PortfolioUMCancelConditionalOrderResponse, - PortfolioUMCancelOrderResponse, - PortfolioUMConditionalOrder, - PortfolioUMForceOrder, - PortfolioUMIncome, - PortfolioUMLeverageBracket, - PortfolioUMModifyOrderResponse, - PortfolioUMOrder, - PortfolioUMOrderModificationHistory, - PortfolioUMPosition, - PortfolioUMSymbolConfig, - PortfolioUMTrade, - QueryPortfolioAllCMConditionalOrdersReq, - QueryPortfolioAllCMOrdersReq, - QueryPortfolioAllUMAlgoOrdersReq, - QueryPortfolioAllUMConditionalOrdersReq, - QueryPortfolioAllUMOrdersReq, - QueryPortfolioCMConditionalOrderHistoryReq, - QueryPortfolioCMForceOrdersReq, - QueryPortfolioCMIncomeReq, - QueryPortfolioCMOpenOrderReq, - QueryPortfolioCMOrderAmendmentReq, - QueryPortfolioCMOrderReq, - QueryPortfolioCMTradesReq, - QueryPortfolioMarginAllOCOReq, - QueryPortfolioMarginAllOrdersReq, - QueryPortfolioMarginForceOrdersReq, - QueryPortfolioMarginOCOReq, - QueryPortfolioMarginOrderReq, - QueryPortfolioMarginTradesReq, - QueryPortfolioUMAlgoOrderReq, - QueryPortfolioUMConditionalOrderHistoryReq, - QueryPortfolioUMForceOrdersReq, - QueryPortfolioUMIncomeReq, - QueryPortfolioUMOpenConditionalOrderReq, - QueryPortfolioUMOpenOrderReq, - QueryPortfolioUMOrderAmendmentReq, - QueryPortfolioUMOrderReq, - QueryPortfolioUMTradesReq, -} from './types/portfolio-margin'; -import { - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - NewOCOParams, - OrderIdProperty, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; -⋮---- -/** - * REST client for Portfolio Margin APIs (papi) - * - * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info - */ -export class PortfolioClient extends BaseRestClient +export type OrderListContingencyType = + | 'OCO' + | 'OTO' + | 'OTOCO' + | 'OPO' + | 'OPOCO'; ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +// listStatusType +export type OCOStatus = 'RESPONSE' | 'EXEC_STARTED' | 'ALL_DONE'; ⋮---- -getClientId(): BinanceBaseUrlKey +// listOrderStatus +export type OCOOrderStatus = 'EXECUTING' | 'ALL_DONE' | 'REJECT'; ⋮---- -/** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise +export type OrderType = + | 'LIMIT' + | 'LIMIT_MAKER' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -/** - * - * Misc Endpoints - * - **/ +export type OrderListOrderType = + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; ⋮---- -testConnectivity(): Promise +export type SelfTradePreventionMode = + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE' + | 'DECREMENT' + | 'TRANSFER'; ⋮---- -signTradFiPerpsContract(): Promise +export interface BasicAssetParam { + asset: string; +} ⋮---- -/** - * - * DERIVATIVES -TRADE endpoints - * - **/ +export interface BasicSymbolParam { + symbol: string; + isIsolated?: StringBoolean; +} ⋮---- -submitNewUMOrder( - params: NewPortfolioUMOrderReq, -): Promise +export interface SymbolArrayParam { + symbols: string[]; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). - */ -submitNewUMConditionalOrder( - params: NewPortfolioUMConditionalOrderReq, -): Promise +export interface BasicAssetPaginatedParams { + asset?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +export interface BasicSymbolPaginatedParams { + symbol?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -submitNewUMAlgoOrder( - params: NewPortfolioUMAlgoOrderReq, -): Promise +export interface SymbolPrice { + symbol: string; + price: numberInString; + time?: number; +} ⋮---- -submitNewCMOrder( - params: NewPortfolioCMOrderReq, -): Promise +// used by spot and usdm +export interface OrderBookParams { + symbol: string; + limit?: 5 | 10 | 20 | 50 | 100 | 500 | 1000 | 5000; + symbolStatus?: string; +} ⋮---- -submitNewCMConditionalOrder( - params: NewPortfolioCMConditionalOrderReq, -): Promise +export type KlineInterval = + | '1s' + | '1m' + | '3m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '3d' + | '1w' + | '1M'; ⋮---- -submitNewMarginOrder( - params: NewPortfolioMarginOrderReq, -): Promise +export interface GetOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -submitMarginLoan(params: +export interface GetOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -submitMarginRepay(params: +export interface HistoricalTradesParams { + symbol: string; + limit?: number; + fromId?: number; +} ⋮---- -submitNewMarginOCO( - params: NewPortfolioMarginOCOReq, -): Promise +export interface KlinesParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -cancelUMOrder( - params: CancelPortfolioUMOrderReq, -): Promise +export type Kline = [ + number, // open time + numberInString, // open + numberInString, // high + numberInString, // low + numberInString, // close + numberInString, // volume + number, // close time + numberInString, // quote asset volume + number, // number of trades + numberInString, // taker buy base asset vol + numberInString, // taker buy quote asset vol + numberInString, // ignore? +]; ⋮---- -cancelAllUMOrders(params: +number, // open time +numberInString, // open +numberInString, // high +numberInString, // low +numberInString, // close +numberInString, // volume +number, // close time +numberInString, // quote asset volume +number, // number of trades +numberInString, // taker buy base asset vol +numberInString, // taker buy quote asset vol +numberInString, // ignore? ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). - */ -cancelUMConditionalOrder( - params: CancelPortfolioUMConditionalOrderReq, -): Promise +/** @deprecated `FuturesKline` will be removed soon. Use `Kline` instead. **/ +export type FuturesKline = Kline; +export interface RecentTradesParams { + symbol: string; + limit?: number; +} ⋮---- -cancelUMAlgoOrder( - params: CancelPortfolioUMAlgoOrderReq, -): Promise +export interface CancelOrderParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). - */ -cancelAllUMConditionalOrders(params: +export interface AmendKeepPriorityParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + newQty: numberInString; +} ⋮---- -cancelAllUMAlgoOpenOrders(params: { - symbol: string; -}): Promise +export interface CancelOCOParams { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; +} ⋮---- -cancelCMOrder( - params: CancelPortfolioCMOrderReq, -): Promise +export interface NewOCOParams { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + limitClientOrderId?: string; + limitStrategyId?: number; + limitStrategyType?: number; + price: number; + limitIcebergQty?: number; + trailingDelta?: number; + stopClientOrderId?: string; + stopPrice: number; + stopStrategyId?: number; + stopStrategyType?: number; + stopLimitPrice?: number; + stopIcebergQty?: number; + stopLimitTimeInForce?: OrderTimeInForce; + newOrderRespType?: OrderResponseType; + /** For isolated margin trading only */ + isIsolated?: StringBoolean; + /** Define a side effect, only for margin trading */ + sideEffectType?: SideEffects; +} ⋮---- -cancelAllCMOrders(params: +/** For isolated margin trading only */ ⋮---- -cancelCMConditionalOrder( - params: CancelPortfolioCMConditionalOrderReq, -): Promise +/** Define a side effect, only for margin trading */ ⋮---- -cancelAllCMConditionalOrders(params: +export interface NewOrderListParams< + T extends OrderResponseType = OrderResponseType, +> { + symbol: string; + listClientOrderId?: string; + side: OrderSide; + quantity: number; + aboveType: OrderListOrderType; + aboveClientOrderId?: string; + aboveIcebergQty?: number; + abovePrice?: number; + aboveStopPrice?: number; + aboveTrailingDelta?: number; + aboveTimeInForce?: OrderTimeInForce; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: OrderListOrderType; + belowClientOrderId?: string; + belowIcebergQty?: number; + belowPrice?: number; + belowStopPrice?: number; + belowTrailingDelta?: number; + belowTimeInForce?: OrderTimeInForce; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: T; + selfTradePreventionMode?: SelfTradePreventionMode; +} ⋮---- -cancelMarginOrder( - params: CancelPortfolioMarginOrderReq, -): Promise +export interface SymbolFromPaginatedRequestFromId { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -cancelMarginOCO( - params: CancelPortfolioMarginOCOReq, -): Promise +export interface GetAllOrdersParams { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -cancelAllMarginOrders(params: { - symbol: string; -}): Promise +export interface RateLimiter { + rateLimitType: 'REQUEST_WEIGHT' | 'ORDERS' | 'RAW_REQUESTS'; + interval: 'SECOND' | 'MINUTE' | 'DAY'; + intervalNum: number; + limit: number; +} ⋮---- -modifyUMOrder( - params: ModifyPortfolioUMOrderReq, -): Promise +export interface SymbolPriceFilter { + filterType: 'PRICE_FILTER'; + minPrice: numberInString; + maxPrice: numberInString; + tickSize: numberInString; +} ⋮---- -modifyCMOrder( - params: ModifyPortfolioCMOrderReq, -): Promise +export interface SymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -getUMOrder(params: QueryPortfolioUMOrderReq): Promise +export interface SymbolPercentPriceBySideFilter { + filterType: 'PERCENT_PRICE_BY_SIDE'; + bidMultiplierUp: numberInString; + bidMultiplierDown: numberInString; + askMultiplierUp: numberInString; + askMultiplierDown: numberInString; + avgPriceMins: number; +} ⋮---- -getAllUMOrders( - params: QueryPortfolioAllUMOrdersReq, -): Promise +export interface SymbolLegacyMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + minNotional: numberInString; + applyToMarket: boolean; + avgPriceMins: number; +} ⋮---- -getUMOpenOrder( - params: QueryPortfolioUMOpenOrderReq, -): Promise +export interface SymbolLotSizeFilter { + filterType: 'LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -getAllUMOpenOrders(params: +export interface SymbolMinNotionalFilter { + filterType: 'NOTIONAL'; + minNotional: numberInString; + applyMinToMarket: boolean; + maxNotional: numberInString; + applyMaxToMarket: boolean; + avgPriceMins: number; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). - */ -getAllUMConditionalOrders( - params: QueryPortfolioAllUMConditionalOrdersReq, -): Promise +export interface SymbolIcebergPartsFilter { + filterType: 'ICEBERG_PARTS'; + limit: number; +} ⋮---- -getAllUMAlgoOrders( - params: QueryPortfolioAllUMAlgoOrdersReq, -): Promise +export interface SymbolMarketLotSizeFilter { + filterType: 'MARKET_LOT_SIZE'; + minQty: numberInString; + maxQty: numberInString; + stepSize: numberInString; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). - */ -getUMOpenConditionalOrders(params: { - symbol?: string; -}): Promise +export interface SymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -getUMAlgoOpenOrders(params?: { - symbol?: string; -}): Promise +export interface SymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -/** - * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). - */ -getUMOpenConditionalOrder( - params: QueryPortfolioUMOpenConditionalOrderReq, -): Promise +export interface SymbolMaxIcebergOrdersFilter { + filterType: 'MAX_NUM_ICEBERG_ORDERS'; + maxNumIcebergOrders: number; +} ⋮---- -getUMAlgoOrder( - params: QueryPortfolioUMAlgoOrderReq, -): Promise +export interface SymbolMaxPositionFilter { + filterType: 'MAX_POSITION'; + maxPosition: numberInString; +} ⋮---- -/** - * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. - */ -getUMConditionalOrderHistory( - params: QueryPortfolioUMConditionalOrderHistoryReq, -): Promise +export type SymbolFilter = + | SymbolPriceFilter + | SymbolPercentPriceFilter + | SymbolPercentPriceBySideFilter + | SymbolLegacyMinNotionalFilter + | SymbolLotSizeFilter + | SymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | SymbolMaxOrdersFilter + | SymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter; ⋮---- -getCMOrder(params: QueryPortfolioCMOrderReq): Promise +export interface ExchangeMaxNumOrdersFilter { + filterType: 'EXCHANGE_MAX_NUM_ORDERS'; + maxNumOrders: number; +} ⋮---- -getAllCMOrders( - params: QueryPortfolioAllCMOrdersReq, -): Promise +export interface ExchangeMaxAlgoOrdersFilter { + filterType: 'EXCHANGE_MAX_ALGO_ORDERS'; + maxNumAlgoOrders: number; +} ⋮---- -getCMOpenOrder( - params: QueryPortfolioCMOpenOrderReq, -): Promise +export type ExchangeFilter = + | ExchangeMaxNumOrdersFilter + | ExchangeMaxAlgoOrdersFilter; ⋮---- -getAllCMOpenOrders(params: { - symbol?: string; - pair?: string; -}): Promise +export type OrderBookPrice = numberInString; +export type OrderBookAmount = numberInString; ⋮---- -getCMOpenConditionalOrders(params: { - symbol?: string; -}): Promise +export type OrderBookRow = [OrderBookPrice, OrderBookAmount]; ⋮---- -getCMOpenConditionalOrder(params: { - symbol: string; - strategyId?: number; - newClientStrategyId?: string; -}): Promise +export type OrderBookPriceFormatted = number; +export type OrderBookAmountFormatted = number; +export type OrderBookRowFormatted = [ + OrderBookPriceFormatted, + OrderBookAmountFormatted, +]; ⋮---- -getAllCMConditionalOrders( - params: QueryPortfolioAllCMConditionalOrdersReq, -): Promise +export interface GenericCodeMsgError { + code: number; + msg: string; +} ⋮---- -getCMConditionalOrderHistory( - params: QueryPortfolioCMConditionalOrderHistoryReq, -): Promise +export interface RowsWithTotal { + rows: T[]; + total: number; +} ⋮---- -getUMForceOrders( - params: QueryPortfolioUMForceOrdersReq, -): Promise +export interface CoinStartEndLimit { + coin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} + +================ +File: src/coinm-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; ⋮---- -getCMForceOrders( - params: QueryPortfolioCMForceOrdersReq, -): Promise +import { + ClassicPortfolioMarginAccount, + ClassicPortfolioMarginNotionalLimit, + CoinMAccountTradeParams, + CoinMOpenInterest, + CoinMPositionTrade, + CoinMSymbolOrderBookTicker, + FundingRate, + FuturesTransactionHistoryDownloadLink, + GetClassicPortfolioMarginNotionalLimitParams, + PositionRisk, +} from './types/coin'; +import { + AggregateFuturesTrade, + CancelAllOpenOrdersResult, + CancelFuturesOrderResult, + CancelMultipleOrdersParams, + CancelOrdersTimeoutParams, + ChangeStats24hr, + ContinuousContractKlinesParams, + ForceOrderResult, + FundingRateHistory, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, + FuturesCoinMAccountBalance, + FuturesCoinMAccountInformation, + FuturesCoinMBasisParams, + FuturesCoinMLongShortAccountRatioParams, + FuturesCoinMTakerBuySellVolumeParams, + FuturesDataPaginatedParams, + FuturesExchangeInfo, + FuturesNewAlgoOrderParams, + FuturesOrderBook, + FuturesQueryOpenAlgoOrdersParams, + GetForceOrdersParams, + GetIncomeHistoryParams, + GetPositionMarginChangeHistoryParams, + IncomeHistory, + IndexPriceConstituents, + IndexPriceKlinesParams, + MarkPrice, + ModeChangeResult, + ModifyFuturesOrderParams, + ModifyFuturesOrderResult, + NewFuturesOrderParams, + NewOrderError, + NewOrderResult, + OrderAmendment, + OrderResult, + PositionModeParams, + PositionModeResponse, + QuarterlyContractSettlementPrice, + RawFuturesTrade, + RebateDataOverview, + SetCancelTimeoutResult, + SetIsolatedMarginParams, + SetIsolatedMarginResult, + SetLeverageParams, + SetLeverageResult, + SetMarginTypeParams, + SymbolKlinePaginatedParams, + SymbolLeverageBracketsResult, + UserCommissionRate, +} from './types/futures'; +import { + BasicSymbolPaginatedParams, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + GenericCodeMsgError, + GetAllOrdersParams, + GetOrderModifyHistoryParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, + OrderBookParams, + OrderIdProperty, + RecentTradesParams, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import BaseRestClient from './util/BaseRestClient'; +import { + asArray, + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, +} from './util/requestUtils'; ⋮---- -getUMOrderModificationHistory( - params: QueryPortfolioUMOrderAmendmentReq, -): Promise +export class CoinMClient extends BaseRestClient ⋮---- -getCMOrderModificationHistory( - params: QueryPortfolioCMOrderAmendmentReq, -): Promise +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) ⋮---- -getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -getUMTrades(params: QueryPortfolioUMTradesReq): Promise +/** + * + * Market Data Endpoints + * + **/ ⋮---- -getCMTrades(params: QueryPortfolioCMTradesReq): Promise +testConnectivity(): Promise ⋮---- -getUMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/um/adlQuantile', params); +getExchangeInfo(): Promise ⋮---- -getCMADLQuantile(params: { symbol?: string }): Promise< - { - symbol: string; - adlQuantile: PortfolioADLQuantile; - }[] - > { - return this.getPrivate('papi/v1/cm/adlQuantile', params); +getOrderBook(params: OrderBookParams): Promise ⋮---- -toggleUMFeeBurn(params: { - feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off -}): Promise< +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +getHistoricalTrades( + params: HistoricalTradesParams, +): Promise ⋮---- -getUMFeeBurnStatus(): Promise< +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise ⋮---- -getMarginOrder( - params: QueryPortfolioMarginOrderReq, -): Promise +/** + * Index Price and Mark Price + */ +getMarkPrice(params?: ⋮---- -getMarginOpenOrders(params: { - symbol: string; -}): Promise +getFundingRateHistory( + params?: Partial, +): Promise ⋮---- -getAllMarginOrders( - params: QueryPortfolioMarginAllOrdersReq, -): Promise +getFundingRate(params?: ⋮---- -getMarginOCO( - params: QueryPortfolioMarginOCOReq, -): Promise +getKlines(params: KlinesParams): Promise ⋮---- -getAllMarginOCO( - params: QueryPortfolioMarginAllOCOReq, -): Promise +getContinuousContractKlines( + params: ContinuousContractKlinesParams, +): Promise ⋮---- -getMarginOpenOCO(): Promise +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- -getMarginTrades( - params: QueryPortfolioMarginTradesReq, -): Promise +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -repayMarginDebt( - params: PortfolioMarginRepayDebtReq, -): Promise +getPremiumIndexKlines(params: KlinesParams): Promise ⋮---- -/** - * - * DERIVATIVES - ACCOUNT endpoints - * - **/ +get24hrChangeStatistics(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -getBalance(params?: +getSymbolPriceTicker(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -getAccountInfo(): Promise +getSymbolOrderBookTicker(params?: { + symbol?: string; + pair?: string; +}): Promise ⋮---- -getMarginMaxBorrow(params: +getOpenInterest(params: ⋮---- -amount: string; // account's currently max borrowable amount with sufficient system availability -borrowLimit: string; // max borrowable amount limited by the account level +getOpenInterestStatistics(params: FuturesDataPaginatedParams): Promise ⋮---- -getMarginMaxWithdraw(params: +getTopTradersLongShortAccountRatio( + params: FuturesCoinMLongShortAccountRatioParams, +): Promise ⋮---- -amount: string; // max withdrawable amount +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams & { pair?: string }, +): Promise ⋮---- -getUMPosition(params?: +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -getCMPosition(params?: { - marginAsset?: string; - pair?: string; -}): Promise +getTakerBuySellVolume( + params: FuturesCoinMTakerBuySellVolumeParams, +): Promise +⋮---- +getCompositeSymbolIndex(params: FuturesCoinMBasisParams): Promise ⋮---- /** - * Change UM initial leverage (`POST /papi/v1/um/leverage`). - * `leverage` is an unbounded number here. The maximum is symbol-specific: - * bracket 1 `initialLeverage` from `GET /papi/v1/um/leverageBracket` - * (Binance derivatives changelog 2026-10-09). - */ -updateUMLeverage(params: + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getIndexPriceConstituents(params: { + symbol: string; +}): Promise ⋮---- -updateCMLeverage(params: +/** + * possibly @deprecated + * Only in old documentation, not in new one + **/ +getQuarterlyContractSettlementPrices(params: { + pair: string; +}): Promise ⋮---- -updateUMPositionMode(params: { - dualSidePosition: 'true' | 'false'; -}): Promise< +/** + * + * Trade Endpoints + * + **/ ⋮---- -updateCMPositionMode(params: { - dualSidePosition: 'true' | 'false'; -}): Promise< +submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- -getUMPositionMode(): Promise< +/** + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + * + * Known issue: `quantity` and `price` should be sent as strings + */ +submitMultipleOrders( + orders: NewFuturesOrderParams[], +): Promise<(NewOrderResult | NewOrderError)[]> ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode +/** + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, +): Promise ⋮---- -getCMPositionMode(): Promise< +/** + * Warning: max 5 orders at a time! This method does not throw, instead it returns individual errors in the response array if any orders were rejected. + */ +modifyMultipleOrders( + orders: ModifyFuturesOrderParams[], +): Promise<(ModifyFuturesOrderResult | NewOrderError)[]> ⋮---- -dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode +getOrderModifyHistory( + params: GetOrderModifyHistoryParams, +): Promise ⋮---- -getUMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - notionalCoef: string; - brackets: PortfolioUMLeverageBracket[]; - }[] - > { - return this.getPrivate('papi/v1/um/leverageBracket', params); +cancelOrder(params: CancelOrderParams): Promise ⋮---- -getCMLeverageBrackets(params?: { symbol?: string }): Promise< - { - symbol: string; - brackets: PortfolioCMLeverageBracket[]; - }[] - > { - return this.getPrivate('papi/v1/cm/leverageBracket', params); +cancelMultipleOrders( + params: CancelMultipleOrdersParams, +): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -getUMTradingStatus(params?: { +cancelAllOpenOrders(params: { symbol?: string; -}): Promise -⋮---- -getUMCommissionRate(params: +}): Promise ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, +): Promise ⋮---- -getCMCommissionRate(params: +getOrder(params: GetOrderParams): Promise ⋮---- -makerCommissionRate: string; // e.g., "0.0002" for 0.02% -takerCommissionRate: string; // e.g., "0.0004" for 0.04% +getAllOrders(params: GetAllOrdersParams): Promise ⋮---- -getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< +getAllOpenOrders(params?: ⋮---- -getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< +getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -getAutoRepayFuturesStatus(): Promise< +/** + * + * Algo Order Endpoints (Effective 2026-06-30, CM-UM integration) + * Conditional orders migrate to Algo Service on COIN-M + * + **/ ⋮---- -autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise ⋮---- -updateAutoRepayFuturesStatus(params: { - autoRepay: 'true' | 'false'; -}): Promise< +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise ⋮---- -getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise ⋮---- -repayFuturesNegativeBalance(): Promise< +getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- -getPortfolioNegativeBalanceInterestHistory( - params?: GetPortfolioInterestHistoryReq, -): Promise +getAccountTrades( + params: CoinMAccountTradeParams & { orderId?: number }, +): Promise ⋮---- -autoCollectFunds(): Promise< +getPositions(params?: { + marginAsset?: string; + pair?: string; +}): Promise ⋮---- -/** - * Fund collection by asset (`POST /papi/v1/asset-collection`). - * - * Optional `amount` and `futureType` must be sent together. `futureType` - * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). - * If neither is sent, collection behavior is unchanged. - */ -transferAssetFuturesMargin(params: { - asset: string; - amount?: number; - futureType?: 'UM' | 'CM' | 'OPTION'; -}): Promise< +setPositionMode(params: PositionModeParams): Promise ⋮---- -transferBNB(params: { - amount: string; - transferSide: 'TO_UM' | 'FROM_UM'; -}): Promise< +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -tranId: number; // transaction id +setLeverage(params: SetLeverageParams): Promise ⋮---- -getUMIncomeHistory( - params?: QueryPortfolioUMIncomeReq, -): Promise +getADLQuantileEstimation(params?: ⋮---- -getCMIncomeHistory( - params?: QueryPortfolioCMIncomeReq, -): Promise +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, +): Promise ⋮---- -getUMAccount(): Promise< +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, +): Promise +/** + * + * Account Endpoints + * + **/ ⋮---- -positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market +getBalance(): Promise ⋮---- -getCMAccount(): Promise< +getAccountCommissionRate(params: { + symbol?: string; +}): Promise ⋮---- -getUMAccountConfig(): Promise +getAccountInformation(): Promise ⋮---- -getUMSymbolConfig(params?: { +/** + * Notional Bracket for Symbol (NOT "pair") + */ +getNotionalAndLeverageBrackets(params?: { symbol?: string; -}): Promise +}): Promise ⋮---- -getUMAccountV2(): Promise< +// TO ADD: dapi/v1/leverageBracket +// can use dapi/v2/leverageBracket ⋮---- -positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market +getCurrentPositionMode(): Promise ⋮---- -getUMTradeHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms +/** + * Query income history (`GET /dapi/v1/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getIncomeHistory(params?: GetIncomeHistoryParams): Promise +⋮---- +/** + * Get a download id for futures transaction history (`GET /dapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. + */ +getDownloadIdForFuturesTransactionHistory(params: { + startTime: number; + endTime: number; }): Promise< ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +getDownloadIdForFuturesOrderHistory(params: { + startTime: number; + endTime: number; +}): Promise< ⋮---- -getUMTradeDownloadLink(params: { +getFuturesOrderHistoryDownloadLink(params: { downloadId: string; -}): Promise +}): Promise ⋮---- -getUMOrderHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms +getDownloadIdForFuturesTradeHistory(params: { + startTime: number; + endTime: number; }): Promise< ⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms -⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days -⋮---- -getUMOrderDownloadLink(params: { +getFuturesTradeHistoryDownloadLink(params: { downloadId: string; -}): Promise -⋮---- -getUMTransactionHistoryDownloadId(params: { - startTime: number; // Timestamp in ms - endTime: number; // Timestamp in ms -}): Promise< -⋮---- -startTime: number; // Timestamp in ms -endTime: number; // Timestamp in ms +}): Promise ⋮---- -avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +/** + * + * Portfolio Margin Endpoints + * + **/ ⋮---- -getUMTransactionDownloadLink(params: { - downloadId: string; -}): Promise +getClassicPortfolioMarginAccount(params: { + asset: string; +}): Promise ⋮---- /** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewPortfolioUMOrderReq - | CancelOrderParams - | NewOCOParams - | CancelOCOParams, - orderIdProperty: OrderIdProperty, -): void + * @deprecated at 6th August, 2024 + **/ +getClassicPortfolioMarginNotionalLimits( + params?: GetClassicPortfolioMarginNotionalLimitParams, +): Promise< ⋮---- /** * - * User Data Stream Endpoints + * Broker Futures Endpoints + * Possibly @deprecated, found only in old docs + * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker * **/ -getPMUserDataListenKey(): Promise< -⋮---- -keepAlivePMUserDataListenKey(): Promise -⋮---- -closePMUserDataListenKey(): Promise - -================ -File: src/usdm-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; ⋮---- -import { FundingRate } from './types/coin'; -import { - AggregateFuturesTrade, - Basis, - BasisParams, - CancelAllOpenOrdersResult, - CancelFuturesOrderResult, - CancelMultipleOrdersParams, - CancelOrdersTimeoutParams, - ChangeStats24hr, - ContinuousContractKlinesParams, - ForceOrderResult, - FundingRateHistory, - FuturesAccountBalance, - FuturesAccountConfig, - FuturesAccountInformation, - FuturesAlgoOrderResponse, - FuturesCancelAlgoOrderParams, - FuturesCancelAlgoOrderResponse, - FuturesCancelAllAlgoOpenOrdersResponse, - FuturesConvertOrderStatus, - FuturesConvertPair, - FuturesConvertQuote, - FuturesConvertQuoteRequest, - FuturesDataPaginatedParams, - FuturesExchangeInfo, - FuturesNewAlgoOrderParams, - FuturesOrderBook, - FuturesPosition, - FuturesPositionTrade, - FuturesPositionV3, - FuturesQueryAlgoOrderParams, - FuturesQueryAlgoOrderResponse, - FuturesQueryAllAlgoOrdersParams, - FuturesQueryOpenAlgoOrdersParams, - FuturesSymbolOrderBookTicker, - FuturesTradeHistoryDownloadId, - FuturesTransactionDownloadLink, - GetForceOrdersParams, - GetFuturesAllOrdersParams, - GetFuturesOrderModifyHistoryParams, - GetIncomeHistoryParams, - GetPositionMarginChangeHistoryParams, - HistoricOpenInterest, - IncomeHistory, - IndexPriceConstituents, - IndexPriceKlinesParams, - InsuranceFundBalance, - MarkPrice, - ModeChangeResult, - ModifyFuturesOrderParams, - ModifyFuturesOrderResult, - ModifyOrderParams, - MultiAssetModeResponse, - MultiAssetsMode, - NewFuturesOrderParams, - NewOrderError, - NewOrderResult, - OpenInterest, - OrderResult, - PortfolioMarginProAccountInfo, - PositionModeParams, - PositionModeResponse, - QuarterlyContractSettlementPrice, - RawFuturesTrade, - RebateDataOverview, - RpiOrderBook, - SetCancelTimeoutResult, - SetIsolatedMarginParams, - SetIsolatedMarginResult, - SetLeverageParams, - SetLeverageResult, - SetMarginTypeParams, - SymbolAdlRisk, - SymbolConfig, - SymbolKlinePaginatedParams, - SymbolLeverageBracketsResult, - TradingSchedule, - UserCommissionRate, - UserForceOrder, -} from './types/futures'; -import { - BasicSymbolPaginatedParams, - BasicSymbolParam, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - GenericCodeMsgError, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - numberInString, - OrderBookParams, - OrderIdProperty, - RecentTradesParams, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import BaseRestClient from './util/BaseRestClient'; -import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, - RestClientOptions, -} from './util/requestUtils'; +/** + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, +): Promise< ⋮---- -export class USDMClient extends BaseRestClient +/** + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, +): Promise< ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +/** + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise ⋮---- /** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(): Promise + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- /** - * - * MARKET DATA endpoints - Rest API - * + * @deprecated **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- -testConnectivity(): Promise +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -getExchangeInfo(): Promise +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -getOrderBook(params: OrderBookParams): Promise +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -getRpiOrderBook(params: { - symbol: string; - limit?: number; -}): Promise +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -getRecentTrades(params: RecentTradesParams): Promise +getFuturesUserDataListenKey(): Promise< ⋮---- -getHistoricalTrades( - params: HistoricalTradesParams, -): Promise +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise +closeFuturesUserDataListenKey(): Promise ⋮---- -getKlines(params: KlinesParams): Promise +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void + +================ +File: src/portfolio-client.ts +================ +import { AxiosRequestConfig } from 'axios'; ⋮---- -getContinuousContractKlines( - params: ContinuousContractKlinesParams, -): Promise +import { + CancelPortfolioCMConditionalOrderReq, + CancelPortfolioCMOrderReq, + CancelPortfolioMarginOCOReq, + CancelPortfolioMarginOrderReq, + CancelPortfolioUMAlgoOrderReq, + CancelPortfolioUMConditionalOrderReq, + CancelPortfolioUMOrderReq, + DownloadLinkResponse, + GetMarginInterestHistoryReq, + GetMarginLoanRecordsReq, + GetMarginRepayRecordsReq, + GetPortfolioInterestHistoryReq, + ModifyPortfolioCMOrderReq, + ModifyPortfolioUMOrderReq, + NewPortfolioCMConditionalOrderReq, + NewPortfolioCMConditionalOrderResponse, + NewPortfolioCMOrderReq, + NewPortfolioCMOrderResponse, + NewPortfolioConditionalOrderResponse, + NewPortfolioMarginOCOReq, + NewPortfolioMarginOCOResponse, + NewPortfolioMarginOrderReq, + NewPortfolioMarginOrderResponse, + NewPortfolioUMAlgoOrderReq, + NewPortfolioUMConditionalOrderReq, + NewPortfolioUMOrderReq, + NewPortfolioUMOrderResponse, + PortfolioAccountInformation, + PortfolioADLQuantile, + PortfolioBalance, + PortfolioCMAccountAsset, + PortfolioCMAccountPosition, + PortfolioCMCancelConditionalOrderResponse, + PortfolioCMCancelOrderResponse, + PortfolioCMConditionalHistoryOrder, + PortfolioCMConditionalOrder, + PortfolioCMForceOrder, + PortfolioCMIncome, + PortfolioCMLeverageBracket, + PortfolioCMModifyOrderResponse, + PortfolioCMOrder, + PortfolioCMOrderModificationHistory, + PortfolioCMPosition, + PortfolioCMTrade, + PortfolioMarginCancelAllOrdersResponse, + PortfolioMarginCancelOrderResponse, + PortfolioMarginForceOrder, + PortfolioMarginInterestRecord, + PortfolioMarginLoanRecord, + PortfolioMarginOCO, + PortfolioMarginOCOCancelResponse, + PortfolioMarginOrder, + PortfolioMarginRepayDebtReq, + PortfolioMarginRepayDebtResponse, + PortfolioMarginRepayRecord, + PortfolioMarginTrade, + PortfolioNegativeBalanceInterestRecord, + PortfolioTradFiPerpsContractSignResponse, + PortfolioTradingStatus, + PortfolioUMAccountAsset, + PortfolioUMAccountAssetV2, + PortfolioUMAccountConfig, + PortfolioUMAccountPosition, + PortfolioUMAccountPositionV2, + PortfolioUMAlgoOrder, + PortfolioUMCancelAlgoOrderResponse, + PortfolioUMCancelAllUMAlgoOpenOrdersResponse, + PortfolioUMCancelConditionalOrderResponse, + PortfolioUMCancelOrderResponse, + PortfolioUMConditionalOrder, + PortfolioUMForceOrder, + PortfolioUMIncome, + PortfolioUMLeverageBracket, + PortfolioUMModifyOrderResponse, + PortfolioUMOrder, + PortfolioUMOrderModificationHistory, + PortfolioUMPosition, + PortfolioUMSymbolConfig, + PortfolioUMTrade, + QueryPortfolioAllCMConditionalOrdersReq, + QueryPortfolioAllCMOrdersReq, + QueryPortfolioAllUMAlgoOrdersReq, + QueryPortfolioAllUMConditionalOrdersReq, + QueryPortfolioAllUMOrdersReq, + QueryPortfolioCMConditionalOrderHistoryReq, + QueryPortfolioCMForceOrdersReq, + QueryPortfolioCMIncomeReq, + QueryPortfolioCMOpenOrderReq, + QueryPortfolioCMOrderAmendmentReq, + QueryPortfolioCMOrderReq, + QueryPortfolioCMTradesReq, + QueryPortfolioMarginAllOCOReq, + QueryPortfolioMarginAllOrdersReq, + QueryPortfolioMarginForceOrdersReq, + QueryPortfolioMarginOCOReq, + QueryPortfolioMarginOrderReq, + QueryPortfolioMarginTradesReq, + QueryPortfolioUMAlgoOrderReq, + QueryPortfolioUMConditionalOrderHistoryReq, + QueryPortfolioUMForceOrdersReq, + QueryPortfolioUMIncomeReq, + QueryPortfolioUMOpenConditionalOrderReq, + QueryPortfolioUMOpenOrderReq, + QueryPortfolioUMOrderAmendmentReq, + QueryPortfolioUMOrderReq, + QueryPortfolioUMTradesReq, +} from './types/portfolio-margin'; +import { + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + NewOCOParams, + OrderIdProperty, +} from './types/shared'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, +} from './util/requestUtils'; ⋮---- -getIndexPriceKlines(params: IndexPriceKlinesParams): Promise +/** + * REST client for Portfolio Margin APIs (papi) + * + * https://developers.binance.com/docs/derivatives/portfolio-margin/general-info + */ +export class PortfolioClient extends BaseRestClient ⋮---- -getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) ⋮---- -getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise +getClientId(): BinanceBaseUrlKey ⋮---- -getMarkPrice(params: +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- -getMarkPrice(): Promise; +/** + * + * Misc Endpoints + * + **/ ⋮---- -getMarkPrice(params?: +testConnectivity(): Promise ⋮---- -getFundingRateHistory( - params?: Partial, -): Promise +signTradFiPerpsContract(): Promise ⋮---- -getFundingRates(): Promise +/** + * + * DERIVATIVES -TRADE endpoints + * + **/ ⋮---- -get24hrChangeStatistics(params: +submitNewUMOrder( + params: NewPortfolioUMOrderReq, +): Promise ⋮---- -get24hrChangeStatistics(): Promise; +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.submitNewUMAlgoOrder} (`POST /papi/v1/um/algo/order`). + */ +submitNewUMConditionalOrder( + params: NewPortfolioUMConditionalOrderReq, +): Promise ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; -}): Promise +submitNewUMAlgoOrder( + params: NewPortfolioUMAlgoOrderReq, +): Promise ⋮---- -getSymbolPriceTicker(params: +submitNewCMOrder( + params: NewPortfolioCMOrderReq, +): Promise ⋮---- -getSymbolPriceTicker(): Promise; +submitNewCMConditionalOrder( + params: NewPortfolioCMConditionalOrderReq, +): Promise ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; -}): Promise +submitNewMarginOrder( + params: NewPortfolioMarginOrderReq, +): Promise ⋮---- -getSymbolPriceTickerV2(params: +submitMarginLoan(params: ⋮---- -getSymbolPriceTickerV2(): Promise; +submitMarginRepay(params: ⋮---- -getSymbolPriceTickerV2(params?: { - symbol?: string; -}): Promise +submitNewMarginOCO( + params: NewPortfolioMarginOCOReq, +): Promise ⋮---- -getSymbolOrderBookTicker(params: { - symbol: string; - }): Promise; +cancelUMOrder( + params: CancelPortfolioUMOrderReq, +): Promise ⋮---- -getSymbolOrderBookTicker(): Promise; +cancelAllUMOrders(params: ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; -}): Promise +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelUMAlgoOrder} (`DELETE /papi/v1/um/algo/order`). + */ +cancelUMConditionalOrder( + params: CancelPortfolioUMConditionalOrderReq, +): Promise ⋮---- -getQuarterlyContractSettlementPrices(params: { - pair: string; -}): Promise +cancelUMAlgoOrder( + params: CancelPortfolioUMAlgoOrderReq, +): Promise ⋮---- -getOpenInterest(params: +/** + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.cancelAllUMAlgoOpenOrders} (`DELETE /papi/v1/um/algo/allOpenOrders`). + */ +cancelAllUMConditionalOrders(params: ⋮---- -getOpenInterestStatistics( - params: FuturesDataPaginatedParams, -): Promise +cancelAllUMAlgoOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -getTopTradersLongShortPositionRatio( - params: FuturesDataPaginatedParams, -): Promise +cancelCMOrder( + params: CancelPortfolioCMOrderReq, +): Promise ⋮---- -getTopTradersLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +cancelAllCMOrders(params: ⋮---- -getGlobalLongShortAccountRatio( - params: FuturesDataPaginatedParams, -): Promise +cancelCMConditionalOrder( + params: CancelPortfolioCMConditionalOrderReq, +): Promise ⋮---- -getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise +cancelAllCMConditionalOrders(params: ⋮---- -getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +cancelMarginOrder( + params: CancelPortfolioMarginOrderReq, +): Promise ⋮---- -getCompositeSymbolIndex(params?: +cancelMarginOCO( + params: CancelPortfolioMarginOCOReq, +): Promise ⋮---- -getMultiAssetsModeAssetIndex(params?: +cancelAllMarginOrders(params: { + symbol: string; +}): Promise ⋮---- -/** - * Possibly @deprecated, found only in old docs - **/ -getBasis(params: BasisParams): Promise +modifyUMOrder( + params: ModifyPortfolioUMOrderReq, +): Promise ⋮---- -getIndexPriceConstituents(params: { - symbol: string; -}): Promise +modifyCMOrder( + params: ModifyPortfolioCMOrderReq, +): Promise ⋮---- -getInsuranceFundBalance(params?: { - symbol?: string; -}): Promise +getUMOrder(params: QueryPortfolioUMOrderReq): Promise ⋮---- -getTradingSchedule(): Promise +getAllUMOrders( + params: QueryPortfolioAllUMOrdersReq, +): Promise +⋮---- +getUMOpenOrder( + params: QueryPortfolioUMOpenOrderReq, +): Promise +⋮---- +getAllUMOpenOrders(params: ⋮---- /** - * - * TRADE endpoints - Rest API - * - **/ + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getAllUMAlgoOrders} (`GET /papi/v1/um/algo/allAlgoOrders`). + */ +getAllUMConditionalOrders( + params: QueryPortfolioAllUMConditionalOrdersReq, +): Promise ⋮---- -submitNewOrder(params: NewFuturesOrderParams): Promise +getAllUMAlgoOrders( + params: QueryPortfolioAllUMAlgoOrdersReq, +): Promise ⋮---- /** - * Warning: max 5 orders at a time! This method does not throw, instead it returns - * individual errors in the response array if any orders were rejected. - * - * Note: this method will automatically ensure "price" and "quantity" are sent as a - * string, if present in the request. See #523 & #526 for more details. + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOpenOrders} (`GET /papi/v1/um/algo/openAlgoOrders`). */ -submitMultipleOrders( - orders: NewFuturesOrderParams[], -): Promise<(NewOrderResult | NewOrderError)[]> +getUMOpenConditionalOrders(params: { + symbol?: string; +}): Promise ⋮---- -// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 +getUMAlgoOpenOrders(params?: { + symbol?: string; +}): Promise ⋮---- /** - * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + * @deprecated From 2026-04-28; replaced by {@link PortfolioClient.getUMAlgoOrder} (`GET /papi/v1/um/algo/algoOrder`). */ -modifyOrder( - params: ModifyFuturesOrderParams, -): Promise +getUMOpenConditionalOrder( + params: QueryPortfolioUMOpenConditionalOrderReq, +): Promise ⋮---- -modifyMultipleOrders(orders: ModifyOrderParams[]): Promise +getUMAlgoOrder( + params: QueryPortfolioUMAlgoOrderReq, +): Promise ⋮---- -getOrderModifyHistory( - params: GetFuturesOrderModifyHistoryParams, -): Promise +/** + * @deprecated From 2026-04-28; use {@link PortfolioClient.getUMAlgoOrder} or {@link PortfolioClient.getAllUMAlgoOrders} instead of `.../conditional/orderHistory`. + */ +getUMConditionalOrderHistory( + params: QueryPortfolioUMConditionalOrderHistoryReq, +): Promise ⋮---- -cancelOrder(params: CancelOrderParams): Promise +getCMOrder(params: QueryPortfolioCMOrderReq): Promise ⋮---- -cancelMultipleOrders( - params: CancelMultipleOrdersParams, -): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> +getAllCMOrders( + params: QueryPortfolioAllCMOrdersReq, +): Promise ⋮---- -cancelAllOpenOrders(params: { +getCMOpenOrder( + params: QueryPortfolioCMOpenOrderReq, +): Promise +⋮---- +getAllCMOpenOrders(params: { + symbol?: string; + pair?: string; +}): Promise +⋮---- +getCMOpenConditionalOrders(params: { + symbol?: string; +}): Promise +⋮---- +getCMOpenConditionalOrder(params: { symbol: string; -}): Promise + strategyId?: number; + newClientStrategyId?: string; +}): Promise ⋮---- -// Auto-cancel all open orders -setCancelOrdersOnTimeout( - params: CancelOrdersTimeoutParams, -): Promise +getAllCMConditionalOrders( + params: QueryPortfolioAllCMConditionalOrdersReq, +): Promise ⋮---- -getOrder(params: GetOrderParams): Promise +getCMConditionalOrderHistory( + params: QueryPortfolioCMConditionalOrderHistoryReq, +): Promise ⋮---- -getAllOrders(params?: GetFuturesAllOrdersParams): Promise +getUMForceOrders( + params: QueryPortfolioUMForceOrdersReq, +): Promise ⋮---- -getAllOpenOrders(params?: +getCMForceOrders( + params: QueryPortfolioCMForceOrdersReq, +): Promise ⋮---- -getCurrentOpenOrder(params: GetOrderParams): Promise +getUMOrderModificationHistory( + params: QueryPortfolioUMOrderAmendmentReq, +): Promise ⋮---- -getForceOrders(params?: GetForceOrdersParams): Promise +getCMOrderModificationHistory( + params: QueryPortfolioCMOrderAmendmentReq, +): Promise ⋮---- -getAccountTrades( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise +getMarginForceOrders(params: QueryPortfolioMarginForceOrdersReq): Promise< ⋮---- -setMarginType(params: SetMarginTypeParams): Promise +getUMTrades(params: QueryPortfolioUMTradesReq): Promise ⋮---- -setPositionMode(params: PositionModeParams): Promise +getCMTrades(params: QueryPortfolioCMTradesReq): Promise ⋮---- -/** - * Change initial leverage (`POST /fapi/v1/leverage`). - * `leverage` is an unbounded number here. The maximum is symbol-specific: - * bracket 1 `initialLeverage` from `GET /fapi/v1/leverageBracket` - * (Binance derivatives changelog 2026-10-09). - */ -setLeverage(params: SetLeverageParams): Promise +getUMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/um/adlQuantile', params); ⋮---- -setMultiAssetsMode(params: { - multiAssetsMargin: MultiAssetsMode; -}): Promise +getCMADLQuantile(params: { symbol?: string }): Promise< + { + symbol: string; + adlQuantile: PortfolioADLQuantile; + }[] + > { + return this.getPrivate('papi/v1/cm/adlQuantile', params); ⋮---- -setIsolatedPositionMargin( - params: SetIsolatedMarginParams, -): Promise +toggleUMFeeBurn(params: { + feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off +}): Promise< ⋮---- -/** - * @deprecated - * Use getPositionsV3() instead - **/ -getPositions(params?: Partial): Promise +feeBurn: 'true' | 'false'; // 'true': Fee Discount On; 'false': Fee Discount Off ⋮---- -getPositionsV3(params?: +getUMFeeBurnStatus(): Promise< ⋮---- -getADLQuantileEstimation(params?: +getMarginOrder( + params: QueryPortfolioMarginOrderReq, +): Promise ⋮---- -getSymbolAdlRisk(params: +getMarginOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -getSymbolAdlRisk(): Promise; +getAllMarginOrders( + params: QueryPortfolioMarginAllOrdersReq, +): Promise ⋮---- -getSymbolAdlRisk(params?: { - symbol?: string; -}): Promise +getMarginOCO( + params: QueryPortfolioMarginOCOReq, +): Promise ⋮---- -getPositionMarginChangeHistory( - params: GetPositionMarginChangeHistoryParams, -): Promise +getAllMarginOCO( + params: QueryPortfolioMarginAllOCOReq, +): Promise +⋮---- +getMarginOpenOCO(): Promise +⋮---- +getMarginTrades( + params: QueryPortfolioMarginTradesReq, +): Promise +⋮---- +repayMarginDebt( + params: PortfolioMarginRepayDebtReq, +): Promise ⋮---- /** * - * ACCOUNT endpoints - Rest API + * DERIVATIVES - ACCOUNT endpoints * **/ ⋮---- -getBalanceV3(): Promise +getBalance(params?: ⋮---- -/** - * @deprecated - * Use getBalanceV3() instead - **/ -getBalance(): Promise +getAccountInfo(): Promise ⋮---- -getAccountInformationV3(): Promise +getMarginMaxBorrow(params: ⋮---- -/** - * @deprecated - * Use getAccountInformationV3() instead - **/ -getAccountInformation(): Promise -⋮---- -getAccountCommissionRate(params: { - symbol: string; -}): Promise -⋮---- -getFuturesAccountConfig(): Promise -⋮---- -getFuturesSymbolConfig(params: +amount: string; // account's currently max borrowable amount with sufficient system availability +borrowLimit: string; // max borrowable amount limited by the account level ⋮---- -getUserForceOrders(): Promise +getMarginMaxWithdraw(params: ⋮---- -/** - * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) - */ -getNotionalAndLeverageBrackets(params?: { - symbol?: string; -}): Promise +amount: string; // max withdrawable amount ⋮---- -getMultiAssetsMode(): Promise +getUMPosition(params?: ⋮---- -getCurrentPositionMode(): Promise +getCMPosition(params?: { + marginAsset?: string; + pair?: string; +}): Promise ⋮---- /** - * Query income history (`GET /fapi/v1/income`). - * Paginate with `startTime` and `endTime`. `page` is not accepted. + * Change UM initial leverage (`POST /papi/v1/um/leverage`). + * `leverage` is an unbounded number here. The maximum is symbol-specific: + * bracket 1 `initialLeverage` from `GET /papi/v1/um/leverageBracket` + * (Binance derivatives changelog 2026-10-09). */ -getIncomeHistory(params?: GetIncomeHistoryParams): Promise +updateUMLeverage(params: ⋮---- -getApiQuantitativeRulesIndicators(params?: { - symbol?: string; -}): Promise +updateCMLeverage(params: ⋮---- -getFuturesTransactionHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +updateUMPositionMode(params: { + dualSidePosition: 'true' | 'false'; +}): Promise< ⋮---- -getFuturesTransactionHistoryDownloadLink(params: { - downloadId: string; -}): Promise +updateCMPositionMode(params: { + dualSidePosition: 'true' | 'false'; +}): Promise< ⋮---- -getFuturesOrderHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +getUMPositionMode(): Promise< ⋮---- -getFuturesOrderHistoryDownloadLink(params: { - downloadId: string; -}): Promise +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -getFuturesTradeHistoryDownloadId(params: { - startTime: number; - endTime: number; -}): Promise +getCMPositionMode(): Promise< ⋮---- -getFuturesTradeDownloadLink(params: { - downloadId: string; -}): Promise +dualSidePosition: boolean; // true: Hedge Mode; false: One-way Mode ⋮---- -setBNBBurnEnabled(params: { - feeBurn: 'true' | 'false'; -}): Promise< +getUMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + notionalCoef: string; + brackets: PortfolioUMLeverageBracket[]; + }[] + > { + return this.getPrivate('papi/v1/um/leverageBracket', params); ⋮---- -getBNBBurnStatus(): Promise< +getCMLeverageBrackets(params?: { symbol?: string }): Promise< + { + symbol: string; + brackets: PortfolioCMLeverageBracket[]; + }[] + > { + return this.getPrivate('papi/v1/cm/leverageBracket', params); ⋮---- -signTradFiPerpsAgreement(): Promise< +getUMTradingStatus(params?: { + symbol?: string; +}): Promise ⋮---- -testOrder(params: NewFuturesOrderParams): Promise +getUMCommissionRate(params: ⋮---- -/** - * - * Algo Order Endpoints (Effective 2025-12-02) - * Conditional orders migrate to Algo Service - * - **/ +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -submitNewAlgoOrder( - params: FuturesNewAlgoOrderParams, -): Promise +getCMCommissionRate(params: ⋮---- -cancelAlgoOrder( - params: FuturesCancelAlgoOrderParams, -): Promise +makerCommissionRate: string; // e.g., "0.0002" for 0.02% +takerCommissionRate: string; // e.g., "0.0004" for 0.04% ⋮---- -cancelAllAlgoOpenOrders(params: { - symbol: string; -}): Promise +getMarginLoanRecords(params: GetMarginLoanRecordsReq): Promise< ⋮---- -getAlgoOrder( - params: FuturesQueryAlgoOrderParams, -): Promise +getMarginRepayRecords(params: GetMarginRepayRecordsReq): Promise< ⋮---- -getOpenAlgoOrders( - params?: FuturesQueryOpenAlgoOrdersParams, -): Promise +getAutoRepayFuturesStatus(): Promise< ⋮---- -getAllAlgoOrders( - params: FuturesQueryAllAlgoOrdersParams, -): Promise +autoRepay: boolean; // true: auto-repay futures is on; false: auto-repay futures is off ⋮---- -/** - * - * Convert Endpoints - * - **/ +updateAutoRepayFuturesStatus(params: { + autoRepay: 'true' | 'false'; +}): Promise< ⋮---- -getAllConvertPairs(params?: { - fromAsset?: string; - toAsset?: string; -}): Promise +getMarginInterestHistory(params?: GetMarginInterestHistoryReq): Promise< ⋮---- -submitConvertQuoteRequest( - params: FuturesConvertQuoteRequest, -): Promise +repayFuturesNegativeBalance(): Promise< ⋮---- -acceptConvertQuote(params: +getPortfolioNegativeBalanceInterestHistory( + params?: GetPortfolioInterestHistoryReq, +): Promise ⋮---- -getConvertOrderStatus(params: { - orderId?: string; - quoteId?: string; -}): Promise +autoCollectFunds(): Promise< ⋮---- /** + * Fund collection by asset (`POST /papi/v1/asset-collection`). * - * Portfolio Margin Pro Endpoints - * - **/ -⋮---- -getPortfolioMarginProAccountInfo(params: { + * Optional `amount` and `futureType` must be sent together. `futureType` + * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). + * If neither is sent, collection behavior is unchanged. + */ +transferAssetFuturesMargin(params: { asset: string; -}): Promise + amount?: number; + futureType?: 'UM' | 'CM' | 'OPTION'; +}): Promise< ⋮---- -/** - * - * Broker Futures Endpoints - * Possibly @deprecated, found only in old docs - * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker - * - **/ +transferBNB(params: { + amount: string; + transferSide: 'TO_UM' | 'FROM_UM'; +}): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerIfNewFuturesUser( - brokerId: string, - type: 1 | 2 = 1, -): Promise< +tranId: number; // transaction id ⋮---- /** - * @deprecated - **/ -setBrokerCustomIdForClient( - customerId: string, - email: string, -): Promise< + * Query UM income history (`GET /papi/v1/um/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getUMIncomeHistory( + params?: QueryPortfolioUMIncomeReq, +): Promise ⋮---- /** - * @deprecated - **/ -getBrokerClientCustomIds( - customerId: string, - email: string, - page?: number, - limit?: number, -): Promise + * Query CM income history (`GET /papi/v1/cm/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getCMIncomeHistory( + params?: QueryPortfolioCMIncomeReq, +): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerUserCustomId(brokerId: string): Promise +getUMAccount(): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise +positions: PortfolioUMAccountPosition[]; // positions of all symbols in the market ⋮---- -/** - * @deprecated - **/ -getBrokerUserTradeVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getCMAccount(): Promise< ⋮---- -/** - * @deprecated - **/ -getBrokerRebateVolume( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getUMAccountConfig(): Promise ⋮---- -/** - * @deprecated - **/ -getBrokerTradeDetail( - type: 1 | 2 = 1, - startTime?: number, - endTime?: number, - limit?: number, -): Promise +getUMSymbolConfig(params?: { + symbol?: string; +}): Promise ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +getUMAccountV2(): Promise< ⋮---- -// USD-M Futures +positions: PortfolioUMAccountPositionV2[]; // positions of all symbols in the market ⋮---- -getFuturesUserDataListenKey(): Promise< +getUMTradeHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< ⋮---- -keepAliveFuturesUserDataListenKey(): Promise +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms ⋮---- -closeFuturesUserDataListenKey(): Promise +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTradeDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +getUMOrderHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMOrderDownloadLink(params: { + downloadId: string; +}): Promise +⋮---- +getUMTransactionHistoryDownloadId(params: { + startTime: number; // Timestamp in ms + endTime: number; // Timestamp in ms +}): Promise< +⋮---- +startTime: number; // Timestamp in ms +endTime: number; // Timestamp in ms +⋮---- +avgCostTimestampOfLast30d: number; // Average time taken for data download in the past 30 days +⋮---- +getUMTransactionDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- /** * Validate syntax meets requirements set by binance. Log warning if not. */ private validateOrderId( params: - | NewFuturesOrderParams - | FuturesNewAlgoOrderParams + | NewPortfolioUMOrderReq | CancelOrderParams | NewOCOParams | CancelOCOParams, orderIdProperty: OrderIdProperty, ): void +⋮---- +/** + * + * User Data Stream Endpoints + * + **/ +getPMUserDataListenKey(): Promise< +⋮---- +keepAlivePMUserDataListenKey(): Promise +⋮---- +closePMUserDataListenKey(): Promise ================ -File: src/types/websockets/ws-api-responses.ts +File: src/usdm-client.ts ================ -import type { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures.js'; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; +⋮---- +import { FundingRate } from './types/coin'; +import { + AggregateFuturesTrade, + Basis, + BasisParams, + CancelAllOpenOrdersResult, + CancelFuturesOrderResult, + CancelMultipleOrdersParams, + CancelOrdersTimeoutParams, + ChangeStats24hr, + ContinuousContractKlinesParams, + ForceOrderResult, + FundingRateHistory, + FuturesAccountBalance, + FuturesAccountConfig, + FuturesAccountInformation, + FuturesAlgoOrderResponse, + FuturesCancelAlgoOrderParams, + FuturesCancelAlgoOrderResponse, + FuturesCancelAllAlgoOpenOrdersResponse, + FuturesConvertOrderStatus, + FuturesConvertPair, + FuturesConvertQuote, + FuturesConvertQuoteRequest, + FuturesDataPaginatedParams, + FuturesExchangeInfo, + FuturesNewAlgoOrderParams, + FuturesOrderBook, + FuturesPosition, + FuturesPositionTrade, + FuturesPositionV3, + FuturesQueryAlgoOrderParams, + FuturesQueryAlgoOrderResponse, + FuturesQueryAllAlgoOrdersParams, + FuturesQueryOpenAlgoOrdersParams, + FuturesSymbolOrderBookTicker, + FuturesTradeHistoryDownloadId, + FuturesTransactionDownloadLink, + GetForceOrdersParams, + GetFuturesAllOrdersParams, + GetFuturesOrderModifyHistoryParams, + GetIncomeHistoryParams, + GetPositionMarginChangeHistoryParams, + HistoricOpenInterest, + IncomeHistory, + IndexPriceConstituents, + IndexPriceKlinesParams, + InsuranceFundBalance, + MarkPrice, + ModeChangeResult, + ModifyFuturesOrderParams, + ModifyFuturesOrderResult, + ModifyOrderParams, + MultiAssetModeResponse, + MultiAssetsMode, + NewFuturesOrderParams, + NewOrderError, + NewOrderResult, + OpenInterest, + OrderResult, + PortfolioMarginProAccountInfo, + PositionModeParams, + PositionModeResponse, + QuarterlyContractSettlementPrice, + RawFuturesTrade, + RebateDataOverview, + RpiOrderBook, + SetCancelTimeoutResult, + SetIsolatedMarginParams, + SetIsolatedMarginResult, + SetLeverageParams, + SetLeverageResult, + SetMarginTypeParams, + SymbolAdlRisk, + SymbolConfig, + SymbolKlinePaginatedParams, + SymbolLeverageBracketsResult, + TradingSchedule, + UserCommissionRate, + UserForceOrder, +} from './types/futures'; import { + BasicSymbolPaginatedParams, + BasicSymbolParam, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + GenericCodeMsgError, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, numberInString, - OrderSide, - OrderTimeInForce, - SelfTradePreventionMode, -} from '../shared'; -import { OrderResponse, SpotNewOrderConditionalFields } from '../spot'; + OrderBookParams, + OrderIdProperty, + RecentTradesParams, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, +} from './util/requestUtils'; ⋮---- -/** - * Error response type - */ -export interface ErrorResponse { - code: number; - msg: string; -} +export class USDMClient extends BaseRestClient ⋮---- -export interface WSAPISessionStatus { - apiKey: string; - authorizedSince: number; - connectedSince: number; - returnRateLimits: boolean; - serverTime: number; - userDataStream: boolean; -} +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) ⋮---- /** - * General response types - */ -export interface WSAPIServerTime { - serverTime: number; -} + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(): Promise ⋮---- /** - * Market data response types - */ -export interface WSAPIOrderBook { - lastUpdateId: number; - // [price, quantity] - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} + * + * MARKET DATA endpoints - Rest API + * + **/ ⋮---- -// [price, quantity] +testConnectivity(): Promise ⋮---- -export interface WSAPITrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; -} +getExchangeInfo(): Promise ⋮---- -export interface WSAPIAggregateTrade { - a: number; // Aggregate trade ID - p: numberInString; // Price - q: numberInString; // Quantity - f: number; // First trade ID - l: number; // Last trade ID - T: number; // Timestamp - m: boolean; // Was the buyer the maker? - M: boolean; // Was the trade the best price match? -} +getOrderBook(params: OrderBookParams): Promise ⋮---- -a: number; // Aggregate trade ID -p: numberInString; // Price -q: numberInString; // Quantity -f: number; // First trade ID -l: number; // Last trade ID -T: number; // Timestamp -m: boolean; // Was the buyer the maker? -M: boolean; // Was the trade the best price match? +getRpiOrderBook(params: { + symbol: string; + limit?: number; +}): Promise ⋮---- -export type WSAPIKline = [ - number, // Kline open time - numberInString, // Open price - numberInString, // High price - numberInString, // Low price - numberInString, // Close price - numberInString, // Volume - number, // Kline close time - numberInString, // Quote asset volume - number, // Number of trades - numberInString, // Taker buy base asset volume - numberInString, // Taker buy quote asset volume - numberInString, // Unused field -]; +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -number, // Kline open time -numberInString, // Open price -numberInString, // High price -numberInString, // Low price -numberInString, // Close price -numberInString, // Volume -number, // Kline close time -numberInString, // Quote asset volume -number, // Number of trades -numberInString, // Taker buy base asset volume -numberInString, // Taker buy quote asset volume -numberInString, // Unused field +getHistoricalTrades( + params: HistoricalTradesParams, +): Promise ⋮---- -export interface WSAPIAvgPrice { - mins: number; // Average price interval (in minutes) - price: numberInString; // Average price - closeTime: number; // Last trade time -} +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise ⋮---- -mins: number; // Average price interval (in minutes) -price: numberInString; // Average price -closeTime: number; // Last trade time +getKlines(params: KlinesParams): Promise ⋮---- -export interface WSAPIFullTicker { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - prevClosePrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First trade ID - lastId: number; // Last trade ID - count: number; // Number of trades -} +getContinuousContractKlines( + params: ContinuousContractKlinesParams, +): Promise ⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades +getIndexPriceKlines(params: IndexPriceKlinesParams): Promise ⋮---- -export interface WSAPIMiniTicker { - symbol: string; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - lastPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First trade ID - lastId: number; // Last trade ID - count: number; // Number of trades -} +getMarkPriceKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -firstId: number; // First trade ID -lastId: number; // Last trade ID -count: number; // Number of trades +getPremiumIndexKlines(params: SymbolKlinePaginatedParams): Promise ⋮---- -export interface WSAPIPriceTicker { - symbol: string; - price: numberInString; -} +getMarkPrice(params: ⋮---- -export interface WSAPIBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; -} +getMarkPrice(): Promise; ⋮---- -/** - * Futures market data response types - */ -export interface WSAPIFuturesOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - // [price, quantity] - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} +getMarkPrice(params?: ⋮---- -E: number; // Message output time -T: number; // Transaction time -// [price, quantity] +getFundingRateHistory( + params?: Partial, +): Promise ⋮---- -export interface WSAPIFuturesPriceTicker { - symbol: string; - price: numberInString; - time: number; // Transaction time -} +getFundingRates(): Promise ⋮---- -time: number; // Transaction time +get24hrChangeStatistics(params: ⋮---- -export interface WSAPIFuturesBookTicker { - lastUpdateId: number; - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; // Transaction time -} +get24hrChangeStatistics(): Promise; ⋮---- -time: number; // Transaction time +get24hrChangeStatistics(params?: { + symbol?: string; +}): Promise ⋮---- -/** - * Account response types - */ -export interface WSAPIAccountInformation { - makerCommission: number; - takerCommission: number; - buyerCommission: number; - sellerCommission: number; - canTrade: boolean; - canWithdraw: boolean; - canDeposit: boolean; - commissionRates: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - brokered: boolean; - requireSelfTradePrevention: boolean; - preventSor: boolean; - updateTime: number; - accountType: string; - balances: { - asset: string; - free: numberInString; - locked: numberInString; - }[]; - permissions: string[]; - uid: number; -} +getSymbolPriceTicker(params: ⋮---- -export interface WSAPIAccountCommission { - symbol: string; - standardCommission: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - taxCommission: { - maker: numberInString; - taker: numberInString; - buyer: numberInString; - seller: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ - discount: numberInString; - }; -} +getSymbolPriceTicker(): Promise; ⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ +getSymbolPriceTicker(params?: { + symbol?: string; +}): Promise ⋮---- -export interface WSAPIRateLimit { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} +getSymbolPriceTickerV2(params: ⋮---- -export interface WSAPIOrder { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice: numberInString; - icebergQty: numberInString; - time: number; - updateTime: number; - isWorking: boolean; - workingTime: number; - origQuoteOrderQty: numberInString; - selfTradePreventionMode: string; - preventedMatchId?: number; - preventedQuantity?: numberInString; - /** Present only for expired orders. */ - expiryReason?: string; -} +getSymbolPriceTickerV2(): Promise; ⋮---- -/** Present only for expired orders. */ +getSymbolPriceTickerV2(params?: { + symbol?: string; +}): Promise ⋮---- -export interface WSAPIBlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface WSAPIOrderList { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { +getSymbolOrderBookTicker(params: { symbol: string; - orderId: number; - clientOrderId: string; - }[]; -} + }): Promise; ⋮---- -export interface WSAPITrade { - symbol: string; - id: number; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isBestMatch: boolean; -} +getSymbolOrderBookTicker(): Promise; ⋮---- -export interface WSAPIPreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: string; - price: numberInString; - makerPreventedQuantity: numberInString; - transactTime: number; -} +getSymbolOrderBookTicker(params?: { + symbol?: string; +}): Promise ⋮---- -export interface WSAPIAllocation { - symbol: string; - allocationId: number; - allocationType: string; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isAllocator: boolean; -} +getQuarterlyContractSettlementPrices(params: { + pair: string; +}): Promise ⋮---- -/** - * Trading response types - */ -export interface WSAPIOrderTestResponse { - // Empty response object - [key: string]: never; -} +getOpenInterest(params: ⋮---- -// Empty response object +getOpenInterestStatistics( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -export interface WSAPIOrderTestWithCommission { - standardCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ - discount: numberInString; - }; -} +getTopTradersLongShortPositionRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ +getTopTradersLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -export interface WSAPIOrderCancel { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: numberInString; - trailingDelta?: number; - trailingTime?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode: string; -} +getGlobalLongShortAccountRatio( + params: FuturesDataPaginatedParams, +): Promise ⋮---- -export interface WSAPIOrderCancelReplaceResponse { - cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: WSAPIOrderCancel | ErrorResponse; - newOrderResponse: OrderResponse | ErrorResponse | null; -} +getTakerBuySellVolume(params: FuturesDataPaginatedParams): Promise ⋮---- -export interface WSAPIOrderListCancelResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: WSAPIOrderCancel[]; -} +getHistoricalBlvtNavKlines(params: SymbolKlinePaginatedParams): Promise +⋮---- +getCompositeSymbolIndex(params?: +⋮---- +getMultiAssetsModeAssetIndex(params?: ⋮---- /** - * Order list response types - */ -export interface WSAPIOrderListPlaceResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: OrderResponse[]; -} + * Possibly @deprecated, found only in old docs + **/ +getBasis(params: BasisParams): Promise ⋮---- -export interface WSAPIOrderListStatusResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { +getIndexPriceConstituents(params: { symbol: string; - orderId: number; - clientOrderId: string; - /** Present only for expired orders. */ - expiryReason?: string; - }[]; -} -⋮---- -/** Present only for expired orders. */ +}): Promise ⋮---- -/** - * SOR response types - */ -export interface WSAPISOROrderPlaceResponse { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; - fills: { - matchType: string; - price: string; - qty: string; - commission: string; - commissionAsset: string; - tradeId: number; - allocId: number; - }[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: boolean; -} +getInsuranceFundBalance(params?: { + symbol?: string; +}): Promise ⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +getTradingSchedule(): Promise ⋮---- -export interface WSAPISOROrderTestResponse { - // Empty response object - [key: string]: never; -} +/** + * + * TRADE endpoints - Rest API + * + **/ ⋮---- -// Empty response object -⋮---- -export interface WSAPISOROrderTestResponseWithCommission { - standardCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - maker: numberInString; - taker: numberInString; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ - discount: numberInString; - }; -} +submitNewOrder(params: NewFuturesOrderParams): Promise ⋮---- /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ + * Warning: max 5 orders at a time! This method does not throw, instead it returns + * individual errors in the response array if any orders were rejected. + * + * Note: this method will automatically ensure "price" and "quantity" are sent as a + * string, if present in the request. See #523 & #526 for more details. + */ +submitMultipleOrders( + orders: NewFuturesOrderParams[], +): Promise<(NewOrderResult | NewOrderError)[]> +⋮---- +// Known issue: `quantity` and `price` should be sent as strings, see #523, #526 ⋮---- /** - * Futures trading response types - */ -export interface WSAPIFuturesOrder { - orderId: number; - symbol: string; - status: string; - clientOrderId: string; - price: string; - avgPrice: string; - origQty: string; - executedQty: string; - cumQty: string; - cumQuote: string; - timeInForce: string; - type: string; - reduceOnly: boolean; - closePosition: boolean; - side: string; - positionSide: string; - stopPrice: string; - workingType: string; - priceProtect: boolean; - origType: string; - priceMatch: string; - selfTradePreventionMode: string; - goodTillDate: number; - updateTime: number; - time?: number; - activatePrice?: string; - priceRate?: string; - modifyId?: number; -} + * Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue + */ +modifyOrder( + params: ModifyFuturesOrderParams, +): Promise ⋮---- -export interface WSAPIFuturesPosition { - entryPrice: string; - breakEvenPrice: string; - marginType: string; - isAutoAddMargin: string; - isolatedMargin: string; - leverage: string; - liquidationPrice: string; - markPrice: string; - maxNotionalValue: string; - positionAmt: string; - notional: string; - isolatedWallet: string; - symbol: string; - unRealizedProfit: string; - positionSide: string; - updateTime: number; -} +modifyMultipleOrders(orders: ModifyOrderParams[]): Promise ⋮---- -export interface WSAPIFuturesPositionV2 { - symbol: string; - positionSide: string; - positionAmt: string; - entryPrice: string; - breakEvenPrice: string; - markPrice: string; - unrealizedProfit: string; - liquidationPrice: string; - isolatedMargin: string; - notional: string; - marginAsset: string; - isolatedWallet: string; - initialMargin: string; - maintMargin: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - adl: number; - bidNotional: string; - askNotional: string; - updateTime: number; -} +getOrderModifyHistory( + params: GetFuturesOrderModifyHistoryParams, +): Promise ⋮---- -export interface WSAPIFuturesAlgoOrder { - algoId: number; - clientAlgoId: string; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; - symbol: string; - side: OrderSide; - positionSide: PositionSide; - timeInForce: OrderTimeInForce; - quantity: numberInString; - algoStatus: FuturesAlgoOrderStatus; - triggerPrice: numberInString; - price: numberInString; - icebergQuantity: numberInString | null; - selfTradePreventionMode: SelfTradePreventionMode; - workingType: WorkingType; - priceMatch: PriceMatchMode; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; -} +cancelOrder(params: CancelOrderParams): Promise ⋮---- -export interface WSAPIFuturesAlgoOrderCancelResponse extends ErrorResponse { - algoId: number; - clientAlgoId: string; -} +cancelMultipleOrders( + params: CancelMultipleOrdersParams, +): Promise<(CancelFuturesOrderResult | GenericCodeMsgError)[]> ⋮---- -/** - * Futures account response types - */ -export interface WSAPIFuturesAccountBalanceItem { - accountAlias: string; - asset: string; - balance: string; - crossWalletBalance: string; - crossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - marginAvailable: boolean; - updateTime: number; -} +cancelAllOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -export interface WSAPIFuturesAccountAsset { - asset: string; - walletBalance: string; - unrealizedProfit: string; - marginBalance: string; - maintMargin: string; - initialMargin: string; - positionInitialMargin: string; - openOrderInitialMargin: string; - crossWalletBalance: string; - crossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - marginAvailable?: boolean; - updateTime: number; -} +// Auto-cancel all open orders +setCancelOrdersOnTimeout( + params: CancelOrdersTimeoutParams, +): Promise ⋮---- -export interface WSAPIFuturesAccountPosition { - symbol: string; - initialMargin?: string; - maintMargin?: string; - unrealizedProfit: string; - positionInitialMargin?: string; - openOrderInitialMargin?: string; - leverage?: string; - isolated?: boolean; - entryPrice?: string; - breakEvenPrice?: string; - maxNotional?: string; - bidNotional?: string; - askNotional?: string; - positionSide: string; - positionAmt: string; - updateTime: number; -} +getOrder(params: GetOrderParams): Promise ⋮---- -export interface WSAPIFuturesAccountStatus { - feeTier?: number; - canTrade?: boolean; - canDeposit?: boolean; - canWithdraw?: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId?: number; - totalInitialMargin: string; - totalMaintMargin: string; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - totalCrossWalletBalance: string; - totalCrossUnPnl: string; - availableBalance: string; - maxWithdrawAmount: string; - assets: WSAPIFuturesAccountAsset[]; - positions: WSAPIFuturesAccountPosition[]; -} +getAllOrders(params?: GetFuturesAllOrdersParams): Promise ⋮---- -/** - * Spot Order response types based on newOrderRespType parameter - */ -export interface WSAPISpotOrderACK { - symbol: string; - orderId: number; - orderListId: number; // always -1 for singular orders - clientOrderId: string; - transactTime: number; -} +getAllOpenOrders(params?: ⋮---- -orderListId: number; // always -1 for singular orders +getCurrentOpenOrder(params: GetOrderParams): Promise ⋮---- -export interface WSAPISpotOrderRESULT - extends WSAPISpotOrderACK, - SpotNewOrderConditionalFields { - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; -} -⋮---- -/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ +getForceOrders(params?: GetForceOrdersParams): Promise ⋮---- -export interface WSAPISpotOrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; -} +getAccountTrades( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, +): Promise ⋮---- -export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { - fills: WSAPISpotOrderFill[]; -} +setMarginType(params: SetMarginTypeParams): Promise ⋮---- -export type WSAPISpotOrderResponse = - | WSAPISpotOrderACK - | WSAPISpotOrderRESULT - | WSAPISpotOrderFULL; - -================ -File: src/websocket-client-legacy.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ -import { EventEmitter } from 'events'; -import WebSocket from 'isomorphic-ws'; +setPositionMode(params: PositionModeParams): Promise ⋮---- -import { KlineInterval } from './types/shared'; -import { - WsFormattedMessage, - WsUserDataEvents, -} from './types/websockets/ws-events-formatted'; -import { WsRawMessage } from './types/websockets/ws-events-raw'; -import { - WebsocketClientOptions, - WSClientConfigurableOptions, - WsMarket, - WsResponse, -} from './types/websockets/ws-general'; -import Beautifier from './util/beautifier'; -import { DefaultLogger } from './util/logger'; -import { appendEventIfMissing, RestClientOptions } from './util/requestUtils'; -import { neverGuard } from './util/typeGuards'; -import { ListenKeyStateCache } from './util/websockets/listen-key-state-cache'; -import { RestClientCache } from './util/websockets/rest-client-cache'; -import { - appendEventMarket, - getContextFromWsKey, - getLegacyWsStoreKeyWithContext, - parseEventTypeFromMessage, - parseRawWsMessageLegacy, - safeTerminateWs, - WS_LOGGER_CATEGORY, - WsKey, -} from './util/websockets/websocket-util'; -import { WsStore } from './util/websockets/WsStore'; -import { WsConnectionStateEnum } from './util/websockets/WsStore.types'; +/** + * Change initial leverage (`POST /fapi/v1/leverage`). + * `leverage` is an unbounded number here. The maximum is symbol-specific: + * bracket 1 `initialLeverage` from `GET /fapi/v1/leverageBracket` + * (Binance derivatives changelog 2026-10-09). + */ +setLeverage(params: SetLeverageParams): Promise ⋮---- -alpha: '', // Legacy client: alpha not supported; use WebsocketClient for alpha streams +setMultiAssetsMode(params: { + multiAssetsMargin: MultiAssetsMode; +}): Promise ⋮---- -type WsEventInternalSrc = 'event' | 'function'; +setIsolatedPositionMargin( + params: SetIsolatedMarginParams, +): Promise ⋮---- -type WebSocketWithMetadata = WebSocket & { - onping?: (event: unknown) => void; - onpong?: (event: unknown) => void; - wsKey?: WsKey | string; -}; +/** + * @deprecated + * Use getPositionsV3() instead + **/ +getPositions(params?: Partial): Promise ⋮---- -export declare interface WebsocketClientV1 { - on(event: 'reply', listener: (event: WsResponse) => void): this; - - on(event: 'message', listener: (event: WsRawMessage) => void): this; - - on( - event: 'formattedMessage', - listener: (event: WsFormattedMessage) => void, - ): this; - - on( - event: 'formattedUserDataMessage', - listener: (event: WsUserDataEvents) => void, - ): this; - - on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; - - on( - event: 'open' | 'reconnected', - listener: (event: { - wsKey: WsKey; - ws: WebSocket.Event; - event?: any; - }) => void, - ): this; - - on( - event: 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; -} +getPositionsV3(params?: ⋮---- -on(event: 'reply', listener: (event: WsResponse) +getADLQuantileEstimation(params?: ⋮---- -on(event: 'message', listener: (event: WsRawMessage) +getSymbolAdlRisk(params: ⋮---- -on( - event: 'formattedMessage', - listener: (event: WsFormattedMessage) => void, - ): this; +getSymbolAdlRisk(): Promise; ⋮---- -on( - event: 'formattedUserDataMessage', - listener: (event: WsUserDataEvents) => void, - ): this; +getSymbolAdlRisk(params?: { + symbol?: string; +}): Promise ⋮---- -on( - event: 'error', - listener: (event: { wsKey: WsKey; error: any; rawEvent?: string }) => void, - ): this; +getPositionMarginChangeHistory( + params: GetPositionMarginChangeHistoryParams, +): Promise ⋮---- -on( - event: 'open' | 'reconnected', - listener: (event: { - wsKey: WsKey; - ws: WebSocket.Event; - event?: any; - }) => void, - ): this; +/** + * + * ACCOUNT endpoints - Rest API + * + **/ ⋮---- -on( - event: 'reconnecting' | 'close', - listener: (event: { wsKey: WsKey; ws: WebSocket; event?: any }) => void, - ): this; +getBalanceV3(): Promise ⋮---- /** - * @deprecated This legacy websocket client creates one websocket connection per topic. - * - * If subscribing to a lot of topics, consider using the new multiplex `WebsocketClient`. - * - * To split your topics into smaller groups (one connection per group), simply make multiple multiplex WebsocketClient instances. - */ -export class WebsocketClientV1 extends EventEmitter + * @deprecated + * Use getBalanceV3() instead + **/ +getBalance(): Promise ⋮---- -constructor( - options: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, -) +getAccountInformationV3(): Promise ⋮---- -// Some defaults: +/** + * @deprecated + * Use getAccountInformationV3() instead + **/ +getAccountInformation(): Promise ⋮---- -// Automatically send an authentication op/request after a connection opens, for private connections. +getAccountCommissionRate(params: { + symbol: string; +}): Promise ⋮---- -// Individual requests require a signature +getFuturesAccountConfig(): Promise ⋮---- -// add default error handling so this doesn't crash node (if the user didn't set a handler) +getFuturesSymbolConfig(params: ⋮---- -private getRestClientOptions(): RestClientOptions +getUserForceOrders(): Promise ⋮---- -public connectToWsUrl( - url: string, - wsKey?: WsKey | string, - forceNewConnection?: boolean, -): WebSocket +/** + * Contrary to what the docs say - if symbol is provided, this returns an array with length 1 (assuming the symbol exists) + */ +getNotionalAndLeverageBrackets(params?: { + symbol?: string; +}): Promise ⋮---- -// Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node +getMultiAssetsMode(): Promise ⋮---- -// Add ws connection with key to store +getCurrentPositionMode(): Promise ⋮---- -public tryWsSend(wsKey: WsKey | string, wsMessage: string) +/** + * Query income history (`GET /fapi/v1/income`). + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +getIncomeHistory(params?: GetIncomeHistoryParams): Promise ⋮---- -public tryWsPing(wsKey: WsKey | string) +getApiQuantitativeRulesIndicators(params?: { + symbol?: string; +}): Promise ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +/** + * Get a download id for futures transaction history (`GET /fapi/v1/income/asyn`). + * Limited to 100 requests per month, shared across the web download page, + * REST, USD-M and COIN-M. + */ +getFuturesTransactionHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +getFuturesTransactionHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -private onWsOpen(ws: WebSocket.Event, wsKey: WsKey | string, wsUrl: string) +getFuturesOrderHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise ⋮---- -private onWsClose( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - wsUrl: string, -) +getFuturesOrderHistoryDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -// Clear any timers before we initiate revival +getFuturesTradeHistoryDownloadId(params: { + startTime: number; + endTime: number; +}): Promise ⋮---- -// User data sockets include the listen key. To prevent accummulation in memory we should clean up old disconnected states +getFuturesTradeDownloadLink(params: { + downloadId: string; +}): Promise ⋮---- -private onWsMessage( - event: WebSocket.MessageEvent, - wsKey: WsKey | string, - source: WsEventInternalSrc, -) -⋮---- -// Edge case where raw event does not include event type, detect using wsKey and mutate msg.e -⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn -⋮---- -// emit a separate event for user data messages +setBNBBurnEnabled(params: { + feeBurn: 'true' | 'false'; +}): Promise< ⋮---- -private sendPing(wsKey: WsKey | string, wsUrl: string) +getBNBBurnStatus(): Promise< ⋮---- -private onWsPing( - event: any, - wsKey: WsKey | string, - ws: WebSocket, - source: WsEventInternalSrc, -) +signTradFiPerpsAgreement(): Promise< ⋮---- -private onWsPong( - event: any, - wsKey: WsKey | string, - source: WsEventInternalSrc, -) +testOrder(params: NewFuturesOrderParams): Promise ⋮---- /** - * Closes a connection, if it's even open. If open, this will trigger a reconnect asynchronously. - * If closed, trigger a reconnect immediately - */ -private executeReconnectableClose( - wsKey: WsKey | string, - reason: string, - wsUrl: string, -) + * + * Algo Order Endpoints (Effective 2025-12-02) + * Conditional orders migrate to Algo Service + * + **/ ⋮---- -public close(wsKey: WsKey | string, shouldReconnectAfterClose?: boolean) +submitNewAlgoOrder( + params: FuturesNewAlgoOrderParams, +): Promise ⋮---- -public closeAll(shouldReconnectAfterClose?: boolean) +cancelAlgoOrder( + params: FuturesCancelAlgoOrderParams, +): Promise ⋮---- -public closeWs(ws: WebSocket, shouldReconnectAfterClose?: boolean) +cancelAllAlgoOpenOrders(params: { + symbol: string; +}): Promise ⋮---- -private parseWsError( - context: string, - error: any, - wsKey: WsKey | string, - wsUrl: string, -) +getAlgoOrder( + params: FuturesQueryAlgoOrderParams, +): Promise ⋮---- -private reconnectWithDelay( - wsKey: WsKey | string, - connectionDelayMs: number, - wsUrl: string, -) +getOpenAlgoOrders( + params?: FuturesQueryOpenAlgoOrdersParams, +): Promise ⋮---- -// We'll set a new one once the new stream respawns, with a diff listenKey in the key +getAllAlgoOrders( + params: FuturesQueryAllAlgoOrdersParams, +): Promise ⋮---- -private clearTimers(wsKey: WsKey | string) +/** + * + * Convert Endpoints + * + **/ ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: WsKey | string) +getAllConvertPairs(params?: { + fromAsset?: string; + toAsset?: string; +}): Promise ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: WsKey | string) +submitConvertQuoteRequest( + params: FuturesConvertQuoteRequest, +): Promise ⋮---- -// Timer tracking that a reconnect is about to happen / in progress -private clearReconnectTimer(wsKey: WsKey | string) +acceptConvertQuote(params: ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -private getWsBaseUrl(market: WsMarket, wsKey?: WsKey | string): string +getConvertOrderStatus(params: { + orderId?: string; + quoteId?: string; +}): Promise ⋮---- -public getWs(wsKey: WsKey | string): WebSocket | undefined +/** + * + * Portfolio Margin Pro Endpoints + * + **/ ⋮---- -private setWsState(wsKey: WsKey | string, state: WsConnectionStateEnum) +getPortfolioMarginProAccountInfo(params: { + asset: string; +}): Promise ⋮---- /** - * Send WS message to subscribe to topics. Use subscribe() to call this. - */ -private requestSubscribeTopics(wsKey: WsKey | string, topics: string[]) + * + * Broker Futures Endpoints + * Possibly @deprecated, found only in old docs + * All broker endpoints start with /sapi/v1/broker or sapi/v2/broker or sapi/v3/broker + * + **/ ⋮---- /** - * Send WS message to unsubscribe from topics. Use unsubscribe() to call this. - */ -private requestUnsubscribeTopics(wsKey: WsKey, topics: string[]) + * @deprecated + **/ +getBrokerIfNewFuturesUser( + brokerId: string, + type: 1 | 2 = 1, +): Promise< ⋮---- /** - * Send WS message to unsubscribe from topics. - */ -public requestListSubscriptions(wsKey: WsKey, requestId: number) + * @deprecated + **/ +setBrokerCustomIdForClient( + customerId: string, + email: string, +): Promise< ⋮---- /** - * Send WS message to set property state - */ -public requestSetProperty( - wsKey: WsKey, - property: 'combined' | string, - value: any, - requestId: number, -) + * @deprecated + **/ +getBrokerClientCustomIds( + customerId: string, + email: string, + page?: number, + limit?: number, +): Promise ⋮---- /** - * Send WS message to get property state - */ -public requestGetProperty( - wsKey: WsKey, - property: 'combined' | string, - requestId: number, -) + * @deprecated + **/ +getBrokerUserCustomId(brokerId: string): Promise ⋮---- /** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- + * @deprecated **/ +getBrokerRebateDataOverview(type: 1 | 2 = 1): Promise ⋮---- -private setKeepAliveListenKeyTimer( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -// Set timer to keep WS alive every 50 minutes -⋮---- -// 1000 * 60 -⋮---- -private sendKeepAliveForMarket( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -private async checkKeepAliveListenKey( - listenKey: string, - market: WsMarket, - ws: WebSocket, - wsKey: WsKey, - symbol?: string, - isTestnet?: boolean, -) -⋮---- -// Simple way to test keep alive failure handling: -// throw new Error(`Fake keep alive failure`); -⋮---- -// code: -1125, -// message: 'This listenKey does not exist.', +/** + * @deprecated + **/ +getBrokerUserTradeVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -// If max failurees reached, tear down and respawn if allowed +/** + * @deprecated + **/ +getBrokerRebateVolume( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -// reconnect follows a less automatic workflow since this is tied to a listen key (which may need a new one). -// Kill connection first, with instruction NOT to reconnect automatically +/** + * @deprecated + **/ +getBrokerTradeDetail( + type: 1 | 2 = 1, + startTime?: number, + endTime?: number, + limit?: number, +): Promise ⋮---- -// Then respawn a connection with a potentially new listen key (since the old one may be invalid now) +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -private teardownUserDataListenKey(listenKey: string, ws?: WebSocket) +// USD-M Futures ⋮---- -private async respawnUserDataStream( - market: WsMarket, - symbol?: string, - isTestnet?: boolean, - respawnAttempt?: number, -): Promise +getFuturesUserDataListenKey(): Promise< ⋮---- -// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key +keepAliveFuturesUserDataListenKey(): Promise ⋮---- -// This timer should probably be tracked/singleton +closeFuturesUserDataListenKey(): Promise ⋮---- /** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ -⋮---- -/** - * Subscribe to a universal market websocket stream + * Validate syntax meets requirements set by binance. Log warning if not. */ -⋮---- -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +private validateOrderId( + params: + | NewFuturesOrderParams + | FuturesNewAlgoOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams, + orderIdProperty: OrderIdProperty, +): void + +================ +File: src/types/websockets/ws-api-responses.ts +================ +import type { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures.js'; +import { + numberInString, + OrderSide, + OrderTimeInForce, + SelfTradePreventionMode, +} from '../shared'; +import { OrderResponse, SpotNewOrderConditionalFields } from '../spot'; ⋮---- /** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket + * Error response type + */ +export interface ErrorResponse { + code: number; + msg: string; +} ⋮---- -/** - * Subscribe to trades for a symbol in a market category - * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning - */ -public subscribeTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPISessionStatus { + apiKey: string; + authorizedSince: number; + connectedSince: number; + returnRateLimits: boolean; + serverTime: number; + userDataStream: boolean; +} ⋮---- /** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket + * General response types + */ +export interface WSAPIServerTime { + serverTime: number; +} ⋮---- /** - * Subscribe to coin index for a symbol in COINM Futures markets - * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. - */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket + * Market data response types + */ +export interface WSAPIOrderBook { + lastUpdateId: number; + // [price, quantity] + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +// [price, quantity] ⋮---- -/** - * Subscribe to mark price for a symbol in a market category - */ -public subscribeMarkPrice( - symbol: string, - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPITrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIAggregateTrade { + a: number; // Aggregate trade ID + p: numberInString; // Price + q: numberInString; // Quantity + f: number; // First trade ID + l: number; // Last trade ID + T: number; // Timestamp + m: boolean; // Was the buyer the maker? + M: boolean; // Was the trade the best price match? +} ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +a: number; // Aggregate trade ID +p: numberInString; // Price +q: numberInString; // Quantity +f: number; // First trade ID +l: number; // Last trade ID +T: number; // Timestamp +m: boolean; // Was the buyer the maker? +M: boolean; // Was the trade the best price match? ⋮---- -/** - * Subscribe to continuous contract klines(candles) for a symbol futures - */ -public subscribeContinuousContractKlines( - symbol: string, - contractType: 'perpetual' | 'current_quarter' | 'next_quarter', - interval: KlineInterval, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export type WSAPIKline = [ + number, // Kline open time + numberInString, // Open price + numberInString, // High price + numberInString, // Low price + numberInString, // Close price + numberInString, // Volume + number, // Kline close time + numberInString, // Quote asset volume + number, // Number of trades + numberInString, // Taker buy base asset volume + numberInString, // Taker buy quote asset volume + numberInString, // Unused field +]; ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket +number, // Kline open time +numberInString, // Open price +numberInString, // High price +numberInString, // Low price +numberInString, // Close price +numberInString, // Volume +number, // Kline close time +numberInString, // Quote asset volume +number, // Number of trades +numberInString, // Taker buy base asset volume +numberInString, // Taker buy quote asset volume +numberInString, // Unused field ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIAvgPrice { + mins: number; // Average price interval (in minutes) + price: numberInString; // Average price + closeTime: number; // Last trade time +} ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +mins: number; // Average price interval (in minutes) +price: numberInString; // Average price +closeTime: number; // Last trade time ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIFullTicker { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + prevClosePrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First trade ID + lastId: number; // Last trade ID + count: number; // Number of trades +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket -⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades ⋮---- -/** - * Subscribe to rolling window ticker statistics for all market symbols, - * computed over multiple windows. Note that only tickers that have - * changed will be present in the array. - * - * Notes: - * - Supported window sizes: 1h,4h,1d. - * - Supported markets: spot - */ -public subscribeAllRollingWindowTickers( - market: 'spot', - windowSize: '1h' | '4h' | '1d', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIMiniTicker { + symbol: string; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + lastPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First trade ID + lastId: number; // Last trade ID + count: number; // Number of trades +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +firstId: number; // First trade ID +lastId: number; // Last trade ID +count: number; // Number of trades ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIPriceTicker { + symbol: string; + price: numberInString; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} ⋮---- /** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket + * Futures market data response types + */ +export interface WSAPIFuturesOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + // [price, quantity] + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} ⋮---- -/** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - * - * Use getContextFromWsKey(data.wsKey) to extract symbol from events - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +E: number; // Message output time +T: number; // Transaction time +// [price, quantity] ⋮---- -/** - * Subscribe to orderbook depth updates to locally manage an order book. - * - * Note that the updatems parameter depends on which market you're trading - * - * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream - * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams - * - * Use getContextFromWsKey(data.wsKey) to extract symbol from events - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIFuturesPriceTicker { + symbol: string; + price: numberInString; + time: number; // Transaction time +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - forceNewConnection?: boolean, -): WebSocket +time: number; // Transaction time ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export interface WSAPIFuturesBookTicker { + lastUpdateId: number; + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; // Transaction time +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket +time: number; // Transaction time ⋮---- /** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket + * Account response types + */ +export interface WSAPIAccountInformation { + makerCommission: number; + takerCommission: number; + buyerCommission: number; + sellerCommission: number; + canTrade: boolean; + canWithdraw: boolean; + canDeposit: boolean; + commissionRates: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + brokered: boolean; + requireSelfTradePrevention: boolean; + preventSor: boolean; + updateTime: number; + accountType: string; + balances: { + asset: string; + free: numberInString; + locked: numberInString; + }[]; + permissions: string[]; + uid: number; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIAccountCommission { + symbol: string; + standardCommission: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + taxCommission: { + maker: numberInString; + taker: numberInString; + buyer: numberInString; + seller: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ + discount: numberInString; + }; +} ⋮---- /** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - forceNewConnection?: boolean, -): WebSocket + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIRateLimit { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIOrder { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice: numberInString; + icebergQty: numberInString; + time: number; + updateTime: number; + isWorking: boolean; + workingTime: number; + origQuoteOrderQty: numberInString; + selfTradePreventionMode: string; + preventedMatchId?: number; + preventedQuantity?: numberInString; + /** Present only for expired orders. */ + expiryReason?: string; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket +/** Present only for expired orders. */ ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(forceNewConnection?: boolean): WebSocket +export interface WSAPIBlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIOrderList { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeSpotAllBookTickers(forceNewConnection?: boolean): WebSocket +export interface WSAPITrade { + symbol: string; + id: number; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isBestMatch: boolean; +} ⋮---- -/** - * Subscribe to top bid/ask levels for symbol in spot markets. - */ -public subscribeSpotPartialBookDepth( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 1000 | 100 = 1000, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIPreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: string; + price: numberInString; + makerPreventedQuantity: numberInString; + transactTime: number; +} ⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - forceNewConnection?: boolean, -): WebSocket +export interface WSAPIAllocation { + symbol: string; + allocationId: number; + allocationType: string; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isAllocator: boolean; +} ⋮---- /** - * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. - * Supports spot, margin & isolated margin listen keys. - */ -public subscribeSpotUserDataStreamWithListenKey( - listenKey: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): WebSocket | undefined + * Trading response types + */ +export interface WSAPIOrderTestResponse { + // Empty response object + [key: string]: never; +} ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +// Empty response object ⋮---- -/** - * Subscribe to spot user data stream - listen key is automaticallyr generated. Calling multiple times only opens one connection. - */ -public async subscribeSpotUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise +export interface WSAPIOrderTestWithCommission { + standardCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ + discount: numberInString; + }; +} ⋮---- /** - * Subscribe to margin user data stream - listen key is automatically generated. - */ -public async subscribeMarginUserDataStream( - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise +export interface WSAPIOrderCancel { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: numberInString; + trailingDelta?: number; + trailingTime?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode: string; +} ⋮---- -// Start & store timer to keep alive listen key (and handle expiration) +export interface WSAPIOrderCancelReplaceResponse { + cancelResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: WSAPIOrderCancel | ErrorResponse; + newOrderResponse: OrderResponse | ErrorResponse | null; +} ⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +export interface WSAPIOrderListCancelResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: WSAPIOrderCancel[]; +} ⋮---- /** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeUsdFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Necessary so client knows this is a reconnect -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) -⋮---- -/** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. - */ -public async subscribeCoinFuturesUserDataStream( - isTestnet?: boolean, - forceNewConnection?: boolean, - isReconnecting?: boolean, -): Promise -⋮---- -// Necessary so client knows this is a reconnect -⋮---- -// Start & store timer to keep alive listen key (and handle expiration) - -================ -File: src/types/websockets/ws-events-formatted.ts -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - FuturesContractType, - FuturesOrderType, - MarginType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - KlineInterval, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRowFormatted, - OrderExecutionType, - OrderListContingencyType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -import { - AccountUpdateEventType, - FuturesMarketSymbolType, -} from './ws-events-raw'; -import { WsSharedBase } from './ws-general'; -⋮---- -export interface WsMessageKlineFormatted extends WsSharedBase { - eventType: 'kline' | 'indexPrice_kline'; - eventTime: number; + * Order list response types + */ +export interface WSAPIOrderListPlaceResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; symbol: string; - kline: { - startTime: number; - endTime: number; + orders: { symbol: string; - interval: KlineInterval; - firstTradeId: number; - lastTradeId: number; - open: number; - close: number; - high: number; - low: number; - volume: number; - trades: number; - final: boolean; - quoteVolume: number; - volumeActive: number; - quoteVolumeActive: number; - ignored: number; - }; + orderId: number; + clientOrderId: string; + }[]; + orderReports: OrderResponse[]; } ⋮---- -export interface WsMessageContinuousKlineFormatted extends WsSharedBase { - eventType: 'continuous_kline'; - eventTime: number; +export interface WSAPIOrderListStatusResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; symbol: string; - contractType: FuturesContractType; - kline: { - startTime: number; - endTime: number; + orders: { symbol: string; - interval: KlineInterval; - firstTradeId: number; - lastTradeId: number; - open: number; - close: number; - high: number; - low: number; - volume: number; - trades: number; - final: boolean; - quoteVolume: number; - volumeActive: number; - quoteVolumeActive: number; - ignored: number; - }; + orderId: number; + clientOrderId: string; + /** Present only for expired orders. */ + expiryReason?: string; + }[]; } ⋮---- -export interface WsMessageAggTradeFormatted extends WsSharedBase { - eventType: 'aggTrade'; - eventTime: number; - symbol: string; - tradeId: number; - price: number; - quantity: number; - firstTradeId: number; - lastTradeId: number; - time: number; - maker: boolean; - ignored: boolean; - symbolType?: FuturesMarketSymbolType; -} +/** Present only for expired orders. */ ⋮---- -export interface WsMessageTradeFormatted extends WsSharedBase { - eventType: 'trade'; - eventTime: number; +/** + * SOR response types + */ +export interface WSAPISOROrderPlaceResponse { symbol: string; - tradeId: number; - price: number; - quantity: number; - buyerOrderId: number; - sellerOrderId: number; - time: number; - maker: boolean; - ignored: boolean; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; + fills: { + matchType: string; + price: string; + qty: string; + commission: string; + commissionAsset: string; + tradeId: number; + allocId: number; + }[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: boolean; } ⋮---- -export interface WsMessageBlockTradeFormatted extends WsSharedBase { - eventType: 'blockTrade'; - eventTime: number; - symbol: string; - tradeId: number; - price: number; - quantity: number; - time: number; - maker: boolean; -} +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -export interface WsMessage24hrMiniTickerFormatted extends WsSharedBase { - eventType: '24hrMiniTicker'; - eventTime: number; - symbol: string; - contractSymbol?: string; //coinm only - close: number; - open: number; - high: number; - low: number; - baseAssetVolume: number; - quoteAssetVolume: number; - symbolType?: FuturesMarketSymbolType; +export interface WSAPISOROrderTestResponse { + // Empty response object + [key: string]: never; } ⋮---- -contractSymbol?: string; //coinm only +// Empty response object ⋮---- -export interface WsMessage24hrTickerFormatted extends WsSharedBase { - /** - * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). - * Will be retired on 2026-03-26. - * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. - */ - eventType: '24hrTicker' | '!ticker@arr'; - eventTime: number; - symbol: string; - priceChange: number; - priceChangePercent: number; - weightedAveragePrice: number; - previousClose: number; - currentClose: number; - closeQuantity: number; - bestBid: number; - bestBidQuantity: number; - bestAskPrice: number; - bestAskQuantity: number; - open: number; - high: number; - low: number; - baseAssetVolume: number; - quoteAssetVolume: number; - openTime: number; - closeTime: number; - firstTradeId: number; - lastTradeId: number; - trades: number; - symbolType?: FuturesMarketSymbolType; +export interface WSAPISOROrderTestResponseWithCommission { + standardCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + maker: numberInString; + taker: numberInString; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ + discount: numberInString; + }; } ⋮---- /** - * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). - * Will be retired on 2026-03-26. - * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. - */ + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ ⋮---- -export interface WsMessageRollingWindowTickerFormatted extends WsSharedBase { - eventType: 'ticker'; - eventTime: number; +/** + * Futures trading response types + */ +export interface WSAPIFuturesOrder { + orderId: number; symbol: string; - priceChange: number; - priceChangePercent: number; - weightedAveragePrice: number; - open: number; - high: number; - low: number; - currentClose: number; - baseAssetVolume: number; - quoteAssetVolume: number; - openTime: number; - closeTime: number; - firstTradeId: number; - lastTradeId: number; - trades: number; - streamName: string; - isWSAPIResponse: false; + status: string; + clientOrderId: string; + price: string; + avgPrice: string; + origQty: string; + executedQty: string; + cumQty: string; + cumQuote: string; + timeInForce: string; + type: string; + reduceOnly: boolean; + closePosition: boolean; + side: string; + positionSide: string; + stopPrice: string; + workingType: string; + priceProtect: boolean; + origType: string; + priceMatch: string; + selfTradePreventionMode: string; + goodTillDate: number; + updateTime: number; + time?: number; + activatePrice?: string; + priceRate?: string; + modifyId?: number; } ⋮---- -export interface WsMessageBookTickerEventFormatted extends WsSharedBase { - eventType: 'bookTicker'; - updateId: number; - eventTime: number; - transactionTime: number; +export interface WSAPIFuturesPosition { + entryPrice: string; + breakEvenPrice: string; + marginType: string; + isAutoAddMargin: string; + isolatedMargin: string; + leverage: string; + liquidationPrice: string; + markPrice: string; + maxNotionalValue: string; + positionAmt: string; + notional: string; + isolatedWallet: string; symbol: string; - bidPrice: number; - bidQty: number; - askPrice: number; - askQty: number; - symbolType?: FuturesMarketSymbolType; + unRealizedProfit: string; + positionSide: string; + updateTime: number; } ⋮---- -export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { - eventType: 'partialBookDepth' | 'string'; - lastUpdateId: number; - bids: OrderBookRowFormatted[]; - asks: OrderBookRowFormatted[]; - symbolType?: FuturesMarketSymbolType; +export interface WSAPIFuturesPositionV2 { + symbol: string; + positionSide: string; + positionAmt: string; + entryPrice: string; + breakEvenPrice: string; + markPrice: string; + unrealizedProfit: string; + liquidationPrice: string; + isolatedMargin: string; + notional: string; + marginAsset: string; + isolatedWallet: string; + initialMargin: string; + maintMargin: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + adl: number; + bidNotional: string; + askNotional: string; + updateTime: number; } ⋮---- -export interface WsMessageDiffBookDepthEventFormatted extends WsSharedBase { - eventType: 'depthUpdate'; - eventTime: number; - transactionTime: number; // futures only +export interface WSAPIFuturesAlgoOrder { + algoId: number; + clientAlgoId: string; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; symbol: string; - firstUpdateId: number; - lastUpdateId: number; - finalUpdateId: number; // futures only - bidDepthDelta: { price: number; quantity: number }[]; - askDepthDelta: { price: number; quantity: number }[]; - symbolType?: FuturesMarketSymbolType; + side: OrderSide; + positionSide: PositionSide; + timeInForce: OrderTimeInForce; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + triggerPrice: numberInString; + price: numberInString; + icebergQuantity: numberInString | null; + selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; + priceMatch: PriceMatchMode; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; } ⋮---- -transactionTime: number; // futures only -⋮---- -finalUpdateId: number; // futures only +export interface WSAPIFuturesAlgoOrderCancelResponse extends ErrorResponse { + algoId: number; + clientAlgoId: string; +} ⋮---- /** - * USER DATA WS EVENTS - **/ + * Futures account response types + */ +export interface WSAPIFuturesAccountBalanceItem { + accountAlias: string; + asset: string; + balance: string; + crossWalletBalance: string; + crossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + marginAvailable: boolean; + updateTime: number; +} ⋮---- -interface SpotBalanceFormatted { +export interface WSAPIFuturesAccountAsset { asset: string; - availableBalance: number; - onOrderBalance: number; + walletBalance: string; + unrealizedProfit: string; + marginBalance: string; + maintMargin: string; + initialMargin: string; + positionInitialMargin: string; + openOrderInitialMargin: string; + crossWalletBalance: string; + crossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + marginAvailable?: boolean; + updateTime: number; } ⋮---- -export interface WsMessageSpotOutboundAccountPositionFormatted - extends WsSharedBase { - eventType: 'outboundAccountPosition'; - eventTime: number; - lastAccountUpdateTime: number; - balances: SpotBalanceFormatted[]; +export interface WSAPIFuturesAccountPosition { + symbol: string; + initialMargin?: string; + maintMargin?: string; + unrealizedProfit: string; + positionInitialMargin?: string; + openOrderInitialMargin?: string; + leverage?: string; + isolated?: boolean; + entryPrice?: string; + breakEvenPrice?: string; + maxNotional?: string; + bidNotional?: string; + askNotional?: string; + positionSide: string; + positionAmt: string; + updateTime: number; } ⋮---- -export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { - eventType: 'balanceUpdate'; - eventTime: number; - asset: string; - balanceDelta: number; - clearTime: number; +export interface WSAPIFuturesAccountStatus { + feeTier?: number; + canTrade?: boolean; + canDeposit?: boolean; + canWithdraw?: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId?: number; + totalInitialMargin: string; + totalMaintMargin: string; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + totalCrossWalletBalance: string; + totalCrossUnPnl: string; + availableBalance: string; + maxWithdrawAmount: string; + assets: WSAPIFuturesAccountAsset[]; + positions: WSAPIFuturesAccountPosition[]; } ⋮---- -export interface WsMessageSpotUserDataExecutionReportEventFormatted - extends WsSharedBase { - eventType: 'executionReport'; - eventTime: number; +/** + * Spot Order response types based on newOrderRespType parameter + */ +export interface WSAPISpotOrderACK { symbol: string; - newClientOrderId: string; - side: OrderSide; - orderType: OrderType; - cancelType: OrderTimeInForce; - quantity: number; - price: number; - stopPrice: number; - icebergQuantity: number; - orderListId: number; - originalClientOrderId: string; - executionType: OrderExecutionType; - orderStatus: OrderStatus; - rejectReason: string; orderId: number; - lastTradeQuantity: number; - accumulatedQuantity: number; - lastTradePrice: number; - commission: number; - commissionAsset: string | null; - tradeTime: number; - tradeId: number; - ignoreThis1: number; - isOrderOnBook: boolean; - isMaker: boolean; - ignoreThis2: true; - orderCreationTime: number; - cummulativeQuoteAssetTransactedQty: number; - lastQuoteAssetTransactedQty: number; - orderQuoteQty: number; + orderListId: number; // always -1 for singular orders + clientOrderId: string; + transactTime: number; +} +⋮---- +orderListId: number; // always -1 for singular orders +⋮---- +export interface WSAPISpotOrderRESULT + extends WSAPISpotOrderACK, + SpotNewOrderConditionalFields { + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: string; + timeInForce: string; + type: string; + side: string; workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; + selfTradePreventionMode: string; + /** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ expiryReason?: string; - trailingDelta?: number; - preventedMatchId?: number; - trailingTime?: number; - strategyId?: number; - strategyType?: number; - tradeGroupId?: number; - counterOrderId?: number; - /** Allocation ID. */ - allocationId?: number; - preventedQuantity?: number; - lastPreventedQuantity?: number; - counterSymbol?: string; - preventedExecutionQuantity?: number; - preventedExecutionPrice?: number; - preventedExecutionQuoteQty?: number; } ⋮---- -/** Allocation ID. */ +/** With newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -export interface WsMessagePortfolioMarginProAccountUpdateFormatted - extends WsSharedBase { - eventType: 'PM_PRO_ACCOUNT_UPDATE'; - eventTime: number; - uniMMR: number; - accountEquity: number; - actualEquity: number; - initialMargin: number; - maintenanceMargin: number; - availableBalance: number; - virtualMaxWithdraw: number; +export interface WSAPISpotOrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; } ⋮---- -export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { - eventType: 'serverShutdown'; - eventTime: number; +export interface WSAPISpotOrderFULL extends WSAPISpotOrderRESULT { + fills: WSAPISpotOrderFill[]; } ⋮---- -export interface OrderObjectFormatted { - symbol: string; - orderId: number; - clientOrderId: string; -} +export type WSAPISpotOrderResponse = + | WSAPISpotOrderACK + | WSAPISpotOrderRESULT + | WSAPISpotOrderFULL; + +================ +File: src/types/websockets/ws-events-formatted.ts +================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + FuturesContractType, + FuturesOrderType, + MarginType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + KlineInterval, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRowFormatted, + OrderExecutionType, + OrderListContingencyType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +import { + AccountUpdateEventType, + FuturesMarketSymbolType, +} from './ws-events-raw'; +import { WsSharedBase } from './ws-general'; ⋮---- -export interface WsMessageSpotUserDataListStatusEventFormatted - extends WsSharedBase { - eventType: 'listStatus'; +export interface WsMessageKlineFormatted extends WsSharedBase { + eventType: 'kline' | 'indexPrice_kline'; eventTime: number; symbol: string; - orderListId: number; - contingencyType: OrderListContingencyType; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listRejectReason: string; - listClientOrderId: string; - transactionTime: number; - orders: OrderObjectFormatted[]; + kline: { + startTime: number; + endTime: number; + symbol: string; + interval: KlineInterval; + firstTradeId: number; + lastTradeId: number; + open: number; + close: number; + high: number; + low: number; + volume: number; + trades: number; + final: boolean; + quoteVolume: number; + volumeActive: number; + quoteVolumeActive: number; + ignored: number; + }; } ⋮---- -export interface WsMessageMarginLevelChangeFormatted extends WsSharedBase { - eventType: 'marginLevelChange'; +export interface WsMessageContinuousKlineFormatted extends WsSharedBase { + eventType: 'continuous_kline'; eventTime: number; - marginLevel: string; - status: string; -} -⋮---- -export interface WsMessageMarginLiabilityChangeAssetFormatted { - asset: string; - principal: string; - interest: string; + symbol: string; + contractType: FuturesContractType; + kline: { + startTime: number; + endTime: number; + symbol: string; + interval: KlineInterval; + firstTradeId: number; + lastTradeId: number; + open: number; + close: number; + high: number; + low: number; + volume: number; + trades: number; + final: boolean; + quoteVolume: number; + volumeActive: number; + quoteVolumeActive: number; + ignored: number; + }; } ⋮---- -export interface WsMessageMarginLiabilityChangeFormatted extends WsSharedBase { - eventType: 'liabilityChange'; +export interface WsMessageAggTradeFormatted extends WsSharedBase { + eventType: 'aggTrade'; eventTime: number; - type: string; - asset?: string; - transactionId?: number; - principal?: string; - interest?: string; - totalLiability?: string; - liabilities?: WsMessageMarginLiabilityChangeAssetFormatted[]; -} -⋮---- -export interface WsAccountUpdatedBalance { - asset: string; - balanceChange: number; // this is except for pnl and commission - crossWalletBalance: number; - walletBalance: number; -} -⋮---- -balanceChange: number; // this is except for pnl and commission -⋮---- -export interface WsUpdatedPosition { symbol: string; - marginAsset: string; - positionAmount: number; - entryPrice: number; - accumulatedRealisedPreFee: number; - unrealisedPnl: number; - marginType: 'cross' | 'isolated'; - isolatedWalletAmount: number; - positionSide: PositionSide; + tradeId: number; + price: number; + quantity: number; + firstTradeId: number; + lastTradeId: number; + time: number; + maker: boolean; + ignored: boolean; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesUserDataListenKeyExpiredFormatted - extends WsSharedBase { - eventType: 'listenKeyExpired'; +export interface WsMessageTradeFormatted extends WsSharedBase { + eventType: 'trade'; eventTime: number; -} -⋮---- -export interface WsMessageFuturesMarginCalledPositionFormatted { symbol: string; - positionSide: PositionSide; - positionAmount: number; - marginType: Uppercase; - isolatedWalletAmount: number; - markPrice: number; - unrealisedPnl: number; - maintenanceMarginRequired: number; + tradeId: number; + price: number; + quantity: number; + buyerOrderId: number; + sellerOrderId: number; + time: number; + maker: boolean; + ignored: boolean; } ⋮---- -export interface WsMessageFuturesUserDataMarginCallFormatted - extends WsSharedBase { - eventType: 'MARGIN_CALL'; +export interface WsMessageBlockTradeFormatted extends WsSharedBase { + eventType: 'blockTrade'; eventTime: number; - crossWalletBalance: number; - positions: WsMessageFuturesMarginCalledPositionFormatted[]; + symbol: string; + tradeId: number; + price: number; + quantity: number; + time: number; + maker: boolean; } ⋮---- -export interface WsMessageFuturesUserDataAccountUpdateFormatted - extends WsSharedBase { - eventType: 'ACCOUNT_UPDATE'; +export interface WsMessage24hrMiniTickerFormatted extends WsSharedBase { + eventType: '24hrMiniTicker'; eventTime: number; - transactionTime: number; - updateData: { - updateEventType: AccountUpdateEventType; - symbol?: string; // only when updateEventType is FUNDING_FEE - updatedBalances: WsAccountUpdatedBalance[]; - updatedPositions: WsUpdatedPosition[]; - }; + symbol: string; + contractSymbol?: string; //coinm only + close: number; + open: number; + high: number; + low: number; + baseAssetVolume: number; + quoteAssetVolume: number; + symbolType?: FuturesMarketSymbolType; } ⋮---- -symbol?: string; // only when updateEventType is FUNDING_FEE -⋮---- -export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted - extends WsSharedBase { - eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; - eventTime: number; - transactionTime: number; - order: { - symbol: string; - orderId: number; - reason: string; - }; -} +contractSymbol?: string; //coinm only ⋮---- -export interface WsMessageFuturesUserDataTradeLiteEventFormatted - extends WsSharedBase { - eventType: 'TRADE_LITE'; +export interface WsMessage24hrTickerFormatted extends WsSharedBase { + /** + * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). + * Will be retired on 2026-03-26. + * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. + */ + eventType: '24hrTicker' | '!ticker@arr'; eventTime: number; - transactionTime: number; symbol: string; - originalQuantity: number; - originalPrice: number; - isMakerSide: boolean; - clientOrderId: string; - side: 'BUY' | 'SELL'; - lastFilledPrice: number; - lastFilledQuantity: number; - tradeId: number; - orderId: number; + priceChange: number; + priceChangePercent: number; + weightedAveragePrice: number; + previousClose: number; + currentClose: number; + closeQuantity: number; + bestBid: number; + bestBidQuantity: number; + bestAskPrice: number; + bestAskQuantity: number; + open: number; + high: number; + low: number; + baseAssetVolume: number; + quoteAssetVolume: number; + openTime: number; + closeTime: number; + firstTradeId: number; + lastTradeId: number; + trades: number; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesUserDataTradeUpdateEventFormatted - extends WsSharedBase { - eventType: 'ORDER_TRADE_UPDATE'; +/** + * @deprecated '!ticker@arr' stream has been deprecated by Binance (2025-11-14). + * Will be retired on 2026-03-26. + * Use '@ticker' for single symbol or '!miniTicker@arr' for all symbols instead. + */ +⋮---- +export interface WsMessageRollingWindowTickerFormatted extends WsSharedBase { + eventType: 'ticker'; eventTime: number; - transactionTime: number; - order: { - symbol: string; - clientOrderId: string; - orderSide: OrderSide; - orderType: FuturesOrderType; - timeInForce: OrderTimeInForce; - originalQuantity: number; - originalPrice: number; - averagePrice: number; - stopPrice: number; - executionType: OrderExecutionType; - orderStatus: OrderStatus; - orderId: number; - lastFilledQuantity: number; - orderFilledAccumulatedQuantity: number; - lastFilledPrice: number; - commissionAsset: string; - commissionAmount: number; - orderTradeTime: number; - tradeId: number; - bidsNotional: number; - asksNotional: number; - isMakerTrade: boolean; - isReduceOnly: boolean; - stopPriceWorkingType: WorkingType; - originalOrderType: FuturesOrderType; - positionSide: PositionSide; - isCloseAll: boolean; - realisedProfit: number; - trailingStopActivationPrice?: number; - trailingStopCallbackRate?: number; - orderExpireReason?: string; // Order expire reason - modifyId?: string; // from modify request; only when executionType is AMENDMENT - pP?: boolean; // ignore - si?: number; // ignore - ss?: number; // ignore - }; + symbol: string; + priceChange: number; + priceChangePercent: number; + weightedAveragePrice: number; + open: number; + high: number; + low: number; + currentClose: number; + baseAssetVolume: number; + quoteAssetVolume: number; + openTime: number; + closeTime: number; + firstTradeId: number; + lastTradeId: number; + trades: number; + streamName: string; + isWSAPIResponse: false; } ⋮---- -orderExpireReason?: string; // Order expire reason -modifyId?: string; // from modify request; only when executionType is AMENDMENT -pP?: boolean; // ignore -si?: number; // ignore -ss?: number; // ignore -⋮---- -export interface WsMessageFuturesUserDataAccountConfigUpdateEventFormatted - extends WsSharedBase { - eventType: 'ACCOUNT_CONFIG_UPDATE'; +export interface WsMessageBookTickerEventFormatted extends WsSharedBase { + eventType: 'bookTicker'; + updateId: number; eventTime: number; transactionTime: number; - assetConfiguration?: { - symbol: string; - leverage: number; - }; - accountConfiguration?: { - isMultiAssetsMode: boolean; - }; + symbol: string; + bidPrice: number; + bidQty: number; + askPrice: number; + askQty: number; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { - eventType: 'indexPriceUpdate'; - eventTime: number; - symbol: string; - indexPrice: number; +export interface WsMessagePartialBookDepthEventFormatted extends WsSharedBase { + eventType: 'partialBookDepth' | 'string'; + lastUpdateId: number; + bids: OrderBookRowFormatted[]; + asks: OrderBookRowFormatted[]; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageMarkPriceEventFormatted extends WsSharedBase { - eventType: 'markPriceUpdate'; +export interface WsMessageDiffBookDepthEventFormatted extends WsSharedBase { + eventType: 'depthUpdate'; eventTime: number; + transactionTime: number; // futures only symbol: string; - markPrice: number; - /** Mark price moving average (USDⓈ-M). */ - markPriceMovingAverage?: number; - settlePriceEstimate: number; - indexPrice?: number; // undefined for coinm - /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ - fundingRate: number | ''; - nextFundingTime: number; + firstUpdateId: number; + lastUpdateId: number; + finalUpdateId: number; // futures only + bidDepthDelta: { price: number; quantity: number }[]; + askDepthDelta: { price: number; quantity: number }[]; symbolType?: FuturesMarketSymbolType; } ⋮---- -/** Mark price moving average (USDⓈ-M). */ +transactionTime: number; // futures only ⋮---- -indexPrice?: number; // undefined for coinm -/** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ +finalUpdateId: number; // futures only ⋮---- -export interface WsLiquidationOrderFormatted { - symbol: string; - side: OrderSide; - orderType: FuturesOrderType; - timeInForce: OrderTimeInForce; - quantity: number; - price: number; - averagePrice: number; - orderStatus: OrderStatus; - lastFilledQuantity: number; - orderFilledAccumulatedQuantity: number; - orderTradeTime: number; +/** + * USER DATA WS EVENTS + **/ +⋮---- +interface SpotBalanceFormatted { + asset: string; + availableBalance: number; + onOrderBalance: number; } ⋮---- -export interface WsMessageForceOrderFormatted extends WsSharedBase { - eventType: 'forceOrder'; +export interface WsMessageSpotOutboundAccountPositionFormatted + extends WsSharedBase { + eventType: 'outboundAccountPosition'; eventTime: number; - liquidationOrder: WsLiquidationOrderFormatted; - symbolType?: FuturesMarketSymbolType; + lastAccountUpdateTime: number; + balances: SpotBalanceFormatted[]; } ⋮---- -export interface WsMessageFuturesUserDataStrategyUpdateFormatted - extends WsSharedBase { - eventType: 'STRATEGY_UPDATE'; - transactionTime: number; +export interface WsMessageSpotBalanceUpdateFormatted extends WsSharedBase { + eventType: 'balanceUpdate'; eventTime: number; - strategy: { - strategyId: number; - strategyType: string; - strategyStatus: string; - symbol: string; - updateTime: number; - opCode: number; - }; + asset: string; + balanceDelta: number; + clearTime: number; } ⋮---- -export interface WsMessageFuturesUserDataGridUpdateFormatted +export interface WsMessageSpotUserDataExecutionReportEventFormatted extends WsSharedBase { - eventType: 'GRID_UPDATE'; - transactionTime: number; + eventType: 'executionReport'; eventTime: number; - grid: { - strategyId: number; - strategyType: string; - strategyStatus: string; - symbol: string; - realizedPnl: numberInString; - unmatchedAveragePrice: numberInString; - unmatchedQuantity: numberInString; - unmatchedFee: numberInString; - matchedPnl: numberInString; - updateTime: number; - }; + symbol: string; + newClientOrderId: string; + side: OrderSide; + orderType: OrderType; + cancelType: OrderTimeInForce; + quantity: number; + price: number; + stopPrice: number; + icebergQuantity: number; + orderListId: number; + originalClientOrderId: string; + executionType: OrderExecutionType; + orderStatus: OrderStatus; + rejectReason: string; + orderId: number; + lastTradeQuantity: number; + accumulatedQuantity: number; + lastTradePrice: number; + commission: number; + commissionAsset: string | null; + tradeTime: number; + tradeId: number; + ignoreThis1: number; + isOrderOnBook: boolean; + isMaker: boolean; + ignoreThis2: true; + orderCreationTime: number; + cummulativeQuoteAssetTransactedQty: number; + lastQuoteAssetTransactedQty: number; + orderQuoteQty: number; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + expiryReason?: string; + trailingDelta?: number; + preventedMatchId?: number; + trailingTime?: number; + strategyId?: number; + strategyType?: number; + tradeGroupId?: number; + counterOrderId?: number; + /** Allocation ID. */ + allocationId?: number; + preventedQuantity?: number; + lastPreventedQuantity?: number; + counterSymbol?: string; + preventedExecutionQuantity?: number; + preventedExecutionPrice?: number; + preventedExecutionQuoteQty?: number; } ⋮---- -export interface WsMessageFuturesUserDataContractInfoFormatted +/** Allocation ID. */ +⋮---- +export interface WsMessagePortfolioMarginProAccountUpdateFormatted extends WsSharedBase { - eventType: 'contractInfo'; + eventType: 'PM_PRO_ACCOUNT_UPDATE'; + eventTime: number; + uniMMR: number; + accountEquity: number; + actualEquity: number; + initialMargin: number; + maintenanceMargin: number; + availableBalance: number; + virtualMaxWithdraw: number; +} +⋮---- +export interface WsMessageWsapiServerShutdownFormatted extends WsSharedBase { + eventType: 'serverShutdown'; eventTime: number; +} +⋮---- +export interface OrderObjectFormatted { symbol: string; - pair: string; - contractType: string; - deliveryDateTime: number; - onboardDateTime: number; - contractStatus: string; - notionalBrackets: { - notionalBracket: number; - floorNotional: number; - capNotional: number; - maintenanceRatio: number; - auxiliaryNumber: number; - minLeverage: number; - maxLeverage: number; - }[]; - symbolType?: FuturesMarketSymbolType; + orderId: number; + clientOrderId: string; } ⋮---- -export interface WsMessageFuturesUserDataAlgoUpdateFormatted +export interface WsMessageSpotUserDataListStatusEventFormatted extends WsSharedBase { - eventType: 'ALGO_UPDATE'; + eventType: 'listStatus'; eventTime: number; + symbol: string; + orderListId: number; + contingencyType: OrderListContingencyType; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listRejectReason: string; + listClientOrderId: string; transactionTime: number; - algoOrder: { - clientAlgoId: string; - algoId: number; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; - symbol: string; - side: OrderSide; - positionSide: PositionSide; - timeInForce: OrderTimeInForce; - quantity: numberInString; - algoStatus: FuturesAlgoOrderStatus; - orderId: string; - averagePrice: numberInString; - executedQty: numberInString; - actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType - triggerPrice: numberInString; - price: numberInString; - selfTradePreventionMode: SelfTradePreventionMode; - workingType: WorkingType; - priceMatch: PriceMatchMode; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - triggerTime: number; - goodTillDate: number; - isActivated?: boolean; // trailing stop activation; placeholder, always false for now - // As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). - }; + orders: OrderObjectFormatted[]; } ⋮---- -actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType +export interface WsMessageMarginLevelChangeFormatted extends WsSharedBase { + eventType: 'marginLevelChange'; + eventTime: number; + marginLevel: string; + status: string; +} ⋮---- -isActivated?: boolean; // trailing stop activation; placeholder, always false for now -// As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). +export interface WsMessageMarginLiabilityChangeAssetFormatted { + asset: string; + principal: string; + interest: string; +} ⋮---- -export type WsMessageSpotUserDataEventFormatted = - | WsMessageSpotUserDataExecutionReportEventFormatted - | WsMessageSpotOutboundAccountPositionFormatted - | WsMessageSpotBalanceUpdateFormatted - | WsMessageSpotUserDataListStatusEventFormatted; +export interface WsMessageMarginLiabilityChangeFormatted extends WsSharedBase { + eventType: 'liabilityChange'; + eventTime: number; + type: string; + asset?: string; + transactionId?: number; + principal?: string; + interest?: string; + totalLiability?: string; + liabilities?: WsMessageMarginLiabilityChangeAssetFormatted[]; +} ⋮---- -export type WsMessageFuturesUserDataEventFormatted = - | WsMessageFuturesUserDataAccountUpdateFormatted - | WsMessageFuturesUserDataListenKeyExpiredFormatted - | WsMessageFuturesUserDataMarginCallFormatted - | WsMessageFuturesUserDataTradeUpdateEventFormatted - | WsMessageFuturesUserDataAlgoUpdateFormatted - | WsMessageFuturesUserDataAccountConfigUpdateEventFormatted - | WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted - | WsMessageFuturesUserDataTradeLiteEventFormatted - | WsMessageFuturesUserDataStrategyUpdateFormatted - | WsMessageFuturesUserDataGridUpdateFormatted - | WsMessageFuturesUserDataContractInfoFormatted; +export interface WsAccountUpdatedBalance { + asset: string; + balanceChange: number; // this is except for pnl and commission + crossWalletBalance: number; + walletBalance: number; +} ⋮---- -export type WsUserDataEvents = - | WsMessageSpotUserDataEventFormatted - | WsMessageFuturesUserDataEventFormatted - | WsMessagePortfolioMarginProAccountUpdateFormatted - | WsMessageMarginLevelChangeFormatted - | WsMessageMarginLiabilityChangeFormatted; +balanceChange: number; // this is except for pnl and commission ⋮---- -export type WsFormattedMessage = - | WsUserDataEvents - | WsMessageWsapiServerShutdownFormatted - | WsMessageKlineFormatted - | WsMessageAggTradeFormatted - | WsMessageTradeFormatted - | WsMessageBlockTradeFormatted - | WsMessage24hrMiniTickerFormatted - | WsMessage24hrTickerFormatted - | WsMessageBookTickerEventFormatted - | WsMessagePartialBookDepthEventFormatted - | WsMessageDiffBookDepthEventFormatted - | WsMessageIndexPriceUpdateEventFormatted - | WsMessageMarkPriceEventFormatted - | WsMessageForceOrderFormatted - | WsMessage24hrMiniTickerFormatted[] - | WsMessage24hrTickerFormatted[] - | WsMessageRollingWindowTickerFormatted[] - | WsMessageMarkPriceEventFormatted[]; - -================ -File: src/types/websockets/ws-events-raw.ts -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderStatus, - FuturesAlgoOrderType, - FuturesOrderType, - MarginType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - KlineInterval, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRow, - OrderExecutionType, - OrderListContingencyType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -import { WsSharedBase } from './ws-general'; +export interface WsUpdatedPosition { + symbol: string; + marginAsset: string; + positionAmount: number; + entryPrice: number; + accumulatedRealisedPreFee: number; + unrealisedPnl: number; + marginType: 'cross' | 'isolated'; + isolatedWalletAmount: number; + positionSide: PositionSide; +} ⋮---- -/** 1 = USD-M, 2 = COIN-M. Present on merged futures market streams. */ -export type FuturesMarketSymbolType = 1 | 2; +export interface WsMessageFuturesUserDataListenKeyExpiredFormatted + extends WsSharedBase { + eventType: 'listenKeyExpired'; + eventTime: number; +} ⋮---- -export interface WsMessageKlineRaw extends WsSharedBase { - e: 'kline'; - E: number; - s: string; - k: { - t: number; - T: number; - s: string; - i: KlineInterval; - f: number; - L: number; - o: numberInString; - c: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - n: number; - x: boolean; - q: numberInString; - V: numberInString; - Q: numberInString; - B: numberInString; - }; -} -export interface WsMessageAggTradeRaw extends WsSharedBase { - e: 'aggTrade'; - E: number; - s: string; - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; - M: boolean; - st?: FuturesMarketSymbolType; +export interface WsMessageFuturesMarginCalledPositionFormatted { + symbol: string; + positionSide: PositionSide; + positionAmount: number; + marginType: Uppercase; + isolatedWalletAmount: number; + markPrice: number; + unrealisedPnl: number; + maintenanceMarginRequired: number; } ⋮---- -export interface WsMessageTradeRaw extends WsSharedBase { - e: 'trade'; - E: number; - s: string; - t: number; - p: numberInString; - q: numberInString; - b: number; - a: number; - T: number; - m: boolean; - M: boolean; +export interface WsMessageFuturesUserDataMarginCallFormatted + extends WsSharedBase { + eventType: 'MARGIN_CALL'; + eventTime: number; + crossWalletBalance: number; + positions: WsMessageFuturesMarginCalledPositionFormatted[]; } ⋮---- -export interface WsMessageBlockTradeRaw extends WsSharedBase { - e: 'blockTrade'; - E: number; - s: string; - t: number; - p: numberInString; - q: numberInString; - T: number; - m: boolean; +export interface WsMessageFuturesUserDataAccountUpdateFormatted + extends WsSharedBase { + eventType: 'ACCOUNT_UPDATE'; + eventTime: number; + transactionTime: number; + updateData: { + updateEventType: AccountUpdateEventType; + symbol?: string; // only when updateEventType is FUNDING_FEE + updatedBalances: WsAccountUpdatedBalance[]; + updatedPositions: WsUpdatedPosition[]; + }; } ⋮---- -export interface WsMessage24hrMiniTickerRaw extends WsSharedBase { - e: '24hrMiniTicker'; - E: number; - s: string; - c: numberInString; - o: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - q: numberInString; - st?: FuturesMarketSymbolType; -} +symbol?: string; // only when updateEventType is FUNDING_FEE ⋮---- -export interface WsMessage24hrTickerRaw extends WsSharedBase { - e: '24hrTicker'; - E: number; - s: string; - p: numberInString; - P: numberInString; - w: numberInString; - x: numberInString; - c: numberInString; - Q: numberInString; - b: numberInString; - B: numberInString; - a: numberInString; - A: numberInString; - o: numberInString; - h: numberInString; - l: numberInString; - v: numberInString; - q: numberInString; - O: numberInString; - C: numberInString; - F: number; - L: number; - n: number; - st?: FuturesMarketSymbolType; +export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted + extends WsSharedBase { + eventType: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; + eventTime: number; + transactionTime: number; + order: { + symbol: string; + orderId: number; + reason: string; + }; } ⋮---- -export interface WsMessageRollingWindowTickerRaw extends WsSharedBase { - e: '1hTicker' | '4hTicker' | '1dTicker'; - E: number; - s: string; - p: string; - P: string; - w: string; - o: string; - h: string; - l: string; - c: string; - v: string; - q: string; - O: number; - C: number; - F: number; - L: number; - n: number; +export interface WsMessageFuturesUserDataTradeLiteEventFormatted + extends WsSharedBase { + eventType: 'TRADE_LITE'; + eventTime: number; + transactionTime: number; + symbol: string; + originalQuantity: number; + originalPrice: number; + isMakerSide: boolean; + clientOrderId: string; + side: 'BUY' | 'SELL'; + lastFilledPrice: number; + lastFilledQuantity: number; + tradeId: number; + orderId: number; } ⋮---- -export interface WsMessageBookTickerEventRaw extends WsSharedBase { - e: 'bookTicker'; - u: number; - E: number; // futures only - event time - T: number; // futures only - transaction time - s: string; - b: numberInString; - B: numberInString; - a: numberInString; - A: numberInString; - st?: FuturesMarketSymbolType; +export interface WsMessageFuturesUserDataTradeUpdateEventFormatted + extends WsSharedBase { + eventType: 'ORDER_TRADE_UPDATE'; + eventTime: number; + transactionTime: number; + order: { + symbol: string; + clientOrderId: string; + orderSide: OrderSide; + orderType: FuturesOrderType; + timeInForce: OrderTimeInForce; + originalQuantity: number; + originalPrice: number; + averagePrice: number; + stopPrice: number; + executionType: OrderExecutionType; + orderStatus: OrderStatus; + orderId: number; + lastFilledQuantity: number; + orderFilledAccumulatedQuantity: number; + lastFilledPrice: number; + commissionAsset: string; + commissionAmount: number; + orderTradeTime: number; + tradeId: number; + bidsNotional: number; + asksNotional: number; + isMakerTrade: boolean; + isReduceOnly: boolean; + stopPriceWorkingType: WorkingType; + originalOrderType: FuturesOrderType; + positionSide: PositionSide; + isCloseAll: boolean; + realisedProfit: number; + trailingStopActivationPrice?: number; + trailingStopCallbackRate?: number; + orderExpireReason?: string; // Order expire reason + modifyId?: string; // from modify request; only when executionType is AMENDMENT + pP?: boolean; // ignore + si?: number; // ignore + ss?: number; // ignore + }; } ⋮---- -E: number; // futures only - event time -T: number; // futures only - transaction time -⋮---- -export interface WsMessagePartialBookDepthEventRaw extends WsSharedBase { - e: 'partialBookDepth'; - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; - st?: FuturesMarketSymbolType; -} +orderExpireReason?: string; // Order expire reason +modifyId?: string; // from modify request; only when executionType is AMENDMENT +pP?: boolean; // ignore +si?: number; // ignore +ss?: number; // ignore ⋮---- -export interface WsMessageDiffBookDepthEventRaw extends WsSharedBase { - e: 'depthUpdate'; - E: number; - T: number; // futures only - s: string; - U: number; - u: number; - pu: number; // futures only - b: OrderBookRow[]; - a: OrderBookRow[]; - st?: FuturesMarketSymbolType; +export interface WsMessageFuturesUserDataAccountConfigUpdateEventFormatted + extends WsSharedBase { + eventType: 'ACCOUNT_CONFIG_UPDATE'; + eventTime: number; + transactionTime: number; + assetConfiguration?: { + symbol: string; + leverage: number; + }; + accountConfiguration?: { + isMultiAssetsMode: boolean; + }; } ⋮---- -T: number; // futures only +export interface WsMessageIndexPriceUpdateEventFormatted extends WsSharedBase { + eventType: 'indexPriceUpdate'; + eventTime: number; + symbol: string; + indexPrice: number; +} ⋮---- -pu: number; // futures only +export interface WsMessageMarkPriceEventFormatted extends WsSharedBase { + eventType: 'markPriceUpdate'; + eventTime: number; + symbol: string; + markPrice: number; + /** Mark price moving average (USDⓈ-M). */ + markPriceMovingAverage?: number; + settlePriceEstimate: number; + indexPrice?: number; // undefined for coinm + /** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ + fundingRate: number | ''; + nextFundingTime: number; + symbolType?: FuturesMarketSymbolType; +} ⋮---- -/** - * USER DATA WS EVENTS - **/ +/** Mark price moving average (USDⓈ-M). */ ⋮---- -interface SpotBalanceRaw { - a: string; - f: numberInString; - l: numberInString; -} +indexPrice?: number; // undefined for coinm +/** Note this is in decimal format (e.g. 0.0004 === 0.04%). Multiply by 100 to get funding rate percent value */ ⋮---- -export interface WsMessageSpotOutboundAccountPositionRaw extends WsSharedBase { - e: 'outboundAccountPosition'; - E: number; - u: number; - B: SpotBalanceRaw[]; +export interface WsLiquidationOrderFormatted { + symbol: string; + side: OrderSide; + orderType: FuturesOrderType; + timeInForce: OrderTimeInForce; + quantity: number; + price: number; + averagePrice: number; + orderStatus: OrderStatus; + lastFilledQuantity: number; + orderFilledAccumulatedQuantity: number; + orderTradeTime: number; } ⋮---- -export interface WsMessageSpotBalanceUpdateRaw extends WsSharedBase { - e: 'balanceUpdate'; - E: number; - a: string; - d: numberInString; - T: number; +export interface WsMessageForceOrderFormatted extends WsSharedBase { + eventType: 'forceOrder'; + eventTime: number; + liquidationOrder: WsLiquidationOrderFormatted; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageSpotUserDataExecutionReportEventRaw +export interface WsMessageFuturesUserDataStrategyUpdateFormatted extends WsSharedBase { - e: 'executionReport'; - E: number; - s: string; - c: string; - S: OrderSide; - o: OrderType; - f: OrderTimeInForce; - q: numberInString; - p: numberInString; - P: numberInString; - F: numberInString; - g: number; - C: string; - x: OrderExecutionType; - X: OrderStatus; - r: string; - i: number; - l: numberInString; - z: numberInString; - L: numberInString; - n: numberInString; - N: string | null; - T: number; - t: number; - I: number; - w: boolean; - m: boolean; - M: boolean; - O: number; - Z: numberInString; - Y: numberInString; - Q: numberInString; - W: number; - V: SelfTradePreventionMode; - /** Expiry reason when present (user data executionReport). */ - eR?: string; - d?: number; - v?: number; - D?: number; - j?: number; - J?: number; - u?: number; - U?: number; - /** Allocation ID. */ - a?: number; - A?: numberInString; - B?: numberInString; - Cs?: string; - pl?: numberInString; - pL?: numberInString; - pY?: numberInString; + eventType: 'STRATEGY_UPDATE'; + transactionTime: number; + eventTime: number; + strategy: { + strategyId: number; + strategyType: string; + strategyStatus: string; + symbol: string; + updateTime: number; + opCode: number; + }; } ⋮---- -/** Expiry reason when present (user data executionReport). */ -⋮---- -/** Allocation ID. */ -⋮---- -export interface WsMessagePortfolioMarginProAccountUpdateRaw +export interface WsMessageFuturesUserDataGridUpdateFormatted extends WsSharedBase { - e: 'PM_PRO_ACCOUNT_UPDATE'; - E: number; - u: numberInString; - eq: numberInString; - ae: numberInString; - im: numberInString; - mm: numberInString; - avb: numberInString; - vmw: numberInString; + eventType: 'GRID_UPDATE'; + transactionTime: number; + eventTime: number; + grid: { + strategyId: number; + strategyType: string; + strategyStatus: string; + symbol: string; + realizedPnl: numberInString; + unmatchedAveragePrice: numberInString; + unmatchedQuantity: numberInString; + unmatchedFee: numberInString; + matchedPnl: numberInString; + updateTime: number; + }; } ⋮---- -export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { - e: 'serverShutdown'; - E: number; +export interface WsMessageFuturesUserDataContractInfoFormatted + extends WsSharedBase { + eventType: 'contractInfo'; + eventTime: number; + symbol: string; + pair: string; + contractType: string; + deliveryDateTime: number; + onboardDateTime: number; + contractStatus: string; + notionalBrackets: { + notionalBracket: number; + floorNotional: number; + capNotional: number; + maintenanceRatio: number; + auxiliaryNumber: number; + minLeverage: number; + maxLeverage: number; + }[]; + symbolType?: FuturesMarketSymbolType; } ⋮---- -export interface OrderObjectRaw { - s: string; - i: number; - c: string; +export interface WsMessageFuturesUserDataAlgoUpdateFormatted + extends WsSharedBase { + eventType: 'ALGO_UPDATE'; + eventTime: number; + transactionTime: number; + algoOrder: { + clientAlgoId: string; + algoId: number; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; + side: OrderSide; + positionSide: PositionSide; + timeInForce: OrderTimeInForce; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + orderId: string; + averagePrice: numberInString; + executedQty: numberInString; + actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType + triggerPrice: numberInString; + price: numberInString; + selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; + priceMatch: PriceMatchMode; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + triggerTime: number; + goodTillDate: number; + isActivated?: boolean; // trailing stop activation; placeholder, always false for now + // As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). + }; } ⋮---- -export interface WsMessageMarginLevelChangeRaw extends WsSharedBase { - e: 'marginLevelChange'; - E: number; - l: string; - s: string; -} +actualOrderType: numberInString; // TODO unsure if it's FuturesOrderType ⋮---- -export interface WsMessageMarginLiabilityChangeRaw extends WsSharedBase { - e: 'liabilityChange'; - E: number; - t: 'BORROW' | 'REPAY' | 'INTEREST' | 'DEBT_CHANGE'; - L: { - a: string; - p: string; - i: string; - }[]; -} +isActivated?: boolean; // trailing stop activation; placeholder, always false for now +// As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). ⋮---- -export interface WsMessageSpotUserDataListStatusEventRaw extends WsSharedBase { - e: 'listStatus'; - E: number; - s: string; - g: number; - c: OrderListContingencyType; - l: OCOStatus; - L: OCOOrderStatus; - r: string; - C: string; - T: number; - O: OrderObjectRaw[]; -} +export type WsMessageSpotUserDataEventFormatted = + | WsMessageSpotUserDataExecutionReportEventFormatted + | WsMessageSpotOutboundAccountPositionFormatted + | WsMessageSpotBalanceUpdateFormatted + | WsMessageSpotUserDataListStatusEventFormatted; ⋮---- -export type AccountUpdateEventType = - | 'DEPOSIT' - | 'WITHDRAW' - | 'ORDER' - | 'FUNDING_FEE' - | 'WITHDRAW_REJECT' - | 'ADJUSTMENT' - | 'INSURANCE_CLEAR' - | 'ADMIN_DEPOSIT' - | 'ADMIN_WITHDRAW' - | 'MARGIN_TRANSFER' - | 'MARGIN_TYPE_CHANGE' - | 'ASSET_TRANSFER' - | 'OPTIONS_PREMIUM_FEE' - | 'OPTIONS_SETTLE_PROFIT' - | 'AUTO_EXCHANGE'; +export type WsMessageFuturesUserDataEventFormatted = + | WsMessageFuturesUserDataAccountUpdateFormatted + | WsMessageFuturesUserDataListenKeyExpiredFormatted + | WsMessageFuturesUserDataMarginCallFormatted + | WsMessageFuturesUserDataTradeUpdateEventFormatted + | WsMessageFuturesUserDataAlgoUpdateFormatted + | WsMessageFuturesUserDataAccountConfigUpdateEventFormatted + | WsMessageFuturesUserDataCondOrderTriggerRejectEventFormatted + | WsMessageFuturesUserDataTradeLiteEventFormatted + | WsMessageFuturesUserDataStrategyUpdateFormatted + | WsMessageFuturesUserDataGridUpdateFormatted + | WsMessageFuturesUserDataContractInfoFormatted; ⋮---- -export interface WsMessageFuturesUserDataListenKeyExpiredRaw - extends WsSharedBase { - e: 'listenKeyExpired'; +export type WsUserDataEvents = + | WsMessageSpotUserDataEventFormatted + | WsMessageFuturesUserDataEventFormatted + | WsMessagePortfolioMarginProAccountUpdateFormatted + | WsMessageMarginLevelChangeFormatted + | WsMessageMarginLiabilityChangeFormatted; +⋮---- +export type WsFormattedMessage = + | WsUserDataEvents + | WsMessageWsapiServerShutdownFormatted + | WsMessageKlineFormatted + | WsMessageAggTradeFormatted + | WsMessageTradeFormatted + | WsMessageBlockTradeFormatted + | WsMessage24hrMiniTickerFormatted + | WsMessage24hrTickerFormatted + | WsMessageBookTickerEventFormatted + | WsMessagePartialBookDepthEventFormatted + | WsMessageDiffBookDepthEventFormatted + | WsMessageIndexPriceUpdateEventFormatted + | WsMessageMarkPriceEventFormatted + | WsMessageForceOrderFormatted + | WsMessage24hrMiniTickerFormatted[] + | WsMessage24hrTickerFormatted[] + | WsMessageRollingWindowTickerFormatted[] + | WsMessageMarkPriceEventFormatted[]; + +================ +File: src/types/websockets/ws-events-raw.ts +================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderStatus, + FuturesAlgoOrderType, + FuturesOrderType, + MarginType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + KlineInterval, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRow, + OrderExecutionType, + OrderListContingencyType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +import { WsSharedBase } from './ws-general'; +⋮---- +/** 1 = USD-M, 2 = COIN-M. Present on merged futures market streams. */ +export type FuturesMarketSymbolType = 1 | 2; +⋮---- +export interface WsMessageKlineRaw extends WsSharedBase { + e: 'kline'; E: number; + s: string; + k: { + t: number; + T: number; + s: string; + i: KlineInterval; + f: number; + L: number; + o: numberInString; + c: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + n: number; + x: boolean; + q: numberInString; + V: numberInString; + Q: numberInString; + B: numberInString; + }; } -⋮---- -export interface WsEventStreamTerminatedRaw extends WsSharedBase { - e: 'eventStreamTerminated'; +export interface WsMessageAggTradeRaw extends WsSharedBase { + e: 'aggTrade'; E: number; + s: string; + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; + st?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesMarginCalledPositionRaw { +export interface WsMessageTradeRaw extends WsSharedBase { + e: 'trade'; + E: number; s: string; - ps: PositionSide; - pa: numberInString; - mt: Uppercase; - iw: numberInString; - mp: numberInString; - up: numberInString; - mm: numberInString; + t: number; + p: numberInString; + q: numberInString; + b: number; + a: number; + T: number; + m: boolean; + M: boolean; } ⋮---- -export interface WsMessageFuturesUserDataMarginCallRaw extends WsSharedBase { - e: 'MARGIN_CALL'; +export interface WsMessageBlockTradeRaw extends WsSharedBase { + e: 'blockTrade'; E: number; - cw: numberInString; - p: WsMessageFuturesMarginCalledPositionRaw[]; + s: string; + t: number; + p: numberInString; + q: numberInString; + T: number; + m: boolean; } ⋮---- -export interface WsMessageFuturesAccountUpdatePositionRaw { +export interface WsMessage24hrMiniTickerRaw extends WsSharedBase { + e: '24hrMiniTicker'; + E: number; s: string; - pa: numberInString; - ep: numberInString; - cr: numberInString; - up: numberInString; - mt: 'cross' | 'isolated'; - iw: numberInString; - ps: PositionSide; + c: numberInString; + o: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + q: numberInString; + st?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesAccountUpdateBalanceRaw { - a: string; - wb: numberInString; - cw: numberInString; - bc: numberInString; +export interface WsMessage24hrTickerRaw extends WsSharedBase { + e: '24hrTicker'; + E: number; + s: string; + p: numberInString; + P: numberInString; + w: numberInString; + x: numberInString; + c: numberInString; + Q: numberInString; + b: numberInString; + B: numberInString; + a: numberInString; + A: numberInString; + o: numberInString; + h: numberInString; + l: numberInString; + v: numberInString; + q: numberInString; + O: numberInString; + C: numberInString; + F: number; + L: number; + n: number; + st?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { - e: 'ACCOUNT_UPDATE'; +export interface WsMessageRollingWindowTickerRaw extends WsSharedBase { + e: '1hTicker' | '4hTicker' | '1dTicker'; E: number; - T: number; - a: { - m: AccountUpdateEventType; - S?: string; // symbol; only when m is FUNDING_FEE - B: WsMessageFuturesAccountUpdateBalanceRaw[]; - P: WsMessageFuturesAccountUpdatePositionRaw[]; - }; + s: string; + p: string; + P: string; + w: string; + o: string; + h: string; + l: string; + c: string; + v: string; + q: string; + O: number; + C: number; + F: number; + L: number; + n: number; } ⋮---- -S?: string; // symbol; only when m is FUNDING_FEE -⋮---- -export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw - extends WsSharedBase { - e: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; - E: number; - T: number; - or: { - s: string; - i: number; - r: string; - }; +export interface WsMessageBookTickerEventRaw extends WsSharedBase { + e: 'bookTicker'; + u: number; + E: number; // futures only - event time + T: number; // futures only - transaction time + s: string; + b: numberInString; + B: numberInString; + a: numberInString; + A: numberInString; + st?: FuturesMarketSymbolType; } ⋮---- -export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw - extends WsSharedBase { - e: 'ORDER_TRADE_UPDATE'; - E: number; - T: number; - o: { - s: string; - c: string; - S: OrderSide; - o: FuturesOrderType; - f: OrderTimeInForce; - q: numberInString; - p: numberInString; - ap: numberInString; - sp: numberInString; - x: OrderExecutionType; - X: OrderStatus; - i: number; - l: numberInString; - z: numberInString; - L: numberInString; - N: string; - n: numberInString; - T: numberInString; - t: number; - b: numberInString; - a: numberInString; - m: boolean; - R: boolean; - wt: WorkingType; - ot: FuturesOrderType; - ps: PositionSide; - cp: boolean; - AP: numberInString; - cr: numberInString; - rp: numberInString; - pP: boolean; // ignore - si: numberInString; // ignore - ss: numberInString; // ignore - V: string; - pm: string; - gtd: number; - er?: string; // Order expire reason (available effective 2025-10-23) - M?: string; // modifyId from modify request; only when x is AMENDMENT - }; -} -⋮---- -pP: boolean; // ignore -si: numberInString; // ignore -ss: numberInString; // ignore +E: number; // futures only - event time +T: number; // futures only - transaction time ⋮---- -er?: string; // Order expire reason (available effective 2025-10-23) -M?: string; // modifyId from modify request; only when x is AMENDMENT +export interface WsMessagePartialBookDepthEventRaw extends WsSharedBase { + e: 'partialBookDepth'; + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; + st?: FuturesMarketSymbolType; +} ⋮---- -export interface WsMessageFuturesUserDataAlgoUpdateRaw extends WsSharedBase { - e: 'ALGO_UPDATE'; +export interface WsMessageDiffBookDepthEventRaw extends WsSharedBase { + e: 'depthUpdate'; E: number; - T: number; - o: { - caid: string; - aid: number; - at: FuturesAlgoOrderType; - o: FuturesAlgoConditionalOrderTypes; - s: string; - S: OrderSide; - ps: PositionSide; - f: OrderTimeInForce; - q: numberInString; - X: FuturesAlgoOrderStatus; - ai: string; - tp: numberInString; - p: numberInString; - V: SelfTradePreventionMode; - wt: WorkingType; - pm: PriceMatchMode; - cp: boolean; - pP: boolean; - R: boolean; - tt: number; - gtd: number; - ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now - // As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). - }; + T: number; // futures only + s: string; + U: number; + u: number; + pu: number; // futures only + b: OrderBookRow[]; + a: OrderBookRow[]; + st?: FuturesMarketSymbolType; } ⋮---- -ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now -// As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). +T: number; // futures only ⋮---- -export interface WsMessageFuturesUserDataTradeLiteEventRaw - extends WsSharedBase { - e: 'TRADE_LITE'; // Event Type - E: number; // Event Time - T: number; // Transaction Time - s: string; // Symbol - q: string; // Original Quantity - p: string; // Original Price - m: boolean; // Is this trade the maker side? - c: string; // Client Order Id - S: 'BUY' | 'SELL'; // Side - L: string; // Last Filled Price - l: string; // Order Last Filled Quantity - t: number; // Trade Id - i: number; // Order Id -} +pu: number; // futures only ⋮---- -e: 'TRADE_LITE'; // Event Type -E: number; // Event Time -T: number; // Transaction Time -s: string; // Symbol -q: string; // Original Quantity -p: string; // Original Price -m: boolean; // Is this trade the maker side? -c: string; // Client Order Id -S: 'BUY' | 'SELL'; // Side -L: string; // Last Filled Price -l: string; // Order Last Filled Quantity -t: number; // Trade Id -i: number; // Order Id +/** + * USER DATA WS EVENTS + **/ ⋮---- -export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw - extends WsSharedBase { - e: 'ACCOUNT_CONFIG_UPDATE'; +interface SpotBalanceRaw { + a: string; + f: numberInString; + l: numberInString; +} +⋮---- +export interface WsMessageSpotOutboundAccountPositionRaw extends WsSharedBase { + e: 'outboundAccountPosition'; E: number; - T: number; - ac?: { - s: string; - l: number; - }; - ai?: { - j: boolean; - }; + u: number; + B: SpotBalanceRaw[]; } ⋮---- -export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { - e: 'indexPriceUpdate'; +export interface WsMessageSpotBalanceUpdateRaw extends WsSharedBase { + e: 'balanceUpdate'; E: number; - i?: string; - s?: string; - p: numberInString; + a: string; + d: numberInString; + T: number; } ⋮---- -export interface WsMessageMarkPriceUpdateEventRaw extends WsSharedBase { - e: 'markPriceUpdate'; +export interface WsMessageSpotUserDataExecutionReportEventRaw + extends WsSharedBase { + e: 'executionReport'; E: number; s: string; - p: string; - /** Mark price moving average (USDⓈ-M mark price stream). */ - ap?: string; - P: string; - i: string; + c: string; + S: OrderSide; + o: OrderType; + f: OrderTimeInForce; + q: numberInString; + p: numberInString; + P: numberInString; + F: numberInString; + g: number; + C: string; + x: OrderExecutionType; + X: OrderStatus; r: string; + i: number; + l: numberInString; + z: numberInString; + L: numberInString; + n: numberInString; + N: string | null; T: number; - st?: FuturesMarketSymbolType; + t: number; + I: number; + w: boolean; + m: boolean; + M: boolean; + O: number; + Z: numberInString; + Y: numberInString; + Q: numberInString; + W: number; + V: SelfTradePreventionMode; + /** Expiry reason when present (user data executionReport). */ + eR?: string; + d?: number; + v?: number; + D?: number; + j?: number; + J?: number; + u?: number; + U?: number; + /** Allocation ID. */ + a?: number; + A?: numberInString; + B?: numberInString; + Cs?: string; + pl?: numberInString; + pL?: numberInString; + pY?: numberInString; } ⋮---- -/** Mark price moving average (USDⓈ-M mark price stream). */ +/** Expiry reason when present (user data executionReport). */ ⋮---- -export interface WsMessageForceOrderRaw extends WsSharedBase { - e: 'forceOrder'; +/** Allocation ID. */ +⋮---- +export interface WsMessagePortfolioMarginProAccountUpdateRaw + extends WsSharedBase { + e: 'PM_PRO_ACCOUNT_UPDATE'; E: number; - o: { - s: string; - S: string; - o: string; - f: string; - q: string; - p: string; - ap: string; - X: string; - l: string; - z: string; - T: number; - }; - st?: FuturesMarketSymbolType; + u: numberInString; + eq: numberInString; + ae: numberInString; + im: numberInString; + mm: numberInString; + avb: numberInString; + vmw: numberInString; } ⋮---- -export interface WsMessageFuturesUserDataStrategyUpdateRaw - extends WsSharedBase { - e: 'STRATEGY_UPDATE'; // Event Type - T: number; // Transaction Time - E: number; // Event Time - su: { - si: number; // Strategy ID - st: string; // Strategy Type - ss: string; // Strategy Status - s: string; // Symbol - ut: number; // Update Time - c: number; // opCode - }; +export interface WsMessageWsapiServerShutdownRaw extends WsSharedBase { + e: 'serverShutdown'; + E: number; } ⋮---- -e: 'STRATEGY_UPDATE'; // Event Type -T: number; // Transaction Time -E: number; // Event Time +export interface OrderObjectRaw { + s: string; + i: number; + c: string; +} ⋮---- -si: number; // Strategy ID -st: string; // Strategy Type -ss: string; // Strategy Status -s: string; // Symbol -ut: number; // Update Time -c: number; // opCode +export interface WsMessageMarginLevelChangeRaw extends WsSharedBase { + e: 'marginLevelChange'; + E: number; + l: string; + s: string; +} ⋮---- -export interface WsMessageFuturesUserDataGridUpdateRaw extends WsSharedBase { - e: 'GRID_UPDATE'; // Event Type - T: number; // Transaction Time - E: number; // Event Time - gu: { - si: number; // Strategy ID - st: string; // Strategy Type - ss: string; // Strategy Status - s: string; // Symbol - r: numberInString; // Realized PNL - up: numberInString; // Unmatched Average Price - uq: numberInString; // Unmatched Qty - uf: numberInString; // Unmatched Fee - mp: numberInString; // Matched PNL - ut: number; // Update Time - }; +export interface WsMessageMarginLiabilityChangeRaw extends WsSharedBase { + e: 'liabilityChange'; + E: number; + t: 'BORROW' | 'REPAY' | 'INTEREST' | 'DEBT_CHANGE'; + L: { + a: string; + p: string; + i: string; + }[]; } ⋮---- -e: 'GRID_UPDATE'; // Event Type -T: number; // Transaction Time -E: number; // Event Time +export interface WsMessageSpotUserDataListStatusEventRaw extends WsSharedBase { + e: 'listStatus'; + E: number; + s: string; + g: number; + c: OrderListContingencyType; + l: OCOStatus; + L: OCOOrderStatus; + r: string; + C: string; + T: number; + O: OrderObjectRaw[]; +} ⋮---- -si: number; // Strategy ID -st: string; // Strategy Type -ss: string; // Strategy Status -s: string; // Symbol -r: numberInString; // Realized PNL -up: numberInString; // Unmatched Average Price -uq: numberInString; // Unmatched Qty -uf: numberInString; // Unmatched Fee -mp: numberInString; // Matched PNL -ut: number; // Update Time +export type AccountUpdateEventType = + | 'DEPOSIT' + | 'WITHDRAW' + | 'ORDER' + | 'FUNDING_FEE' + | 'WITHDRAW_REJECT' + | 'ADJUSTMENT' + | 'INSURANCE_CLEAR' + | 'ADMIN_DEPOSIT' + | 'ADMIN_WITHDRAW' + | 'MARGIN_TRANSFER' + | 'MARGIN_TYPE_CHANGE' + | 'ASSET_TRANSFER' + | 'OPTIONS_PREMIUM_FEE' + | 'OPTIONS_SETTLE_PROFIT' + | 'AUTO_EXCHANGE'; ⋮---- -export interface WsMessageFuturesUserDataContractInfoRaw extends WsSharedBase { - e: 'contractInfo'; // Event Type - E: number; // Event Time - s: string; // Symbol - ps: string; // Pair - ct: string; // Contract type - dt: number; // Delivery date time - ot: number; // onboard date time - cs: string; // Contract status - bks: { - bs: number; // Notional bracket - bnf: number; // Floor notional of this bracket - bnc: number; // Cap notional of this bracket - mmr: number; // Maintenance ratio for this bracket - cf: number; // Auxiliary number for quick calculation - mi: number; // Min leverage for this bracket - ma: number; // Max leverage for this bracket - }[]; - st?: FuturesMarketSymbolType; +export interface WsMessageFuturesUserDataListenKeyExpiredRaw + extends WsSharedBase { + e: 'listenKeyExpired'; + E: number; } ⋮---- -e: 'contractInfo'; // Event Type -E: number; // Event Time -s: string; // Symbol -ps: string; // Pair -ct: string; // Contract type -dt: number; // Delivery date time -ot: number; // onboard date time -cs: string; // Contract status +export interface WsEventStreamTerminatedRaw extends WsSharedBase { + e: 'eventStreamTerminated'; + E: number; +} ⋮---- -bs: number; // Notional bracket -bnf: number; // Floor notional of this bracket -bnc: number; // Cap notional of this bracket -mmr: number; // Maintenance ratio for this bracket -cf: number; // Auxiliary number for quick calculation -mi: number; // Min leverage for this bracket -ma: number; // Max leverage for this bracket +export interface WsMessageFuturesMarginCalledPositionRaw { + s: string; + ps: PositionSide; + pa: numberInString; + mt: Uppercase; + iw: numberInString; + mp: numberInString; + up: numberInString; + mm: numberInString; +} ⋮---- -export type WsRawSpotUserDataEventRaw = - | WsMessageSpotUserDataExecutionReportEventRaw - | WsMessageSpotOutboundAccountPositionRaw - | WsMessageSpotBalanceUpdateRaw - | WsMessageSpotUserDataListStatusEventRaw; +export interface WsMessageFuturesUserDataMarginCallRaw extends WsSharedBase { + e: 'MARGIN_CALL'; + E: number; + cw: numberInString; + p: WsMessageFuturesMarginCalledPositionRaw[]; +} ⋮---- -export type WsMessageFuturesUserDataEventRaw = - | WsMessageFuturesUserDataAccountUpdateRaw - | WsMessageFuturesUserDataListenKeyExpiredRaw - | WsMessageFuturesUserDataMarginCallRaw - | WsMessageFuturesUserDataOrderTradeUpdateEventRaw - | WsMessageFuturesUserDataAlgoUpdateRaw - | WsMessageFuturesUserDataAccountConfigUpdateEventRaw - | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw - | WsMessageFuturesUserDataTradeLiteEventRaw - | WsMessageFuturesUserDataStrategyUpdateRaw - | WsMessageFuturesUserDataGridUpdateRaw - | WsMessageFuturesUserDataContractInfoRaw; +export interface WsMessageFuturesAccountUpdatePositionRaw { + s: string; + pa: numberInString; + ep: numberInString; + cr: numberInString; + up: numberInString; + mt: 'cross' | 'isolated'; + iw: numberInString; + ps: PositionSide; +} ⋮---- -export type WsUserDataEventsRaw = - | WsRawSpotUserDataEventRaw - | WsMessageFuturesUserDataEventRaw - | WsMessagePortfolioMarginProAccountUpdateRaw; +export interface WsMessageFuturesAccountUpdateBalanceRaw { + a: string; + wb: numberInString; + cw: numberInString; + bc: numberInString; +} ⋮---- -export type WsRawMessage = - | WsEventStreamTerminatedRaw - | WsMessageWsapiServerShutdownRaw - | WsUserDataEventsRaw - | WsMessageKlineRaw - | WsMessageAggTradeRaw - | WsMessageTradeRaw - | WsMessageBlockTradeRaw - | WsMessage24hrMiniTickerRaw - | WsMessage24hrMiniTickerRaw[] - | WsMessage24hrTickerRaw - | WsMessage24hrTickerRaw[] - | WsMessageRollingWindowTickerRaw[] - | WsMessageBookTickerEventRaw - | WsMessagePartialBookDepthEventRaw - | WsMessageDiffBookDepthEventRaw - | WsMessageForceOrderRaw - | WsMessageIndexPriceUpdateEventRaw; - -================ -File: docs/BINANCE_SDK_QUICKSTART_GUIDE.md -================ - -# Binance SDK Quickstart Guide - - -> [!TIP] -> This guide can be read in tutorial format on the Siebly Website: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) - - -This guide walks through key pieces of a Binance REST API, WebSocket & WebSocket API integration using [`binance`](https://www.npmjs.com/package/binance), the Binance JavaScript and TypeScript SDK by Siebly.io. It also covers HTTP, HTTPS, and SOCKS proxy configuration for REST API calls, streams, and user-data helpers. - -The SDK handles request building and connectivity for you, including request signing, WebSocket management, healthchecks, heartbeats, product-specific user data startup, listen-key refreshes where Binance still uses them, resubscribe behavior, and WebSocket API response mapping so your code can stay focused on the workflow you are automating. This guide will walk you through installation and client selection, then moves through public calls, private auth, REST API calls, streams, user data, and the WebSocket API. - -**Key links** - -- Binance JavaScript SDK by Siebly: [`binance`](https://www.npmjs.com/package/binance) -- GitHub Repository: [`sieblyio/binance`](https://github.com/sieblyio/binance) -- SDK function-endpoint map: [Binance JavaScript Endpoint Reference](./endpointFunctionList.md) -- REST API examples: [Binance SDK REST API examples](../examples/Rest/Spot/rest-spot-public.ts) -- WebSocket examples: [Binance SDK WebSocket examples](../examples/WebSockets/Public/ws-public.ts) -- More SDKs: [Siebly.io](https://siebly.io) - ---- - - -## Why use the SDK - -A stable Binance integration is more than a handful of HTTP requests. Binance splits behavior across product groups, transports, key types, and environments: - -- Spot, Margin, Wallet, Convert, Earn, and Sub-Account APIs live behind the main REST API client, but not all of them share the same endpoint prefix or permission model. -- Some of these product groups expect API calls to reach different subdomains. -- USD-M Futures and COIN-M Futures have separate REST API clients, symbols, endpoint prefixes, and WebSocket endpoints. -- Both have their own subdomains as well. -- Portfolio Margin uses a dedicated REST API client and its own account model. -- Public streams, private user data streams, and WebSocket API commands are different flows. -- Private REST API and WebSocket API requests must be signed. -- User data streams can involve listen keys, WebSocket API subscriptions, token refreshes, and reconnect handling. - -Most of that work is handled for you, while the grouping & naming stays close to Binance's API naming. The SDK gives you dedicated REST API clients for the major product groups, `WebsocketClient` for streaming, `WebsocketAPIClient` for awaitable WebSocket API requests. It also includes TypeScript definitions, ESM/CJS support, proxy support, and optional response beautification. - ---- - - -## Install and API keys - -If you do not have Node.js installed yet, install it first. The SDK is published to both [GitHub](https://github.com/sieblyio/binance) and [npm](https://www.npmjs.com/package/binance), and can therefore be installed with your favourite Node.js compatible package manager. - -Install the SDK with npm: - -```bash -npm install binance -``` - -Or use another npm-compatible package manager: - -```bash -pnpm install binance -yarn add binance -``` - -Create API keys from the relevant Binance page: - -- Binance live API keys: [Binance API Management](https://www.binance.com/en/my/settings/api-management) -- Binance Spot testnet: [Spot Test Network](https://testnet.binance.vision/) -- Binance Futures testnet: [Futures Testnet](https://testnet.binancefuture.com/) -- Binance demo trading: [Binance Demo Trading](https://demo.binance.com/) - -> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. -> Always require strict IP whitelisting for any API keys that you create. - -The main auth and environment rules are: - -- Public market data does not require API keys. -- Private REST APIs require `api_key` and `api_secret`. -- Live, testnet, and demo trading credentials are separate, as they are separate environments. -- API permissions must match the product and action your code is using. -- HMAC keys are the common API key + secret flow. These are the "system generated" API keys, selected by default when creating new API keys for Binance. -- RSA and Ed25519 keys use self-generated private keys. -- Ed25519 is recommended for latency-sensitive integrations with the WebSocket API, as this enables session-based WebSocket API authentication, instead of having to authenticate every request. - -All supported key types use the same SDK constructor shape. The SDK will automatically detect your key type and adjust request building and signing automatically: - -```typescript -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -For HMAC, `api_secret` is your Binance API secret. For RSA or Ed25519, `api_secret` is your PEM private key. - -Typical environment variables: - -```bash -export BINANCE_API_KEY='your-api-key' -export BINANCE_API_SECRET='your-api-secret-or-private-key' -``` - -If you are only testing public endpoints, you do not need any keys at all. - ---- - - -## Products and clients - -Binance is not one single API. The SDK splits API clients around Binance's product groups: - -| Product group | API client | Common usage | -| -------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------- | -| REST API: Spot, Margin, Wallet, Convert, Earn, Sub-accounts, Broker, Alpha | `MainClient` | Spot trading, account data, wallet flows, margin trading, transfers, savings/earn, sub-account management | -| REST API: USD-M Futures | `USDMClient` | USDT/USDC margined futures market data, account data, positions, orders | -| REST API: COIN-M Futures | `CoinMClient` | Coin-margined futures market data, account data, positions, orders | -| REST API: Portfolio Margin | `PortfolioClient` | Portfolio Margin account, UM/CM/margin orders, balances, positions | -| WebSocket streams | `WebsocketClient` | Public market data streams and private user data streams | -| WebSocket API | `WebsocketAPIClient` | REST API-like Spot and Futures commands over persistent WebSocket API connections | - -As a rule of thumb: - -- Use `MainClient` when the Binance docs path starts with `api/` or `sapi/`, including Spot and many account/wallet APIs. -- Use `USDMClient` when the Binance docs path starts with `fapi/`. -- Use `CoinMClient` when the Binance docs path starts with `dapi/`. -- Use `PortfolioClient` when the Binance docs path starts with `papi/`. -- Use `WebsocketClient` when you want to subscribe to streams and receive events. -- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await responses like REST API calls. - -For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). If any endpoints or properties seem to be missing, please open an issue on GitHub and we'll look into it. Targeted PRs are also welcome. - - -### REST API, streams, listen keys, and WebSocket API - -Binance uses several related but different integration patterns. It helps to keep them separate: - -| Flow | SDK surface | Best for | What the SDK handles | -| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| REST API | `MainClient`, `USDMClient`, `CoinMClient`, `PortfolioClient` | Request/response calls, broad API coverage, occasional reads/writes, fallback reconciliation | Base URLs, request signing, timestamps, response parsing, errors | -| Public WebSocket streams | `WebsocketClient.subscribe(...)` | Live market data such as trades, klines, tickers, order book updates | Connection routing, subscribe requests, heartbeats, reconnects, resubscribe | -| Listen-key user data streams | `WebsocketClient.subscribeUsdFuturesUserDataStream()`, `subscribeCoinFuturesUserDataStream()`, portfolio helpers | Private account events where Binance still uses listen keys, especially Futures and Portfolio Margin streams | Listen-key creation, keepalive, refresh, reconnect, stream teardown | -| WebSocket API user data | `WebsocketAPIClient.subscribeUserDataStream(...)` | Spot user data and some newer private stream flows without the old Spot listen-key workflow | WebSocket API auth, subscription command, reconnect/resubscribe behavior | -| WebSocket API commands | `WebsocketAPIClient` methods or `WebsocketClient.sendWSAPIRequest(...)` | Lower-latency request/response commands over an already-open WebSocket, such as order tests, order placement, cancellation, status, account reads | WebSocket connection persistence, auth, request IDs, promise resolution, response/error correlation | - -The WebSocket API uses WebSocket transport for request/response commands such as order tests, order placement, cancellation, status, and account reads. Since much of this surface is a lower-latency alternative to REST, we've introduced the promise-driven `WebsocketAPIClient`. It lets you call a function, send a command over WS, and await the matched response without managing asynchronous WebSocket messaging or connection lifecycle details yourself. - -```typescript -const result = await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), -}); -``` - -Use the REST API when you want maximum endpoint coverage, simple one-off calls, or reconciliation after reconnects. Use the WebSocket API when you want persistent connectivity, lower request overhead, WebSocket API-only features, or a promise-driven command path that can share the same event-driven architecture as your streams. With Ed25519 keys, authentication can happen once per WebSocket API connection, which can improve latency in mid-to-high frequency systems. Removing repeated authentication work from every request can save time cumulatively. - ---- - - -## Start building: first calls - -If you only want the fastest path to a working integration, start here. - -### 1. First Spot REST API request - - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient(); - -async function main() { - const serverTime = await client.getServerTime(); - const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); - const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); - const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); - const candles = await client.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 5, - }); - - console.log({ - serverTime, - symbol: exchangeInfo.symbols?.[0]?.symbol, - ticker, - orderBook, - candles, - }); -} - -main().catch(console.error); -``` - -That confirms public Spot REST API access is wired correctly. - -See also: [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) - -### 2. First public Spot WebSocket stream - - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ - beautify: true, -}); - -ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); -ws.on('message', (data) => console.log('raw message', JSON.stringify(data))); -ws.on('formattedMessage', (data) => console.log('formatted', data)); -ws.on('response', (data) => console.log('response', JSON.stringify(data))); -ws.on('reconnecting', (data) => console.log('reconnecting', data?.wsKey)); -ws.on('reconnected', (data) => console.log('reconnected', data?.wsKey)); -ws.on('exception', console.error); - -ws.subscribe(['btcusdt@trade', 'btcusdt@bookTicker'], WS_KEY_MAP.main); -``` - -That gives you a live public Spot stream without any API keys. - -See also: [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) - -### 3. First private Spot user data stream - -For Spot user data streams, prefer the WebSocket API user data flow. It avoids the older Spot listen-key flow and keeps the stream on a managed WebSocket API connection. - - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -wsApi.getWSClient().on('message', (data) => { - console.log('on message event: ', data.wsKey); -}); - -wsApi.getWSClient().on('open', (data) => { - console.log('ws api open: ', data.wsKey); -}); - -wsApi.getWSClient().on('formattedUserDataMessage', (data) => { - console.log('on formattedUserDataMessage: ', data); -}); - -wsApi.getWSClient().on('exception', console.error); - -async function main() { - await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); -} - -main().catch(console.error); -``` - -The SDK handles authentication and resubscribe behavior for the WebSocket API connection. With Ed25519 keys it can authenticate the WebSocket API session once. With HMAC or RSA keys it signs private WebSocket API commands individually, although that primarily matters in the context of sending regular commands (such as order submissions) via WebSocket API. - -See also: [Spot user data stream over WebSocket API](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) - -### 4. First Spot order over REST API - - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -async function placeOrder() { - const orderRequest = { - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - newOrderRespType: 'FULL', - } as const; - - // Validate the request without sending it to the matching engine. - await client.testNewOrder(orderRequest); - - // Remove this comment when you are ready to place a real order. - // const result = await client.submitNewOrder(orderRequest); - // console.log(result); -} - -placeOrder().catch(console.error); -``` - -Use `testNewOrder()` when you want to validate the request shape and signature without placing a live Spot order. Use `submitNewOrder()` only when you are ready to send the order. - -See also: [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) - -### 5. First USD-M Futures order - -For strategy testing, `demoTrading: true` is usually more realistic than testnet because demo trading uses live market data with simulated trading. - - -```typescript -import { USDMClient } from 'binance'; - -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); - -async function placeFuturesOrder() { - const account = await client.getAccountInformation(); - console.log('demo futures account can trade:', account.canTrade); - - const result = await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: 0.001, - }); - - console.log(result); -} - -placeFuturesOrder().catch(console.error); -``` - -See also: [USD-M Futures demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) - -### 6. First WebSocket API request - -The WebSocket API lets you send requests over a persistent WebSocket connection and await responses, similar to REST API calls. This is useful for lower-latency workflows and for WebSocket API-only features. - - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -async function main() { - const time = await wsApi.getSpotServerTime(); - - const orderTest = await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), - }); - - console.log({ time, orderTest }); -} - -main() - .catch(console.error) - .finally(() => wsApi.disconnectAll()); -``` - -See also: [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) - ---- - - -## Spot, Margin, and Wallet REST API - -Most Binance integrations start with `MainClient`. It covers Spot trading and many account APIs under Binance's main REST API families. - -### Create a public `MainClient` - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient(); -``` - -Public calls do not require keys. - -### Create a private `MainClient` - -If you plan on making private API calls, include API keys when creating the client: - -```typescript -import { MainClient } from 'binance'; - -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautifyResponses: true, -}); -``` - -Private REST API methods are signed automatically. You do not need to manually add timestamps, signatures, or `X-MBX-APIKEY` headers. - -### Common public Spot market data calls - -```typescript -const serverTime = await client.getServerTime(); -const ping = await client.testConnectivity(); -const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); -const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); -const recentTrades = await client.getRecentTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const aggregateTrades = await client.getAggregateTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const candles = await client.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 10, -}); -const averagePrice = await client.getAvgPrice({ symbol: 'BTCUSDT' }); -const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -const bookTicker = await client.getSymbolOrderBookTicker({ - symbol: 'BTCUSDT', -}); -``` - -### Common private Spot account and order calls - -```typescript -const account = await client.getAccountInformation(); -const balances = await client.getBalances(); -const accountInfo = await client.getAccountInfo(); -const openOrders = await client.getOpenOrders({ symbol: 'BTCUSDT' }); -const allOrders = await client.getAllOrders({ symbol: 'BTCUSDT', limit: 10 }); -const myTrades = await client.getAccountTradeList({ - symbol: 'BTCUSDT', - limit: 10, -}); -const tradeFee = await client.getTradeFee({ symbol: 'BTCUSDT' }); -const apiPermissions = await client.getApiKeyPermissions(); -``` - -See also: - -- [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) -- [Spot exchange info example](../examples/Rest/Spot/rest-spot-exchange-info.ts) -- [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) -- [Spot private miscellaneous account example](../examples/Rest/Spot/rest-spot-private-misc.ts) - -### Spot order examples - -Market order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'MARKET', - quantity: 0.001, - newOrderRespType: 'FULL', -}); -``` - -Limit order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Limit maker order: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT_MAKER', - quantity: 0.001, - price: 10000, -}); -``` - -Test an order without sending it: - -```typescript -await client.testNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Cancel an order: - -```typescript -await client.cancelOrder({ - symbol: 'BTCUSDT', - orderId: 123456789, -}); -``` - -**Custom client order IDs** - -You do not always need to set a custom client order ID. Most of the time, the cleanest option is to send the order without `newClientOrderId` or the equivalent custom ID field for that endpoint, and let the SDK handle the request normally: - -```typescript -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', -}); -``` - -If your system needs to know the client order ID before the order is sent, but the ID does not need to carry any meaning, ask the REST API client to generate one: - -```typescript -const newClientOrderId = client.generateNewOrderId(); - -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - newClientOrderId, -}); -``` - -`generateNewOrderId()` is available on every REST API client, including `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. The client already knows its product group, so the generated ID uses the right Binance-compatible prefix. - -If you want to include a small piece of your own context in the client order ID, such as a take-profit marker or strategy step, use the product prefix from the client and append your suffix: - -```typescript -const prefix = client.getOrderIdPrefix(); -const suffix = `tp1_${Date.now()}`; -const newClientOrderId = `${prefix}${suffix}`; -const validBinanceClientOrderId = /^[.A-Z:/a-z0-9_-]{1,32}$/; - -if (!validBinanceClientOrderId.test(newClientOrderId)) { - throw new Error(`Invalid Binance client order ID: ${newClientOrderId}`); -} - -await client.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - newClientOrderId, -}); -``` - -The prefix returned by `getOrderIdPrefix()` is 10 characters long. For endpoints with Binance's common 32-character client order ID limit, that leaves 22 characters for your own suffix. Keep the suffix short and use only characters Binance allows for that field. - -If you need to track richer metadata than will comfortably fit in the client order ID, do not try to squeeze it into these custom order ID fields. Instead, generate an ID with `client.generateNewOrderId()` before placing the order, use that value as the key for your own metadata, and store the metadata locally or in an external store such as Redis. Later, when order updates arrive through REST API polling or user data events, you can look up the richer context using the seen Binance client ID value like a primary key, while keeping the exchange-facing ID short and valid. - -Regular Spot, Futures, and Portfolio orders usually use `newClientOrderId`; newer Futures algo or conditional flows may use `clientAlgoId` instead. Treat both fields, and any similar Binance custom order ID field, as the same kind of SDK-prefixed client ID. The same rule applies: omit it unless you need it, use `generateNewOrderId()` when any unique ID is fine, and use `getOrderIdPrefix()` when building your own value. Do not bypass the SDK prefix, length, or character checks just because the endpoint uses a different field name. - -### Margin REST API examples - -Margin APIs also live on `MainClient`. - -```typescript -const marginAssets = await client.getAllMarginAssets(); -const marginPairs = await client.getAllCrossMarginPairs(); -const priceIndex = await client.queryMarginPriceIndex({ symbol: 'BTCUSDT' }); - -const crossMarginAccount = await client.queryCrossMarginAccountDetails(); -const isolatedMarginAccount = await client.getIsolatedMarginAccountInfo({ - symbols: 'BTCUSDT', -}); -const openMarginOrders = await client.queryMarginAccountOpenOrders({ - symbol: 'BTCUSDT', -}); -``` - -Margin order: - -```typescript -await client.marginAccountNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - isIsolated: 'FALSE', - sideEffectType: 'NO_SIDE_EFFECT', -}); -``` - -Borrow or repay: - -```typescript -await client.submitMarginAccountBorrowRepay({ - asset: 'USDT', - symbol: 'BTCUSDT', - amount: 25, - type: 'BORROW', - isIsolated: 'FALSE', -}); -``` - -Margin permissions, collateral, interest, and liquidation behavior are account-specific. Keep margin trading code separate from ordinary Spot trading code even though both use `MainClient`. - -### Wallet and transfer examples - -Wallet and transfer APIs also live on `MainClient`. - -```typescript -const balances = await client.getBalances(); -const depositAddress = await client.getDepositAddress({ - coin: 'USDT', - network: 'ETH', -}); -const depositHistory = await client.getDepositHistory({ coin: 'USDT' }); -const withdrawHistory = await client.getWithdrawHistory({ coin: 'USDT' }); - -const transferHistory = await client.getUniversalTransferHistory({ - type: 'MAIN_UMFUTURE', -}); -``` - -Withdrawal calls are intentionally not shown as a quickstart. Use withdrawal permissions only when your system truly needs them, and isolate those keys from trading keys. - ---- - - -## Futures REST API - -Binance Futures are split into USD-M and COIN-M product groups. Use the dedicated client for the product you are integrating. - -### Create public Futures clients - -```typescript -import { CoinMClient, USDMClient } from 'binance'; - -const usdm = new USDMClient(); -const coinm = new CoinMClient(); -``` - -Public futures market data does not require keys. - -### Create private Futures clients - -```typescript -import { CoinMClient, USDMClient } from 'binance'; - -const usdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const coinm = new CoinMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -Use `demoTrading: true` for Binance demo trading or `testnet: true` for testnet where supported: - -```typescript -const demoUsdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); - -const testnetUsdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - testnet: true, -}); -``` - -Do not enable both `demoTrading` and `testnet` on the same client. - -### Common public USD-M Futures market data calls - -```typescript -const serverTime = await usdm.getServerTime(); -const exchangeInfo = await usdm.getExchangeInfo(); -const orderBook = await usdm.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); -const recentTrades = await usdm.getRecentTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const candles = await usdm.getKlines({ - symbol: 'BTCUSDT', - interval: '1m', - limit: 10, -}); -const markPrice = await usdm.getMarkPrice({ symbol: 'BTCUSDT' }); -const fundingHistory = await usdm.getFundingRateHistory({ - symbol: 'BTCUSDT', - limit: 10, -}); -const ticker = await usdm.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -``` - -### Common public COIN-M Futures market data calls - -```typescript -const serverTime = await coinm.getServerTime(); -const exchangeInfo = await coinm.getExchangeInfo(); -const orderBook = await coinm.getOrderBook({ - symbol: 'BTCUSD_PERP', - limit: 10, -}); -const candles = await coinm.getKlines({ - symbol: 'BTCUSD_PERP', - interval: '1m', - limit: 10, -}); -const markPrice = await coinm.getMarkPrice({ symbol: 'BTCUSD_PERP' }); -const ticker = await coinm.getSymbolPriceTicker({ symbol: 'BTCUSD_PERP' }); -``` - -See also: - -- [USD-M public REST API example](../examples/Rest/Futures/rest-usdm-public.ts) -- [USD-M demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) -- [USD-M testnet example](../examples/Rest/Futures/rest-usdm-testnet.ts) - -### Common private Futures account calls - -```typescript -const balance = await usdm.getBalance(); -const account = await usdm.getAccountInformation(); -const positions = await usdm.getPositions({ symbol: 'BTCUSDT' }); -const openOrders = await usdm.getAllOpenOrders({ symbol: 'BTCUSDT' }); -const tradeHistory = await usdm.getAccountTrades({ - symbol: 'BTCUSDT', - limit: 10, -}); -const income = await usdm.getIncomeHistory({ - symbol: 'BTCUSDT', - limit: 10, -}); -``` - -### Futures order examples - -Market order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: 0.001, -}); -``` - -Limit order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', -}); -``` - -Reduce-only limit order: - -```typescript -await usdm.submitNewOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - reduceOnly: 'true', -}); -``` - -Batch order management: - -```typescript -await usdm.submitMultipleOrders([ - { - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: 0.001, - price: 10000, - timeInForce: 'GTC', - }, - { - symbol: 'BTCUSDT', - side: 'SELL', - type: 'LIMIT', - quantity: 0.001, - price: 13000, - timeInForce: 'GTC', - }, -]); -``` - -See also: - -- [USD-M order example](../examples/Rest/Futures/rest-usdm-order.ts) -- [USD-M stop-loss order example](../examples/Rest/Futures/rest-usdm-order-sl.ts) -- [USD-M bracket order example](../examples/Rest/Futures/rest-future-bracket-order.ts) - ---- - - -## Portfolio Margin REST API - -Portfolio Margin has its own account model and a dedicated `PortfolioClient`. - -### Create a Portfolio Margin client - -```typescript -import { PortfolioClient } from 'binance'; - -const portfolio = new PortfolioClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); -``` - -### Common Portfolio Margin calls - -```typescript -const ping = await portfolio.testConnectivity(); -const serverTime = await portfolio.getServerTime(); -const balance = await portfolio.getBalance(); -const account = await portfolio.getAccountInfo(); -const umPositions = await portfolio.getUMPosition({ symbol: 'BTCUSDT' }); -const cmPositions = await portfolio.getCMPosition({ pair: 'BTCUSD' }); -const umOpenOrders = await portfolio.getAllUMOpenOrders({ - symbol: 'BTCUSDT', -}); -const marginOpenOrders = await portfolio.getMarginOpenOrders({ - symbol: 'BTCUSDT', -}); -``` - -Portfolio Margin order examples: - -```typescript -await portfolio.submitNewUMOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', -}); - -await portfolio.submitNewCMOrder({ - symbol: 'BTCUSD_PERP', - side: 'SELL', - type: 'MARKET', - quantity: '1', -}); - -await portfolio.submitNewMarginOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'MARKET', - quantity: '0.001', - sideEffectType: 'NO_SIDE_EFFECT', -}); -``` - -See also: - -- [Portfolio Margin public REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-public.ts) -- [Portfolio Margin private REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-private.ts) - ---- - - -## WebSocket Streams - -Use `WebsocketClient` when you want event-driven updates instead of polling the REST API. It is the shared client for public market streams and for the product areas where Binance still uses listen-key style user data streams. - -The workflow is simple: create a client, add event handlers, provide API keys if you need private user data, and subscribe to the streams you want. The SDK opens the correct Binance endpoint, applies proxy settings if configured, fetches and refreshes listen keys where required, monitors heartbeats, reconnects stale sockets, and resubscribes cached topics after reconnect. - -### Common `WebsocketClient` events - -| Event | Meaning | -| -------------------------- | --------------------------------------------------------------- | -| `open` | Connection established | -| `message` | Raw streaming data received | -| `formattedMessage` | Beautified public stream data when `beautify: true` | -| `formattedUserDataMessage` | Beautified private user data stream event when `beautify: true` | -| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | -| `reconnecting` | Connection dropped and retrying | -| `reconnected` | Connection restored and subscriptions resynced | -| `close` | Socket closed | -| `authenticated` | WebSocket API session authentication succeeded | -| `exception` | Errors and unexpected conditions | - -### Understanding `WS_KEY_MAP` - -[`WS_KEY_MAP`](/reference/glossary#ws-key) tells the SDK which Binance WebSocket endpoint family to use. This matters because Spot, USD-M Futures, COIN-M Futures, Options, Portfolio Margin, and WebSocket API traffic do not all live on the same endpoint. - -Common `WS_KEY_MAP` entries: - -| Key | Use | -| ---------------------------- | ----------------------------------------------------------------------- | -| `main` | Spot, margin, and isolated margin market data streams | -| `main2` | Alternate Spot stream port | -| `main3` | Spot market-data-only stream endpoint | -| `mainWSAPI` | Spot and margin WebSocket API | -| `mainWSAPITestnet` | Spot WebSocket API testnet | -| `marginUserData` | Margin user data over WebSocket API listen-token flow | -| `marginRiskUserData` | Cross-margin risk data stream | -| `usdmPublic` | USD-M high-frequency public market data, such as book and depth streams | -| `usdmMarket` | USD-M regular market data, such as trades, klines, tickers, mark price | -| `usdmPrivate` | USD-M private user data stream endpoint | -| `usdmWSAPI` | USD-M Futures WebSocket API | -| `coinm` | COIN-M market data and user data stream endpoint | -| `coinmWSAPI` | COIN-M Futures WebSocket API | -| `eoptions` | European Options WebSocket streams | -| `portfolioMarginUserData` | Portfolio Margin user data stream | -| `portfolioMarginProUserData` | Portfolio Margin Pro user data stream | -| `alpha` | Alpha market data streams | - -These keys act like connection IDs. The SDK uses them to track connection state, cached subscriptions, reconnect behavior, and endpoint-specific routing. - -### Public Spot WebSocket topics - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('formattedMessage', (data) => console.log(data)); -ws.on('exception', console.error); - -ws.subscribe( - [ - 'btcusdt@trade', - 'btcusdt@aggTrade', - 'btcusdt@kline_1m', - 'btcusdt@bookTicker', - 'btcusdt@depth10@100ms', - ], - WS_KEY_MAP.main, -); -``` - -See also: - -- [General public WebSocket example](../examples/WebSockets/Public/ws-public.ts) -- [Spot order book WebSocket example](../examples/WebSockets/Public/ws-public-spot-orderbook.ts) -- [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) - -### Public USD-M Futures WebSocket topics - -USD-M Futures WebSockets have dedicated endpoint families for high-frequency public data and regular market data. - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('formattedMessage', (data) => console.log(data)); -ws.on('exception', console.error); - -// High-frequency public data: book ticker and order book depth. -ws.subscribe( - ['btcusdt@bookTicker', 'btcusdt@depth10@100ms', 'btcusdt@depth@100ms'], - WS_KEY_MAP.usdmPublic, -); - -// Regular market data: trades, mark price, klines, mini tickers, liquidations. -ws.subscribe(['btcusdt@aggTrade', 'btcusdt@markPrice', 'btcusdt@kline_1m'], WS_KEY_MAP.usdmMarket); -``` - -See also: - -- [USD-M public WebSocket example](https://siebly.io/examples/Binance/WebSockets/Public/ws-public) -- [USD-M funding stream example](../examples/WebSockets/Public/ws-public-usdm-funding.ts) - -### Public COIN-M Futures WebSocket topics - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ beautify: true }); - -ws.on('message', (data) => console.log(JSON.stringify(data))); -ws.on('exception', console.error); - -ws.subscribe( - ['btcusd_perp@aggTrade', 'btcusd_perp@markPrice', 'btcusd_perp@kline_1m'], - WS_KEY_MAP.coinm, -); -``` - -COIN-M symbols and stream names are not the same as Spot or USD-M symbols. Treat symbols as product-specific strings. - ---- - - -## User Data Streams - -User data streams are how Binance pushes private account events: order updates, execution updates, balance changes, position changes, margin events, and listen-key or subscription expiry events. - -Binance uses two patterns for these streams: WebSocket API user data subscriptions and listen-key user data streams. The SDK supports both; the product group determines which path you should use. - -For either pattern, listen for the WebSocket lifecycle events as well as account events. The event names are `reconnecting` and `reconnected`. `reconnecting` fires when the SDK starts replacing a dropped connection; `reconnected` fires after the replacement connection is open. Both include the [`wsKey`](/reference/glossary#ws-key), which tells you which connection was affected. For user data streams, `reconnected` is the right place to reconcile private state through the REST API in case account events were missed while the socket was down. - -With `WebsocketAPIClient`, attach those handlers to `wsApi.getWSClient()`. With `WebsocketClient`, attach them directly to the client. - -### Preferred Spot user data stream with `WebsocketAPIClient` - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -const wsClient = wsApi.getWSClient(); - -// raw websocket event, unformatted -wsClient.on('message', (data) => { - console.log('on message event: ', data.wsKey); -}); - -// formatted websocket event -wsClient.on('formattedMessage', (data) => { - console.log('on formattedMessage: ', data); -}); - -// reconnection has started -wsClient.on('reconnecting', ({ wsKey }) => { - console.log('spot user data reconnecting', wsKey); -}); - -// reconnection has completed -wsClient.on('reconnected', ({ wsKey }) => { - console.log('spot user data reconnected', wsKey); - // Fetch account state, open orders, or recent fills here if needed. -}); - -wsClient.on('exception', console.error); - -await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); -``` - -Binance announced deprecation of the old listenKey workflow for Spot and Margin user data streams on April 7, 2025. From February 20, 2026 at 07:00 UTC, the old Spot `POST /api/v3/userDataStream` path returns `410 Gone`; use the WebSocket API user data stream instead. At the time of writing, Spot and Margin are the affected user data stream families. Futures and Portfolio Margin streams still use their existing listenKey-backed workflows. For the migration timeline and JavaScript fix, see [Binance User Data Stream 410 Gone: Fix Spot listenKey in JavaScript](/blog/binance-user-data-stream-410-gone-listenkey-javascript). - -### Margin user data stream with `WebsocketAPIClient` - -```typescript -import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -const wsClient = wsApi.getWSClient(); - -// raw websocket event, unformatted -wsClient.on('message', (data) => { - console.log('on message event: ', data.wsKey); -}); - -// formatted websocket event -wsClient.on('formattedMessage', (data) => { - console.log('on formattedMessage: ', data); -}); - -// reconnection has started -wsClient.on('reconnecting', ({ wsKey }) => { - console.log('spot user data reconnecting', wsKey); -}); - -// reconnection has completed -wsClient.on('reconnected', ({ wsKey }) => { - console.log('spot user data reconnected', wsKey); - // Fetch account state, open orders, or recent fills here if needed. -}); - -await wsApi.subscribeUserDataStream(WS_KEY_MAP.marginUserData); -``` - -For margin, the SDK handles the listen-token workflow used by Binance's margin WebSocket API user data endpoint. - -### Futures user data streams with `WebsocketClient` - -Futures user data streams are conveniently available through `WebsocketClient` in the [Binance JavaScript SDK](https://siebly.io/sdk/binance/javascript). Both USD-M and COIN-M Futures user data streams on Binance follow a listenKey mechanic. The SDK automates the life cycle and maintenance of this listenKey for you. Request the subscription and handle incoming events, as shown in the following example: - -```typescript -import { WebsocketClient } from 'binance'; - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -ws.on('formattedUserDataMessage', (data) => { - console.log('futures account event', data); -}); - -ws.on('reconnecting', ({ wsKey }) => { - console.log('futures user data reconnecting', wsKey); -}); - -ws.on('reconnected', ({ wsKey }) => { - console.log('futures user data reconnected', wsKey); - // Fetch positions, balances, open orders, or fills here if needed. -}); - -ws.on('exception', console.error); - -await ws.subscribeUsdFuturesUserDataStream(); -// await ws.subscribeCoinFuturesUserDataStream(); -``` - -The SDK will fetch the listen key, keep it alive, refresh it when needed, reconnect after network issues, and resubscribe where possible. - -### Portfolio Margin user data stream - -```typescript -import { WebsocketClient, WS_KEY_MAP } from 'binance'; - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, -}); - -ws.on('formattedUserDataMessage', (data) => { - console.log('portfolio margin event', data); -}); - -ws.on('reconnecting', ({ wsKey }) => { - console.log('portfolio margin user data reconnecting', wsKey); -}); - -ws.on('reconnected', ({ wsKey }) => { - console.log('portfolio margin user data reconnected', wsKey); -}); - -ws.on('exception', console.error); - -await ws.subscribePortfolioMarginUserDataStream(WS_KEY_MAP.portfolioMarginUserData); -``` - -See also: - -- [User data connection safety example]() -- [Listen-key user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts>) -- [WebSocket API user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) - ---- - - -## WebSocket API - -Binance's WebSocket API is a request/response API over a persistent WebSocket connection. It is useful when you want lower request overhead than REST API calls, or when a Binance feature is exposed through the WebSocket API flow. - -`WebsocketAPIClient` wraps that in a promise-driven interface: call a method, await a promise, receive the response, and let the SDK manage the underlying WebSocket connection. - -### Authentication - -The SDK supports HMAC, RSA, and Ed25519 keys: - -- HMAC: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. -- RSA: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. -- Ed25519: recommended for WebSocket API because the SDK can authenticate the WebSocket API session once and then send private commands without signing every command. - -If your `api_secret` contains a PEM private key, the SDK automatically detects whether it should use RSA or Ed25519 signing. - -See also: - -- [Ed25519 auth example](../examples/auth/rest-private-ed25519.md) -- [RSA auth example](../examples/auth/rest-private-rsa.md) - -### Spot examples - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const exchangeInfo = await wsApi.getSpotExchangeInfo({ - symbol: 'BTCUSDT', -}); - -const orderBook = await wsApi.getSpotOrderBook({ - symbol: 'BTCUSDT', - limit: 10, -}); - -const account = await wsApi.getSpotAccountInformation({ - timestamp: Date.now(), -}); - -await wsApi.testSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', - timestamp: Date.now(), -}); -``` - -Submit a Spot order over the WebSocket API: - -```typescript -await wsApi.submitNewSpotOrder({ - symbol: 'BTCUSDT', - side: 'BUY', - type: 'LIMIT', - quantity: '0.001', - price: '10000', - timeInForce: 'GTC', -}); -``` - -### Futures examples - -```typescript -import { WebsocketAPIClient } from 'binance'; - -const wsApi = new WebsocketAPIClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, -}); - -const book = await wsApi.getFuturesOrderBook({ - symbol: 'BTCUSDT', - limit: 10, -}); - -const balance = await wsApi.getFuturesAccountBalance('usdm', { - timestamp: Date.now(), -}); - -await wsApi.submitNewFuturesOrder('usdm', { - symbol: 'BTCUSDT', - side: 'SELL', - type: 'MARKET', - quantity: '0.001', - timestamp: Date.now(), -}); -``` - -See also: - -- [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) -- [Raw WebSocket API promises example](../examples/WebSockets/WS-API/ws-api-raw-promises.ts) - ---- - - -## Environments and Special Endpoints - -### Demo trading - -Demo trading uses real market data with simulated trading. For strategy testing, this is usually more useful than testnet. - -```typescript -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - demoTrading: true, -}); -``` - -Demo trading is supported by SDK options for REST API and WebSocket clients where Binance provides demo endpoints. - -### Testnet - -Testnet uses separate credentials and simulated market conditions. - -```typescript -const client = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - testnet: true, -}); -``` - -Use testnet for endpoint wiring and permission checks. Do not use testnet market behavior as evidence that a live strategy is profitable or safe. - -### Market maker endpoints - -Binance provides market maker endpoints for eligible futures users. If you qualify and need those endpoints, enable them with `useMMSubdomain: true`. - -```typescript -const usdm = new USDMClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - useMMSubdomain: true, -}); - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - useMMSubdomain: true, -}); -``` - -Market maker endpoints are for supported futures products. They are not a general Spot endpoint override and are not available on testnet. - ---- - - -## Proxies for REST API and WebSocket - -Use a proxy when the process needs a fixed egress IP, must cross an approved corporate network, or has a controlled network failover path. A proxy does not select a Binance product, enable a market-maker endpoint, change account eligibility, or replace the `testnet` and `demoTrading` options. - -The broader [Using proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) article covers the shared constructor pattern. The Binance examples below also cover the extra REST API request used by listen-key and listen-token helpers. - -Proxy agents are a Node.js networking feature. Browser applications cannot select a raw socket agent. - -### HTTP or HTTPS proxy - -Install the agent: - -```bash -npm install binance https-proxy-agent -``` - -Set `BINANCE_PROXY_URL` to the full proxy URL, including URL-encoded credentials when required. - -This public check sends one Spot REST API call and one Spot stream through the same proxy: - - - -```typescript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; - -const proxyUrl = process.env.BINANCE_PROXY_URL; - -if (!proxyUrl) { - throw new Error('Set BINANCE_PROXY_URL before running this example.'); -} - -const proxyAgent = new HttpsProxyAgent(proxyUrl); - -const rest = new MainClient( - {}, - { - httpsAgent: proxyAgent, - proxy: false, - }, -); - -const ws = new WebsocketClient({ - wsOptions: { - agent: proxyAgent, - }, -}); - -ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through proxy:', wsKey); -}); -ws.on('formattedMessage', (event) => { - console.log('stream update', event); -}); -ws.on('exception', console.error); - -async function main() { - const serverTime = await rest.getServerTime(); - console.log('REST API connected through proxy:', serverTime); - - ws.subscribe(['btcusdt@trade'], WS_KEY_MAP.main); -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); - -main().catch(console.error); -``` - -REST API networking options belong in the second constructor argument for `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. - -- `httpsAgent` sends the HTTPS request through the agent. -- `proxy: false` prevents Axios from applying another proxy configuration on top of that agent. -- `wsOptions.agent` controls the WebSocket connection. - -Public streams, normal WebSocket API commands, and the current Spot WebSocket API user-data subscription only use the socket path. Those workflows need `wsOptions.agent`, but do not make an auxiliary REST API request. - -### Listen-key and listen-token helpers through a proxy - -Some user-data helpers use two network paths. The SDK opens the WebSocket through `wsOptions.agent`, then uses REST API calls to create or renew a listen key or token through `requestOptions`. - -This example authenticates a USD-M Futures user-data stream without placing an order: - - - -```typescript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { WebsocketClient } from 'binance'; - -const proxyUrl = process.env.BINANCE_PROXY_URL; - -if (!proxyUrl) { - throw new Error('Set BINANCE_PROXY_URL before running this example.'); -} - -const proxyAgent = new HttpsProxyAgent(proxyUrl); - -const ws = new WebsocketClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - wsOptions: { - agent: proxyAgent, - }, - requestOptions: { - httpsAgent: proxyAgent, - proxy: false, - }, -}); - -ws.on('open', ({ wsKey }) => { - console.log('user-data socket connected:', wsKey); -}); -ws.on('formattedUserDataMessage', (event) => { - console.log('user-data event', event); -}); -ws.on('exception', console.error); - -async function main() { - await ws.subscribeUsdFuturesUserDataStream(); - console.log('USD-M Futures user-data stream is ready'); -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); - -main().catch(console.error); -``` - -Use both settings for the legacy Spot listen-key helpers, Margin listen-token or listen-key helpers, USD-M and COIN-M user-data helpers, and Portfolio Margin user-data helpers. The same rule applies when `WebsocketAPIClient.subscribeUserDataStream(...)` falls back to one of those helpers. - -Ordinary `WebsocketAPIClient` request and order methods send authentication and commands over the socket. They only need `wsOptions.agent`. The preferred Spot WebSocket API user-data subscription also stays on the socket. - -### SOCKS5 proxy - -Install the SOCKS agent: - -```bash -npm install binance socks-proxy-agent -``` - -Use `SocksProxyAgent` in the same REST API and WebSocket positions: - - - -```typescript -import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; -import { SocksProxyAgent } from 'socks-proxy-agent'; - -const proxyUrl = process.env.BINANCE_SOCKS_PROXY_URL; - -if (!proxyUrl) { - throw new Error('Set BINANCE_SOCKS_PROXY_URL before running this example.'); -} - -const proxyAgent = new SocksProxyAgent(proxyUrl); - -const rest = new MainClient( - {}, - { - httpsAgent: proxyAgent, - proxy: false, - }, -); - -const ws = new WebsocketClient({ - wsOptions: { - agent: proxyAgent, - }, -}); - -async function main() { - const serverTime = await rest.getServerTime(); - console.log('REST API connected through SOCKS5:', serverTime); - - ws.subscribe(['btcusdt@bookTicker'], WS_KEY_MAP.main); -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); - -main().catch(console.error); -``` - -See also: - -- [SOCKS WebSocket proxy example](../examples/WebSockets/Misc/ws-proxy-socks.ts) -- [REST API and WebSocket proxy test configuration](../test/proxy.util.ts) - -### Proxy checks - -- Keep proxy URLs and credentials in environment variables or a secret manager. -- URL-encode usernames and passwords when constructing a proxy URL from separate values. -- Make sure the proxy egress IP matches the Binance API key's IP whitelist. -- Test a public REST API call and public WebSocket subscription before private authentication. -- Confirm that every listen-key or listen-token REST API call uses the same intended network path as its socket. -- Measure request, connection, and reconnect latency through the proxy. -- Treat repeated HTTP 407 responses, TLS errors, and WebSocket reconnect loops as network failures. -- Keep the host clock synchronized. Change `recvWindow` only after measuring timestamp failures and proxy latency. -- The SDK does not rotate proxy endpoints. Handle endpoint selection outside the client when rotation is required. - ---- - - -## Production Notes - -Before a Binance integration trades unattended, these are the parts worth making explicit. - -### 1. Roll out in layers - -Move from public reads to private actions one layer at a time: - -1. Public REST APIs -2. Public WebSockets -3. Private REST API account reads -4. Private account/user data streams -5. Order validation -6. Tiny demo or live trading tests - -For Futures, prefer demo trading before live trading if it fits your setup. - -### 2. Reconnect, then backfill - -Listen for `reconnecting` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange disconnects. - -If your system uses WebSockets for account or market state, a reconnect should usually trigger a REST API backfill: - -1. Pause risky order actions when `reconnecting` fires. -2. On `reconnected`, query the REST API for account state, orders, fills, positions, and any market state you depend on. -3. Reconcile internal state. -4. React to any discrepancies in internal vs exchange state, as needed. -5. Resume normal processing. - -### 3. Keep credentials scoped - -Live, demo trading, Spot testnet, and Futures testnet credentials are different. Keep them separate in your secrets manager and deployment configuration. - -Use the minimum permissions needed for each key. A market-data key should not be able to trade. A trading key should not have withdrawal permissions. Do not put live secrets in frontend code. Make use of IP whitelisting for any API keys. These must be protected, treat them like passwords. - -### 4. Keep streams and commands separate - -Use `WebsocketClient` for streams. Use `WebsocketAPIClient` for commands you want to await. They share WebSocket infrastructure, but they solve different problems. - -### 5. Treat symbols and order IDs as product-specific state - -Spot, USD-M Futures, COIN-M Futures, Options, and Portfolio Margin do not all use the same symbol conventions: - -- Spot: `BTCUSDT` -- USD-M Futures: `BTCUSDT` -- COIN-M Futures: `BTCUSD_PERP` -- Stream names are usually lowercase, such as `btcusdt@trade`. Refer to the examples and/or exchange API docs for exact stream names. - -Client order IDs deserve the same care. If you do not need a custom client order ID, omit it. If your strategy relies on idempotency, retries, or reconciliation, generate an ID before sending the order and persist it using the restClient.generateNewOrderId() method. If you build your own value, keep the SDK's product prefix in place (query it using restClient.getOrderIdPrefix()) and stay within Binance's length and character constraints. - -### 6. Watch clocks and rate limits - -Private Binance requests are timestamp-sensitive. Keep your system clock synced and set `recvWindow` intentionally: - -```typescript -const client = new MainClient({ - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - recvWindow: 5000, -}); - -await client.fetchLatencySummary(); - -// For WebSocket API clients: -wsApi.setTimeOffsetMs(-500); -``` - -The REST API client also tracks Binance rate-limit headers it sees: - -```typescript -const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); -console.log(ticker); - -console.log(client.getRateLimitStates()); -``` - -If you see timestamp errors, fix system clock sync first. If you see rate-limit pressure, reduce polling, batch where the API allows it, and design around Binance's documented request weights. - -For more guidance on resolving timestamp & recvWindow issues, refer to the following guidance: -https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow - -### 7. Logging and large integers - -If you want SDK logs in your own monitoring stack, pass a logger: - -```typescript -import { DefaultLogger, WebsocketClient } from 'binance'; - -const customLogger: typeof DefaultLogger = { - ...DefaultLogger, - trace: () => {}, - info: (...params) => console.info(new Date(), ...params), - error: (...params) => console.error(new Date(), ...params), -}; - -const ws = new WebsocketClient( - { - api_key: process.env.BINANCE_API_KEY!, - api_secret: process.env.BINANCE_API_SECRET!, - beautify: true, - }, - customLogger, -); -``` - -JavaScript cannot precisely represent integers above `Number.MAX_SAFE_INTEGER`. If you need to preserve very large order IDs from WebSocket messages, provide a custom parser: - -```typescript -import { WebsocketClient } from 'binance'; - -const ws = new WebsocketClient({ - customParseJSONFn: (rawEvent) => { - return JSON.parse(rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"')); - }, -}); -``` - -See also: [custom parser example](../examples/WebSockets/Misc/ws-custom-parser.ts) - ---- - - -## FAQ - -**Which REST API client should I use?** - -Use `MainClient` for Spot, margin, wallet, Convert, Earn, sub-account, and many account APIs. Use `USDMClient` for USD-M Futures. Use `CoinMClient` for COIN-M Futures. Use `PortfolioClient` for Portfolio Margin. - -**Do I need API keys for public market data?** - -No. Public REST API market data and public WebSocket market data do not require API keys. - -**Can I use one Binance API key for every product group?** - -Sometimes, but only when the key belongs to the right environment and has the required product permissions enabled. Keep live, demo, and testnet credentials separate. Also keep high-risk permissions, especially withdrawals, separate from ordinary trading keys. - -**What is the difference between HMAC, RSA, and Ed25519?** - -HMAC is the standard API key + secret flow. RSA and Ed25519 use self-generated private keys. The SDK detects PEM private keys automatically when they are passed as `api_secret`. Ed25519 is recommended for latency-sensitive WebSocket API usage because it supports WebSocket API session authentication. - -**Why both `WebsocketClient` and `WebsocketAPIClient`?** - -- `WebsocketClient` is for subscriptions and streaming topics. -- `WebsocketAPIClient` is for commands over Binance's WebSocket API. Think "REST API" but over persistent WebSockets. - -**Should I use listen keys for Spot user data?** - -Use `WebsocketAPIClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` for Spot user data. Binance retired the older Spot listen-key workflow, so JavaScript apps should not start new Spot user data streams with `POST /api/v3/userDataStream`. - -**What happens if a WebSocket connection drops?** - -The SDK supports reconnect and resubscribe flows. Listen for `reconnecting` and `reconnected`. Use `reconnected` as a trigger to reconcile state through the REST API before resuming risky trading actions. - -**Should I use demo trading or testnet?** - -Use demo trading when you want simulated trading with real market data. Use testnet for API wiring, endpoint behavior, and permission checks. Do not treat testnet market behavior as representative of live market behavior. - -**Can I use this Binance API SDK in TypeScript projects?** - -Yes. The package is TypeScript-first and publishes type declarations. - -**Do I need TypeScript to use this JavaScript Binance SDK?** - -No. Pure JavaScript projects can use this SDK too. Type declarations are included and will help your IDE, but TypeScript is not required. - -**Can I use this package in both ESM and CommonJS projects?** - -Yes. The package supports both ESM-style imports and CommonJS `require()`. - -**Does this guide cover every SDK method?** - -No. This guide covers the common first steps and production concerns. For full method coverage, see: - -- [Binance JavaScript endpoint reference](./endpointFunctionList.md) -- [Binance SDK examples](../examples) -- [Binance SDK source on GitHub](https://github.com/sieblyio/binance) - ---- - - -## Next steps - -If you want to learn more about integrating with Binance APIs and WebSockets: - -- Explore the [Binance JavaScript examples on GitHub](../examples) -- Review the full endpoint list: [Binance JavaScript endpoint reference](./endpointFunctionList.md) -- Check the Binance JavaScript SDK on npm: [`binance`](https://www.npmjs.com/package/binance) -- Browse the source code of the Binance JavaScript SDK on GitHub: [`sieblyio/binance`](https://github.com/sieblyio/binance) -- Review auth examples: [Ed25519](../examples/auth/rest-private-ed25519.md) and [RSA](../examples/auth/rest-private-rsa.md) -- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) - -================ -File: src/types/websockets/ws-api-requests.ts -================ -import { - FuturesAlgoConditionalOrderTypes, - FuturesAlgoOrderType, - FuturesOrderType, - PositionSide, - PriceMatchMode, - WorkingType, -} from '../futures'; -import { - BooleanString, - KlineInterval, - numberInString, - OrderResponseType, - OrderSide, - OrderTimeInForce, - OrderType, - SelfTradePreventionMode, -} from '../shared'; -⋮---- -/** - * Simple request params with timestamp (required) & recv window (optional) - */ -export type WSAPIRecvWindowTimestamp = { - recvWindow?: number; - timestamp: number; -}; -⋮---- -/** - * - * Authentication request types - * - */ -export interface WSAPISessionLogonRequest { - timestamp: number; -} -⋮---- -/** - * - * General request types - * - */ -export interface WSAPIExchangeInfoRequest { - symbol?: string; - symbols?: string[]; - permissions?: string[]; - showPermissionSets?: boolean; - symbolStatus?: string; -} -⋮---- -/** - * - * Market data request types - * - */ -⋮---- -export interface WSAPIOrderBookRequest { - symbol: string; - limit?: number; - symbolStatus?: string; -} -⋮---- -export interface WSAPITradesRecentRequest { - symbol: string; - limit?: number; -} -⋮---- -export interface WSAPITradesHistoricalRequest { - symbol: string; - fromId?: number; - limit?: number; -} -⋮---- -export interface WSAPIBlockTradesHistoricalRequest { - symbol: string; - fromId: number; - limit?: number; -} -⋮---- -export interface WSAPITradesAggregateRequest { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIKlinesRequest { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} -⋮---- -export interface WSAPIAvgPriceRequest { - symbol: string; -} -⋮---- -/** - * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. - */ -export interface WSAPIExecutionRulesRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} -⋮---- -export interface WSAPIReferencePriceRequest { - symbol: string; -} -⋮---- -export interface WSAPIReferencePriceCalculationRequest { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITicker24hrRequest { - symbol?: string; - symbols?: string[]; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerTradingDayRequest { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerRequest { - symbol?: string; - symbols?: string[]; - windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} -⋮---- -windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerPriceRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} -⋮---- -/** - * Symbol for single symbol, or symbols for multiple symbols - */ -export interface WSAPITickerBookRequest { - symbol?: string; - symbols?: string[]; - symbolStatus?: string; -} -⋮---- -/** - * - * Account request types - Spot - * - */ -⋮---- -export interface WSAPIAllOrdersRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIAllOrderListsRequest { - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyTradesRequest { - symbol: string; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyPreventedMatchesRequest { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} -⋮---- -export interface WSAPIMyAllocationsRequest { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} -⋮---- -/** - * Trading request types - */ -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; -⋮---- -export interface WSAPINewSpotOrderRequest { - symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; -} -⋮---- -export interface WSAPIOrderTestRequest { - symbol: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - computeCommissionRates?: boolean; - timestamp: number; - recvWindow?: number; -} -⋮---- -export interface WSAPIOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - newClientOrderId?: string; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderCancelReplaceRequest { - symbol: string; - cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; - cancelOrderId?: number; - cancelOrigClientOrderId?: string; - cancelNewClientOrderId?: string; - side: 'BUY' | 'SELL'; - type: string; - timeInForce?: string; - price?: numberInString; - quantity?: numberInString; - quoteOrderQty?: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - stopPrice?: numberInString; - trailingDelta?: number; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; - orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderAmendKeepPriorityRequest { - symbol: string; - orderId?: number | string; - origClientOrderId?: string; - newClientOrderId?: string; - newQty?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOpenOrdersStatusRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOpenOrdersCancelAllRequest { - symbol: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -/** - * Order list request types - */ -export interface WSAPIOrderListPlaceRequest { - symbol: string; - side: 'BUY' | 'SELL'; - price: numberInString; - quantity: numberInString; - listClientOrderId?: string; - limitClientOrderId?: string; - limitIcebergQty?: numberInString; - limitStrategyId?: number; - limitStrategyType?: number; - stopPrice?: numberInString; - trailingDelta?: number; - stopClientOrderId?: string; - stopLimitPrice?: numberInString; - stopLimitTimeInForce?: string; - stopIcebergQty?: numberInString; - stopStrategyId?: number; - stopStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOCORequest { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; - listClientOrderId?: string; - aboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - aboveClientOrderId?: string; - aboveIcebergQty?: numberInString; - abovePrice?: numberInString; - aboveStopPrice?: numberInString; - aboveTrailingDelta?: number; - aboveTimeInForce?: string; - aboveStrategyId?: number; - aboveStrategyType?: number; - belowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - belowClientOrderId?: string; - belowIcebergQty?: numberInString; - belowPrice?: numberInString; - belowStopPrice?: numberInString; - belowTrailingDelta?: number; - belowTimeInForce?: string; - belowStrategyId?: number; - belowStrategyType?: number; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOTORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingQuantity: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOTOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: number | string; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOPORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: numberInString; - pendingStopPrice?: numberInString; - pendingTrailingDelta?: numberInString; - pendingIcebergQty?: numberInString; - pendingTimeInForce?: string; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListPlaceOPOCORequest { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: numberInString; - workingQuantity: numberInString; - workingIcebergQty?: numberInString; - workingTimeInForce?: string; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: numberInString; - pendingAboveStopPrice?: numberInString; - pendingAboveTrailingDelta?: numberInString; - pendingAboveIcebergQty?: numberInString; - pendingAboveTimeInForce?: string; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: numberInString; - pendingBelowStopPrice?: numberInString; - pendingBelowTrailingDelta?: numberInString; - pendingBelowIcebergQty?: numberInString; - pendingBelowTimeInForce?: string; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListStatusRequest { - origClientOrderId?: string; - orderListId?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIOrderListCancelRequest { - symbol: string; - orderListId?: number; - listClientOrderId?: string; - newClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -/** - * SOR request types - */ -export interface WSAPISOROrderPlaceRequest { - symbol: string; - side: 'BUY' | 'SELL'; - type: 'LIMIT' | 'MARKET'; - timeInForce?: string; - price?: numberInString; - quantity: numberInString; - newClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - icebergQty?: numberInString; - strategyId?: number; - strategyType?: number; - selfTradePreventionMode?: string; - timestamp: number; - recvWindow?: number; -} -⋮---- -export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { - computeCommissionRates?: boolean; -}; -⋮---- -/** - * Futures market data request types - */ -⋮---- -export interface WSAPIFuturesOrderBookRequest { - symbol: string; - limit?: number; -} -⋮---- -export interface WSAPIFuturesTickerPriceRequest { - symbol?: string; -} -⋮---- -export interface WSAPIFuturesTickerBookRequest { - symbol?: string; -} -⋮---- -/** - * Futures trading request types - */ -⋮---- -export interface WSAPINewFuturesOrderRequest { - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesOrderType; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberType; - newClientOrderId?: string; - stopPrice?: numberType; - closePosition?: BooleanString; - activationPrice?: numberType; - callbackRate?: numberType; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: SelfTradePreventionMode; - priceMatch?: PriceMatchMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD - recvWindow?: number; - timestamp: number; -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface WSAPIFuturesOrderModifyRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - side: 'BUY' | 'SELL'; - quantity: numberInString; - price: numberInString; - priceMatch?: - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; - origType?: string; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - modifyId?: number; - reduceOnly?: BooleanString; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesOrderCancelRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesOrderStatusRequest { - symbol: string; - orderId?: number; - origClientOrderId?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesPositionRequest { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIFuturesPositionV2Request { - symbol?: string; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIAccountInformationRequest { - omitZeroBalances?: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface WSAPIAccountCommissionWSAPIRequest { - symbol: string; -} -⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api - */ -export interface WSAPINewFuturesAlgoOrderRequest { - algoType: FuturesAlgoOrderType; - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesAlgoConditionalOrderTypes; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberInString; - clientAlgoId?: string; - triggerPrice?: numberInString; - closePosition?: BooleanString; - activatePrice?: numberInString; - callbackRate?: numberInString; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: OrderResponseType; - priceMatch?: PriceMatchMode; - selfTradePreventionMode?: SelfTradePreventionMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD - recvWindow?: number; - timestamp: number; -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order - */ -export interface WSAPIFuturesAlgoOrderCancelRequest { - algoid?: number; - clientalgoid?: string; - recvWindow?: number; - timestamp: number; -} - -================ -File: src/types/futures.ts -================ -import { - BooleanString, - ExchangeFilter, - KlineInterval, - numberInString, - OrderBookRow, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - RateLimiter, - SelfTradePreventionMode, - SymbolIcebergPartsFilter, - SymbolLotSizeFilter, - SymbolMarketLotSizeFilter, - SymbolMaxIcebergOrdersFilter, - SymbolMaxPositionFilter, - SymbolPriceFilter, -} from './shared'; -⋮---- -export type FuturesContractType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; -⋮---- -export interface ContinuousContractKlinesParams { - pair: string; - contractType: FuturesContractType; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface IndexPriceKlinesParams { - pair: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface SymbolKlinePaginatedParams { - symbol: string; - interval: KlineInterval; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface FuturesDataPaginatedParams { - symbol: string; - contractType?: string; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMTakerBuySellVolumeParams { - pair: string; - contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMBasisParams { - pair: string; - contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface FuturesCoinMLongShortAccountRatioParams { - pair: string; - contractType?: 'PERPETUAL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface GetFuturesAllOrdersParams { - symbol?: string; - orderId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export enum EnumDualSideMode { - HedgeMode = 'true', - OneWayMode = 'false', -} -⋮---- -export type DualSideMode = `${EnumDualSideMode}`; -⋮---- -export enum EnumMultiAssetMode { - MultiAssetsMode = 'true', - SingleAssetsMode = 'false', -} -⋮---- -export type MultiAssetsMode = `${EnumMultiAssetMode}`; -⋮---- -export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; -⋮---- -export type MarginType = 'ISOLATED' | 'CROSSED'; -⋮---- -export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; -⋮---- -export type FuturesOrderType = - | 'LIMIT' - | 'MARKET' - | 'STOP' - | 'STOP_MARKET' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_MARKET' - | 'TRAILING_STOP_MARKET'; -⋮---- -export type PriceMatchMode = - | 'NONE' - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; -⋮---- -// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. -export interface NewFuturesOrderParams { - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesOrderType; - timeInForce?: OrderTimeInForce; - quantity?: numberType; - reduceOnly?: BooleanString; - price?: numberType; - newClientOrderId?: string; - stopPrice?: numberType; - closePosition?: BooleanString; - activationPrice?: numberType; - callbackRate?: numberType; - workingType?: WorkingType; - priceProtect?: BooleanString; - newOrderRespType?: 'ACK' | 'RESULT'; - selfTradePreventionMode?: SelfTradePreventionMode; - priceMatch?: PriceMatchMode; - goodTillDate?: number; // Mandatory when timeInForce is GTD -} -⋮---- -goodTillDate?: number; // Mandatory when timeInForce is GTD -⋮---- -export interface ModifyFuturesOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: OrderSide; - quantity?: numberType; - price?: numberType; - priceMatch?: PriceMatchMode; - modifyId?: number; - reduceOnly?: BooleanString; -} -⋮---- -export enum EnumPositionMarginChangeType { - AddPositionMargin = 1, - ReducePositionMargin = 0, -} -⋮---- -export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; -⋮---- -export type IncomeType = - | 'TRANSFER' - | 'WELCOME_BONUS' - | 'REALIZED_PNL' - | 'FUNDING_FEE' - | 'SPECIAL_FUNDING_FEE' - | 'COMMISSION' - | 'INSURANCE_CLEAR'; -⋮---- -export interface CancelMultipleOrdersParams { - symbol: string; - orderIdList?: number[]; - origClientOrderIdList?: string[]; -} -⋮---- -export interface CancelOrdersTimeoutParams { - symbol: string; - countdownTime?: 0 | number; -} -⋮---- -export interface SetLeverageParams { - symbol: string; - leverage: number; -} -⋮---- -export interface SetLeverageResult { - leverage: number; - maxNotionalValue: numberInString; - symbol: string; -} -⋮---- -export interface SetMarginTypeParams { - symbol: string; - marginType: MarginType; -} -⋮---- -export interface SetIsolatedMarginParams { - symbol: string; - positionSide?: PositionSide; - amount: number; - type: PositionMarginChangeType; -} -⋮---- -export interface SetIsolatedMarginResult { - amount: numberInString; - code: 200 | number; - msg: string; - type: 1 | 2; -} -⋮---- -export interface GetPositionMarginChangeHistoryParams { - symbol: string; - type?: PositionMarginChangeType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -/** - * Income history query for `GET /fapi/v1/income` and `GET /dapi/v1/income`. - * Paginate with `startTime` and `endTime`. `page` is not accepted. - */ -export interface GetIncomeHistoryParams { - symbol?: string; - incomeType?: IncomeType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface IncomeHistory { - symbol?: string; - incomeType: IncomeType; - income: string; - asset: string; - time: number; - info: string; - tranId: number; - tradeId: string; -} -⋮---- -export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; -⋮---- -export interface GetForceOrdersParams { - symbol?: string; - autoCloseType?: ForceOrderCloseType; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export type ContactType = - | 'PERPETUAL' - | 'CURRENT_MONTH' - | 'NEXT_MONTH' - | 'CURRENT_QUARTER' - | 'NEXT_QUARTER'; -⋮---- -export type ContractStatus = - | 'PENDING_TRADING' - | 'TRADING' - | 'PRE_DELIVERING' - | 'DELIVERING' - | 'DELIVERED' - | 'CANCELLED' - | 'PRE_SETTLE' - | 'SETTLING' - | 'CLOSE'; -⋮---- -export interface FuturesSymbolPercentPriceFilter { - filterType: 'PERCENT_PRICE'; - multiplierUp: numberInString; - multiplierDown: numberInString; - multiplierDecimal: numberInString; -} -⋮---- -export interface FuturesSymbolMaxOrdersFilter { - filterType: 'MAX_NUM_ORDERS'; - limit: number; -} -⋮---- -export interface FuturesSymbolMaxAlgoOrdersFilter { - filterType: 'MAX_NUM_ALGO_ORDERS'; - limit: number; -} -⋮---- -export interface FuturesSymbolMinNotionalFilter { - filterType: 'MIN_NOTIONAL'; - notional: numberInString; -} -⋮---- -/** - * Undocumented USDⓈ-M `exchangeInfo` filter. Not in the published filter schema. - * Observed on live symbols (for example BTCUSDT) with `positionControlSide: "NONE"`. - * connector-python leaves it in `additional_properties`. - */ -export interface FuturesSymbolPositionRiskControlFilter { - filterType: 'POSITION_RISK_CONTROL'; - /** - * Undocumented. Observed value: `NONE`. - */ - positionControlSide: string; -} -⋮---- -/** - * Undocumented. Observed value: `NONE`. - */ -⋮---- -export type FuturesSymbolFilter = - | SymbolPriceFilter - | FuturesSymbolPercentPriceFilter - | SymbolLotSizeFilter - | FuturesSymbolMinNotionalFilter - | SymbolIcebergPartsFilter - | SymbolMarketLotSizeFilter - | FuturesSymbolMaxOrdersFilter - | FuturesSymbolMaxAlgoOrdersFilter - | SymbolMaxIcebergOrdersFilter - | SymbolMaxPositionFilter - | FuturesSymbolPositionRiskControlFilter; -⋮---- -export interface FuturesSymbolExchangeInfo { - symbol: string; - pair: string; - contractType: ContactType; - deliveryDate: number; - onboardDate: number; - status: ContractStatus; - maintMarginPercent: numberInString; - requiredMarginPercent: numberInString; - baseAsset: string; - quoteAsset: string; - marginAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - underlyingType: 'COIN' | 'INDEX'; // No other known values - underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc - settlePlan: number; - triggerProtect: numberInString; - filters: FuturesSymbolFilter[]; - OrderType: OrderType[]; - timeInForce: OrderTimeInForce[]; - liquidationFee: numberInString; - marketTakeBound: numberInString; - contractSize?: number; -} -⋮---- -underlyingType: 'COIN' | 'INDEX'; // No other known values -underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc -⋮---- -export interface FuturesExchangeInfo { - exchangeFilters: ExchangeFilter[]; - rateLimits: RateLimiter[]; - serverTime: number; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any[]; - symbols: FuturesSymbolExchangeInfo[]; - timezone: string; -} -⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -⋮---- -export interface FuturesOrderBook { - lastUpdateId: number; - E: number; - T: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; -} -⋮---- -export interface RawFuturesTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; -} -⋮---- -export interface AggregateFuturesTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; -} -⋮---- -export interface MarkPrice { - symbol: string; - markPrice: numberInString; - indexPrice: numberInString; - estimatedSettlePrice: numberInString; - lastFundingRate: numberInString; - interestRate: numberInString; - nextFundingTime: number; - time: number; -} -⋮---- -export interface FundingRateHistory { - symbol: string; - fundingRate: numberInString; - fundingTime: number; - markPrice: numberInString; - rateType?: 'Regular' | 'Special'; -} -⋮---- -export interface FuturesSymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - time: number; -} -⋮---- -export interface OpenInterest { - openInterest: numberInString; - symbol: string; - time: number; -} -⋮---- -export interface HistoricOpenInterest { - symbol: string; - sumOpenInterest: string; - sumOpenInterestValue: string; - CMCCirculatingSupply: string; - timestamp: number; -} -⋮---- -export interface PositionModeParams { - dualSidePosition: DualSideMode; -} -⋮---- -export interface ModeChangeResult { - code: 200 | number; - msg: 'success' | string; -} -⋮---- -export interface PositionModeResponse { - dualSidePosition: boolean; -} -⋮---- -export interface MultiAssetModeResponse { - multiAssetsMargin: boolean; -} -⋮---- -export interface NewOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote?: numberInString; - executedQty: numberInString; - orderId: number; - avgPrice?: numberInString; - origQty: numberInString; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - origType: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate?: number; -} -⋮---- -export interface NewOrderError { - code: number; - msg: string; -} -⋮---- -export interface OrderResult { - avgPrice: numberInString; - clientOrderId: string; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - time: number; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - goodTillDate: number; - cumBase?: numberInString; - pair?: string; -} -⋮---- -export interface ModifyFuturesOrderResult { - orderId: number; - symbol: string; - pair: string; - status: OrderStatus; - clientOrderId: string; - price: numberInString; - avgPrice: numberInString; - origQty: numberInString; - executedQty: numberInString; - cumQty: numberInString; - cumBase: numberInString; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - reduceOnly: boolean; - closePosition: boolean; - side: OrderSide; - positionSide: PositionSide; - stopPrice: numberInString; - workingType: WorkingType; - priceProtect: boolean; - origType: FuturesOrderType; - updateTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; - modifyId?: number; -} -⋮---- -export interface CancelFuturesOrderResult { - clientOrderId: string; - cumQty: numberInString; - cumQuote: numberInString; - executedQty: numberInString; - orderId: number; - origQty: numberInString; - origType: FuturesOrderType; - price: numberInString; - reduceOnly: boolean; - side: OrderSide; - positionSide: PositionSide; - status: OrderStatus; - stopPrice: numberInString; - closePosition: boolean; - symbol: string; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - activatePrice: numberInString; - priceRate: numberInString; - updateTime: number; - workingType: WorkingType; - priceProtect: boolean; - selfTradePreventionMode: SelfTradePreventionMode; - priceMatch: PriceMatchMode; -} -⋮---- -export interface CancelAllOpenOrdersResult { - code: 200 | numberInString; - msg: string; -} -⋮---- -export interface FuturesAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - marginAvailable: boolean; - updateTime: numberInString; -} -⋮---- -export interface FuturesCoinMAccountBalance { - accountAlias: string; - asset: string; - balance: numberInString; - withdrawAvailable: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesAccountAsset { - asset: string; - walletBalance: numberInString; - unrealizedProfit: numberInString; - marginBalance: numberInString; - maintMargin: numberInString; - initialMargin: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - maxWithdrawAmount: numberInString; - crossWalletBalance: numberInString; - crossUnPnl: numberInString; - availableBalance: numberInString; - marginAvailable: boolean; - updateTime: number; -} -⋮---- -export interface FuturesAccountPosition { - symbol: string; - initialMargin: numberInString; - maintMargin: numberInString; - unrealizedProfit: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - leverage: numberInString; - isolated: boolean; - entryPrice: numberInString; - maxNotional: numberInString; - positionSide: PositionSide; - positionAmt: numberInString; - notional: numberInString; - isolatedWallet: numberInString; - updateTime: number; - bidNotional: numberInString; - askNotional: numberInString; -} -⋮---- -export interface FuturesCoinMAccountPosition { - symbol: string; - positionAmt: numberInString; - initialMargin: numberInString; - maintMargin: numberInString; - unrealizedProfit: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - leverage: numberInString; - isolated: boolean; - positionSide: PositionSide; - entryPrice: numberInString; - maxQty: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesAccountInformation { - feeTier: numberInString; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - updateTime: numberInString; - multiAssetsMargin: boolean; - totalInitialMargin: numberInString; - totalMaintMargin: numberInString; - totalWalletBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalMarginBalance: numberInString; - totalPositionInitialMargin: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalCrossWalletBalance: numberInString; - totalCrossUnPnl: numberInString; - availableBalance: numberInString; - maxWithdrawAmount: numberInString; - assets: FuturesAccountAsset[]; - positions: FuturesAccountPosition[]; -} -⋮---- -export interface FuturesCoinMAccountInformation { - assets: Omit[]; - positions: FuturesCoinMAccountPosition[]; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; -} -⋮---- -export interface FuturesPosition { - entryPrice: numberInString; - marginType: 'isolated' | 'cross'; - isAutoAddMargin: 'false' | 'true'; - isolatedMargin: numberInString; - leverage: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - maxNotionalValue: numberInString; - positionAmt: numberInString; - notional: numberInString; - isolatedWallet: numberInString; - symbol: string; - unRealizedProfit: numberInString; - positionSide: PositionSide; - updateTime: number; -} -⋮---- -export interface FuturesPositionV3 { - symbol: string; - positionSide: PositionSide; - positionAmt: numberInString; - entryPrice: numberInString; - breakEvenPrice: numberInString; - markPrice: numberInString; - unRealizedProfit: numberInString; - liquidationPrice: numberInString; - isolatedMargin: numberInString; - notional: numberInString; - marginAsset: string; - isolatedWallet: numberInString; - initialMargin: numberInString; - maintMargin: numberInString; - positionInitialMargin: numberInString; - openOrderInitialMargin: numberInString; - adl: number; - bidNotional: numberInString; - askNotional: numberInString; - updateTime: number; -} -⋮---- -export interface FuturesPositionTrade { - buyer: boolean; - commission: numberInString; - commissionAsset: string; - id: number; - maker: boolean; - orderId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - realizedPnl: numberInString; - side: OrderSide; - positionSide: PositionSide; - symbol: string; - time: number; - pair?: string; - baseQty?: numberInString; - marginAsset?: string; -} -⋮---- -export interface ForceOrderResult { - orderId: number; - symbol: string; - status: OrderStatus; - clientOrderId: string; - price: numberInString; - avgPrice: numberInString; - origQty: numberInString; - executedQty: numberInString; - cumQuote: numberInString; - timeInForce: OrderTimeInForce; - type: FuturesOrderType; - reduceOnly: boolean; - closePosition: boolean; - side: OrderSide; - stopPrice: numberInString; - workingType: WorkingType; - origType: FuturesOrderType; - time: number; - updateTime: number; - cumBase?: numberInString; - pair?: string; - goodTillDate?: number; -} -⋮---- -export interface SymbolLeverageBracket { - bracket: number; - initialLeverage: number; - notionalCap: number; - notionalFloor: number; - maintMarginRatio: number; - cum: number; -} -⋮---- -export interface SymbolLeverageBracketsResult { - symbol: string; - brackets: SymbolLeverageBracket[]; -} -⋮---- -export interface UserCommissionRate { - symbol: string; - makerCommissionRate: numberInString; - takerCommissionRate: numberInString; - rpiCommissionRate?: numberInString; -} -⋮---- -export interface FuturesAccountConfig { - feeTier: number; - canTrade: boolean; - canDeposit: boolean; - canWithdraw: boolean; - dualSidePosition: boolean; - updateTime: number; - multiAssetsMargin: boolean; - tradeGroupId: number; -} -⋮---- -export interface SymbolConfig { - symbol: string; - marginType: string; - isAutoAddMargin: string; - leverage: number; - maxNotionalValue: string; -} -⋮---- -export interface UserForceOrder { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; -} -⋮---- -export interface RebateDataOverview { - brokerId: string; - newTraderRebateCommission: numberInString; - oldTraderRebateCommission: numberInString; - totalTradeUser: number; - unit: string; - totalTradeVol: numberInString; - totalRebateVol: numberInString; - time: number; -} -⋮---- -export interface SetCancelTimeoutResult { - symbol: string; - countdownTime: numberInString; -} -⋮---- -export interface ChangeStats24hr { - symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; // First tradeId - lastId: number; // Last tradeId - count: number; -} -⋮---- -firstId: number; // First tradeId -lastId: number; // Last tradeId -⋮---- -export interface OrderAmendmentDetailPrice { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetailQty { - before: numberInString; - after: numberInString; -} -⋮---- -export interface OrderAmendmentDetail { - price: OrderAmendmentDetailPrice; - origQty: OrderAmendmentDetailQty; - count: number; -} -⋮---- -export interface OrderAmendment { - amendmentId: number; - symbol: string; - pair: string; - orderId: number; - clientOrderId: string; - time: number; - amendment: OrderAmendmentDetail; - modifyId?: number; -} -⋮---- -export interface QuarterlyContractSettlementPrice { - deliveryTime: number; - deliveryPrice: number; -} -⋮---- -export interface BasisParams { - pair: string; - contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; - period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; - limit: number; - startTime?: number; - endTime?: number; -} -⋮---- -export interface Basis { - indexPrice: string; - contractType: string; - basisRate: string; - futuresPrice: string; - annualizedBasisRate: string; - basis: string; - pair: string; - timestamp: number; -} -⋮---- -export interface IndexPriceConstituent { - exchange: string; - symbol: string; - price: numberInString; - weight: numberInString; -} -⋮---- -export interface IndexPriceConstituents { - symbol: string; - time: number; - constituents: IndexPriceConstituent[]; -} -⋮---- -export interface InsuranceFundBalance { - symbols: string[]; - assets: { - asset: string; - marginBalance: string; - updateTime: number; - }[]; -} -⋮---- -export interface ModifyOrderParams { - orderId?: number; - origClientOrderId?: string; - symbol: string; - side: 'SELL' | 'BUY'; - quantity: string; - price: string; - priceMatch?: - | 'OPPONENT' - | 'OPPONENT_5' - | 'OPPONENT_10' - | 'OPPONENT_20' - | 'QUEUE' - | 'QUEUE_5' - | 'QUEUE_10' - | 'QUEUE_20'; - modifyId?: number; - reduceOnly?: BooleanString; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface GetFuturesOrderModifyHistoryParams { - symbol: string; - orderId?: number; - origClientOrderId?: string; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface FuturesTradeHistoryDownloadId { - avgCostTimestampOfLast30d: number; - downloadId: string; -} -⋮---- -export interface FuturesTransactionDownloadLink { - downloadId: string; - status: 'completed' | 'processing'; - url: string; - expirationTimestamp: number; - isExpired: boolean | null; -} -⋮---- -export interface PortfolioMarginProAccountInfo { - maxWithdrawAmountUSD: string; - asset: string; - maxWithdrawAmount: string; // This field will be ignored in the response -} -⋮---- -maxWithdrawAmount: string; // This field will be ignored in the response -⋮---- -export interface FuturesConvertPair { - fromAsset: string; - toAsset: string; - fromAssetMinAmount: string; - fromAssetMaxAmount: string; - toAssetMinAmount: string; - toAssetMaxAmount: string; -} -⋮---- -export interface FuturesConvertQuoteRequest { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - validTime?: '10s' | '30s' | '1m' | '2m'; -} -⋮---- -export interface FuturesConvertQuote { - quoteId: string; - ratio: string; - inverseRatio: string; - validTimestamp: number; - toAmount: string; - fromAmount: string; -} -⋮---- -export interface FuturesConvertOrderStatus { - orderId: string; - orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; -} -⋮---- -/** - * Algo Order Types (Effective 2025-12-02) - * USDⓈ-M Futures conditional orders migrate to Algo Service - */ -⋮---- -export type FuturesAlgoOrderType = 'CONDITIONAL'; -⋮---- -export type FuturesAlgoConditionalOrderTypes = - | 'STOP_MARKET' - | 'TAKE_PROFIT_MARKET' - | 'STOP' - | 'TAKE_PROFIT' - | 'TRAILING_STOP_MARKET'; -⋮---- -/** - * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update - */ -export type FuturesAlgoOrderStatus = - | 'NEW' - | 'CANCELED' - | 'TRIGGERING' - | 'TRIGGERED' - | 'FINISHED' - | 'REJECTED' - | 'EXPIRED'; -⋮---- -export interface FuturesNewAlgoOrderParams { - algoType: FuturesAlgoOrderType; - symbol: string; - side: OrderSide; - positionSide?: PositionSide; - type: FuturesAlgoConditionalOrderTypes; - timeInForce?: OrderTimeInForce; - quantity?: numberInString; - price?: numberInString; - triggerPrice?: numberInString; - workingType?: WorkingType; - priceMatch?: PriceMatchMode; - closePosition?: BooleanString; - priceProtect?: BooleanString; - reduceOnly?: BooleanString; - activatePrice?: numberInString; - callbackRate?: numberInString; - clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ - selfTradePreventionMode?: SelfTradePreventionMode; - goodTillDate?: number; -} -⋮---- -clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ -⋮---- -export interface FuturesAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - algoType: FuturesAlgoOrderType; - orderType: FuturesAlgoConditionalOrderTypes; - symbol: string; - side: OrderSide; - positionSide: PositionSide; - timeInForce: OrderTimeInForce; - quantity: numberInString; - algoStatus: FuturesAlgoOrderStatus; - triggerPrice?: numberInString; - price?: numberInString; - icebergQuantity: numberInString | null; - selfTradePreventionMode: SelfTradePreventionMode; - workingType: WorkingType; - priceMatch: PriceMatchMode; - closePosition: boolean; - priceProtect: boolean; - reduceOnly: boolean; - activatePrice?: numberInString; - callbackRate?: numberInString; - createTime: number; - updateTime: number; - triggerTime: number; - goodTillDate: number; -} -⋮---- -export interface FuturesCancelAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} -⋮---- -export interface FuturesCancelAlgoOrderResponse { - algoId: number; - clientAlgoId: string; - code: string; - msg: string; -} -⋮---- -export interface FuturesCancelAllAlgoOpenOrdersResponse { - code: number; - msg: string; -} -⋮---- -export interface FuturesQueryAlgoOrderParams { - algoId?: number; - clientAlgoId?: string; -} -⋮---- -export interface FuturesQueryAlgoOrderResponse - extends FuturesAlgoOrderResponse { - actualOrderId: numberInString; - actualPrice: numberInString; - tpTriggerPrice?: numberInString; - tpPrice?: numberInString; - slTriggerPrice?: numberInString; - slPrice?: numberInString; - tpOrderType?: string; -} -⋮---- -export interface FuturesQueryOpenAlgoOrdersParams { - algoType?: FuturesAlgoOrderType; - symbol?: string; - algoId?: number; -} -⋮---- -export interface FuturesQueryAllAlgoOrdersParams { - symbol: string; - algoId?: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; // Default 500; max 1000 -} -⋮---- -limit?: number; // Default 500; max 1000 -⋮---- -export interface SymbolAdlRisk { - symbol: string; - adlRisk: 'low' | 'medium' | 'high'; - updateTime: number; -} -⋮---- -export interface TradingSession { - startTime: number; - endTime: number; - type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; -} -⋮---- -export interface MarketSchedule { - sessions: TradingSession[]; -} -⋮---- -export interface TradingSchedule { - updateTime: number; - marketSchedules: { - EQUITY?: MarketSchedule; - COMMODITY?: MarketSchedule; - KR_EQUITY?: MarketSchedule; - HK_EQUITY?: MarketSchedule; - CN_EQUITY?: MarketSchedule; - FX?: MarketSchedule; - }; -} -⋮---- -export interface RpiOrderBook { - lastUpdateId: number; - E: number; // Message output time - T: number; // Transaction time - bids: [numberInString, numberInString][]; - asks: [numberInString, numberInString][]; -} -⋮---- -E: number; // Message output time -T: number; // Transaction time - -================ -File: README.md -================ -# Node.js & JavaScript SDK for Binance REST APIs & WebSockets - -[![Build & Test](https://github.com/sieblyio/binance/actions/workflows/test.yml/badge.svg)](https://github.com/sieblyio/binance/actions/workflows/test.yml) -[![npm version](https://img.shields.io/npm/v/binance)][1] -[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] -[![users count](https://dependents.info/sieblyio/binance/badge?label=users)](https://dependents.info/sieblyio/binance) -[![npm downloads](https://img.shields.io/npm/dt/binance)][1] -[![last commit](https://img.shields.io/github/last-commit/sieblyio/binance)][1] -[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/binance/badge)](https://www.codefactor.io/repository/github/sieblyio/binance) -[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) -[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/sieblyio/binance) - -

- - - - SDK Logo - - -

- -[1]: https://www.npmjs.com/package/binance - -> [!TIP] -> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. - -Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets: - -- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). -- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. -- Complete TypeScript support (with type declarations for all API requests & responses). -- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. - - Strongly typed requests and responses. - - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. -- Actively maintained with a modern, promise-driven interface. -- Support for all authentication mechanisms available on Binance: - - HMAC - - RSA - - Ed25519 (required for WS API login, else each request is signed). - - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. -- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. - - Event driven messaging. - - Smart WebSocket persistence - - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. - - Automatically handle listenKey persistence and expiration/refresh. - - Emit `reconnected` event when dropped connection is restored. - - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. - - Optional: - - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). - - Automatic beautification of REST responses (parsing numbers in strings to numbers). -- Supports WebSocket API on all available product groups, including Spot & Futures: - - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; - - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. -- Heavy automated end-to-end testing with real API calls. - - End-to-end testing before any release. - - Real API calls in e2e tests. -- Proxy support via axios integration. -- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). -- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) -- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) - -## Table of Contents - -- [Installation](#installation) -- [Examples](#examples) - - [REST API Examples](./examples/REST) - - [WebSocket Examples](./examples/WebSockets) - - [WebSocket Consumers](./examples/WebSockets/) - - [WebSocket API](./examples/WebSockets/ws-api-client.ts) -- [Issues & Discussion](#issues--discussion) -- [Related Projects](#related-projects) -- [Documentation Links](#documentation) -- [Usage](#usage) - - [Demo Trading vs Testnet](#demo-trading-vs-testnet) - - [REST API Clients](#rest-api-clients) - - [REST Main Client](#rest-main-client) - - [REST USD-M Futures](#rest-usd-m-futures) - - [REST COIN-M Futures](#rest-coin-m-futures) - - [REST Portfolio Margin](#rest-portfolio-margin) - - [WebSockets](#websockets) - - [WebSocket Consumers](#websocket-consumers) - - [WebSocket API](#websocket-api) - - [Event Driven API](#event-driven-api) - - [Promise Driven API](#async-await-api) - - [Market Maker Endpoints](#market-maker-endpoints) - - [Using Market Maker Endpoints](#using-market-maker-endpoints) - - [Best practice](#best-practice) - - [Customise Logging](#customise-logging) - - [Frontend Usage](#browserfrontend-usage) - - [Import](#import) - - [Webpack](#webpack) -- [LLMs & AI](#use-with-llms--ai) -- [Contributions & Thanks](#contributions--thanks) - -## Installation - -`npm install binance --save` - -## Examples - -Refer to the [examples](./examples) folder for implementation demos. - -## Issues & Discussion - -- Issues? Check the [issues tab](https://github.com/sieblyio/binance/issues). -- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. -- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. -- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) - - - -## Related Projects - -Check out our JavaScript/TypeScript/Node.js SDKs & Projects: - -- Visit our website: [https://Siebly.io](https://siebly.io/) -- Try our REST API & WebSocket SDKs published on npmjs: - - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) - - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) - - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) - - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) - - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) - - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) - - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) - - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) - - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) -- Try my misc utilities: - - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) - - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) -- Check out my examples: - - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) - - -## Documentation - -Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. - -- Binance API Documentation - - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) - - [ Derivatives ](https://developers.binance.com/docs/derivatives) - - [ Margin ](https://developers.binance.com/docs/margin_trading) - - [ Wallet ](https://developers.binance.com/docs/wallet) -- [Find all products here](https://developers.binance.com/en) -- [REST Endpoint Function List](./docs/endpointFunctionList.md) -- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) - -## Structure - -This project uses typescript. Resources are stored in 3 key structures: - -- [src](./src) - the whole connector written in typescript -- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. -- [dist](./dist) - the packed bundle of the project for use in browser environments. - ---- - -# Usage - -Create API credentials at Binance - -- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) -- [Testnet](https://testnet.binance.vision/). -- [Testnet Futures](testnet.binancefuture.com). -- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. - -### Demo Trading vs Testnet - -Binance offers two testing environments: - -- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. -- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. - -To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. - -## REST API Clients - -There are several REST API modules as there are some differences in each API group. - -1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. -2. `USDMClient` for USD-M futures APIs. -3. `CoinMClient` for COIN-M futures APIs. -4. `PortfolioClient` for Portfolio Margin APIs. - -Vanilla Options is not yet available. Please get in touch if you're looking for this. - -### REST Main Client - -The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: - -- Spot -- Cross & isolated margin -- Convert -- Wallet -- Futures management (transfers & history) -- Sub account management -- Misc transfers -- Auto & dual invest -- Staking -- Mining -- Loans & VIP loans -- Simple Earn -- NFTs -- C2C -- Exchange Link -- Alpha trading - -Refer to the following links for a complete list of available endpoints: - -- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/sieblyio/binance/blob/master/docs/endpointFunctionList.md) -- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) - -Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. - -```javascript -import { MainClient } from 'binance'; - -// or, if you prefer `require()`: -// const { MainClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -const client = new MainClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); - -client - .getAccountTradeList({ symbol: 'BTCUSDT' }) - .then((result) => { - console.log('getAccountTradeList result: ', result); - }) - .catch((err) => { - console.error('getAccountTradeList error: ', err); - }); - -client - .getExchangeInfo() - .then((result) => { - console.log('getExchangeInfo inverse result: ', result); - }) - .catch((err) => { - console.error('getExchangeInfo inverse error: ', err); - }); -``` - -See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. - -### REST USD-M Futures - -Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. - -```javascript -import { USDMClient } from 'binance'; - -// or, if you prefer `require()`: -// const { USDMClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -const client = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); - -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); - -client - .submitNewOrder({ - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - }) - .then((result) => { - console.log('submitNewOrder result: ', result); - }) - .catch((err) => { - console.error('submitNewOrder error: ', err); - }); -``` - -See [usdm-client.ts](./src/usdm-client.ts) for further information. - -### REST COIN-M Futures - -Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. - -```javascript -import { CoinMClient } from 'binance'; - -// or, if you prefer `require()`: -// const { CoinMClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -const client = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); - -client - .getSymbolOrderBookTicker() - .then((result) => { - console.log('getSymbolOrderBookTicker result: ', result); - }) - .catch((err) => { - console.error('getSymbolOrderBookTicker error: ', err); - }); -``` - -See [coinm-client.ts](./src/coinm-client.ts) for further information. - -### REST Portfolio Margin - -Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. - -```javascript -import { PortfolioClient } from 'binance'; - -// or, if you prefer `require()`: -// const { PortfolioClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -const client = new PortfolioClient({ - api_key: API_KEY, - api_secret: API_SECRET, - // Connect to testnet environment - // testnet: true, -}); - -client - .getBalance() - .then((result) => { - console.log('getBalance result: ', result); - }) - .catch((err) => { - console.error('getBalance error: ', err); - }); - -client - .submitNewUMOrder({ - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - }) - .then((result) => { - console.log('submitNewUMOrder result: ', result); - }) - .catch((err) => { - console.error('submitNewUMOrder error: ', err); - }); -``` - -See [portfolio-client.ts](./src/portfolio-client.ts) for further information. - -## WebSockets - -### WebSocket Consumers - -All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. - -The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: - -```javascript -import { WebsocketClient } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketClient } = require('binance'); - -const API_KEY = 'xxx'; -const API_SECRET = 'yyy'; - -/** - * The WebsocketClient will manage individual connections for you, under the hood. - * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. - */ -const wsClient = new WebsocketClient({ - api_key: key, - api_secret: secret, - // Optional: when enabled, the SDK will try to format incoming data into more readable objects. - // Beautified data is emitted via the "formattedMessage" event - beautify: true, - // Disable ping/pong ws heartbeat mechanism (not recommended) - // disableHeartbeat: true, - // Connect to testnet environment - // testnet: true, -}); - -// receive raw events -wsClient.on('message', (data) => { - console.log('raw message received ', JSON.stringify(data, null, 2)); -}); - -// notification when a connection is opened -wsClient.on('open', (data) => { - console.log('connection opened open:', data.wsKey, data.wsUrl); -}); - -// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. -wsClient.on('formattedMessage', (data) => { - console.log('formattedMessage: ', data); -}); - -// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) -wsClient.on('response', (data) => { - console.log('log response: ', JSON.stringify(data, null, 2)); -}); - -// receive notification when a ws connection is reconnecting automatically -wsClient.on('reconnecting', (data) => { - console.log('ws automatically reconnecting.... ', data?.wsKey); -}); - -// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) -wsClient.on('reconnected', (data) => { - console.log('ws has reconnected ', data?.wsKey); -}); - -// Recommended: receive error events (e.g. first reconnection failed) -wsClient.on('exception', (data) => { - console.log('ws saw error ', data?.wsKey); -}); - -/** - * Subscribe to public topics either one at a time or many in an array - */ - -// E.g. one at a time, routed to the coinm futures websockets: -wsClient.subscribe('btcusd@indexPrice', 'coinm'); -wsClient.subscribe('btcusd@miniTicker', 'coinm'); - -// Or send many topics at once to a stream, e.g. the usdm futures stream: -wsClient.subscribe( - ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], - 'usdm', -); - -// spot & margin topics should go to "main" -// (similar how the MainClient is for REST APIs in that product group) -wsClient.subscribe( - [ - // All Market Rolling Window Statistics Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams - '!ticker_1h@arr', - // Individual Symbol Book Ticker Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams - 'btcusdt@bookTicker', - // Average Price - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price - 'btcusdt@avgPrice', - // Partial Book Depth Streams - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams - 'btcusdt@depth10@100ms', - // Diff. Depth Stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream - 'btcusdt@depth', - ], - // Look at the `WS_KEY_URL_MAP` for a list of values here: - // https://github.com/sieblyio/binance/blob/master/src/util/websockets/websocket-util.ts - // "main" connects to wss://stream.binance.com:9443/stream - // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams - 'main', -); - -/** - * For the user data stream, these convenient subscribe methods open a dedicated - * connection with the listen key workflow: - */ - -wsClient.subscribeSpotUserDataStream(); -wsClient.subscribeMarginUserDataStream(); -wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); -wsClient.subscribeUsdFuturesUserDataStream(); -wsClient.subscribePortfolioMarginUserDataStream(); -``` - -See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. - -#### Preserving large integers in WebSocket messages - -By default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`. -If you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`. - -Example using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder: - -```ts -import { WebsocketClient } from 'binance'; - -/** - * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: - * https://github.com/sieblyio/binance/issues/208 - * - * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: - */ -const ws = new WebsocketClient({ - // Default behaviour, if you don't include this: - // customParseJSONFn: (rawEvent) => { - // return JSON.parse(rawEvent); - // }, - - // Or, pre-process the raw event using RegEx, before using the same workflow: - customParseJSONFn: (rawEvent) => { - return JSON.parse( - rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), - ); - }, - - // Or, use a 3rd party library such as json-bigint: - // customParseJSONFn: (rawEvent) => { - // return JSONbig({ storeAsString: true }).parse(rawEvent); - // }, -}); - -ws.on('message', (msg) => { - console.log(msg); -}); - -// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. -// Use a custom replacer or JSONbig.stringify if you need to log/serialize: -// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; -// console.log(JSON.stringify(msg, replacer)); -``` - -### WebSocket API - -Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. - -#### Authentication - -HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. - -This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. - -#### Event Driven API - -The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. - -Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. - -#### Async Await API - -The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). - -It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. - -Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. - -```typescript -import { WebsocketAPIClient } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketAPIClient } = require('binance'); - -/** - * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will - * require each command to be individually signed. - * - * Check the rest-private-ed25519.md in this folder for more guidance - * on preparing this Ed25519 API key. - */ - -const publicKey = `-----BEGIN PUBLIC KEY----- -MCexampleQTxwLU9o= ------END PUBLIC KEY----- -`; - -const privateKey = `-----BEGIN PRIVATE KEY----- -MC4CAQAexamplewqj5CzUuTy1 ------END PRIVATE KEY----- -`; - -// API Key returned by binance, generated using the publicKey (above) via Binance's website -const apiKey = 'TQpJexamplerobdG'; - -// Make an instance of the WS API Client -const wsClient = new WebsocketAPIClient({ - api_key: apiKey, - api_secret: privateKey, - beautify: true, - - // Enforce testnet ws connections, regardless of supplied wsKey - // testnet: true, -}); - -// 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/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow -// wsClient.setTimeOffsetMs(-5000); - -// Optional, see above. Can be used to prepare a connection before sending commands -// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); - -// Make WebSocket API calls, very similar to a REST API: - -wsClient - .getFuturesAccountBalanceV2({ - timestamp: Date.now(), - recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); - -wsClient - .submitNewFuturesOrder('usdm', { - side: 'SELL', - symbol: 'BTCUSDT', - type: 'MARKET', - quantity: 0.001, - timestamp: Date.now(), - // recvWindow: 5000, - }) - .then((result) => { - console.log('getFuturesAccountBalanceV2 result: ', result); - }) - .catch((err) => { - console.error('getFuturesAccountBalanceV2 error: ', err); - }); -``` - ---- - -## Market Maker Endpoints - -Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. - -These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 - -### Using Market Maker Endpoints - -To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): - -#### Market Maker REST API Clients - -```javascript -import { USDMClient, CoinMClient } from 'binance'; - -// USD-M Futures with MM endpoints -const usdmClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); - -// COIN-M Futures with MM endpoints -const coinmClient = new CoinMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` - -#### Market Maker WebSocket Clients - -```javascript -import { WebsocketClient, WebsocketAPIClient } from 'binance'; - -// WebSocket consumer with MM endpoints -const wsClient = new WebsocketClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); - -// WebSocket API client with MM endpoints -const wsApiClient = new WebsocketAPIClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMSubdomain: true, // Enable market maker endpoints -}); -``` - -**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. - -### Best practice - -Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. - -```javascript -import { USDMClient } from 'binance'; - -// MM client for USD-M futures -const futuresMMClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: true, // Use MM endpoints for futures -}); - -// Regular client for USD-M futures -const futuresRegularClient = new USDMClient({ - api_key: API_KEY, - api_secret: API_SECRET, - useMMEndpoints: false, // Use regular endpoints for futures -}); -``` - -## Customise Logging - -Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. - -```javascript -import { WebsocketClient, DefaultLogger } from 'binance'; - -// or, if you prefer `require()`: -// const { WebsocketClient, DefaultLogger } = require('binance'); - -// Enable all logging on the trace level (disabled by default) -DefaultLogger.trace = (...params) => { - console.trace('trace: ', params); -}; - -// Pass the updated logger as the 2nd parameter -const ws = new WebsocketClient( - { - api_key: key, - api_secret: secret, - beautify: true, - }, - DefaultLogger -); - -// Or, create a completely custom logger with the 3 available functions -const customLogger = { - trace: (...params: LogParams): void => { - console.trace(new Date(), params); - }, - info: (...params: LogParams): void => { - console.info(new Date(), params); - }, - error: (...params: LogParams): void => { - console.error(new Date(), params); - }, -} - -// Pass the custom logger as the 2nd parameter -const ws = new WebsocketClient( - { - api_key: key, - api_secret: secret, - beautify: true, - }, - customLogger -); -``` - -## Browser/Frontend 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 crypto-browserify stream-browserify - ``` -2. Add this to your `tsconfig.json` - ```json - { - "compilerOptions": { - "paths": { - "crypto": [ - "./node_modules/crypto-browserify" - ], - "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. - -## 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` -- Sign up with my referral links: - - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 - - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ - - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY - - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 - - - - -### Contributions & Pull Requests - -Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. - -## Used By - -[![Repository Users Preview Image](https://dependents.info/sieblyio/binance/image)](https://github.com/sieblyio/binance/network/dependents) - - - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) - - - -================ -File: src/main-client.ts -================ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { AxiosRequestConfig } from 'axios'; -⋮---- -import { - AmendKeepPriorityParams, - BasicAssetPaginatedParams, - BasicAssetParam, - BasicSymbolParam, - BinanceBaseUrlKey, - CancelOCOParams, - CancelOrderParams, - CoinStartEndLimit, - ExchangeSymbol, - GetAllOrdersParams, - GetOrderParams, - HistoricalTradesParams, - Kline, - KlinesParams, - NewOCOParams, - NewOrderListParams, - OrderBookParams, - OrderIdProperty, - OrderResponseType, - OrderType, - RecentTradesParams, - RowsWithTotal, - SymbolFromPaginatedRequestFromId, - SymbolPrice, -} from './types/shared'; -import { - AcceptQuoteRequestParams, - AccountInfo, - AccountInformation, - ActiveInstitutionalLoanRiskUnit, - AddBSwapLiquidityParams, - AddInstitutionalLoanCollateralAccountParams, - AddIpRestriction, - AdjustCryptoLoanLTVParams, - AdjustCryptoLoanLTVResponse, - AdjustFlexibleCryptoLoanLTVParams, - AdjustFlexibleCryptoLoanLTVResponse, - AggregateTrade, - AlgoOrder, - AllCoinsInformationResponse, - Allocation, - AllocationsParams, - AlphaAggTrade, - AlphaAggTradesParams, - AlphaExchangeInfo, - AlphaFullDepthParams, - AlphaFullDepthResponse, - AlphaKline, - AlphaKlinesParams, - AlphaTicker, - AlphaToken, - ApiKeyBrokerSubAccount, - APIPermissions, - APITradingStatus, - ApplicationStatus, - AssetDetail, - BasicFromPaginatedParams, - BasicFuturesSubAccountParams, - BasicMarginAssetParams, - BasicSubAccount, - BasicTimeRangeParam, - BethRewardsHistory, - BfusdAccountResponse, - BfusdQuotaResponse, - BfusdRateHistoryRow, - BfusdRedeemParams, - BfusdRedeemResponse, - BfusdRedemptionHistoryRow, - BfusdRewardsHistoryRow, - BfusdSubscribeParams, - BfusdSubscribeResponse, - BfusdSubscriptionHistoryRow, - BlockTrade, - BlvtRedemptionRecord, - BlvtSubscriptionRecord, - BlvtUserLimitInfo, - BNBBurnResponse, - BnbTransferParams, - BnsolRateHistoryRecord, - BnsolRewardHistoryRecord, - BorrowCryptoLoanParams, - BorrowCryptoLoanResponse, - BorrowFlexibleLoanParams, - BorrowFlexibleLoanResponse, - BorrowInterestRate, - BrokerCommissionRebate, - BrokerSubAccount, - BrokerSubAccountCoinFuturesCommission, - BrokerSubAccountFuturesCommission, - BrokerSubAccountHistory, - BrokerUniversalTransfer, - BSwapLiquidity, - BSwapOperations, - BSwapOperationsParams, - BUSDConversionRecord, - CancelAlgoOrderResponse, - CancelHashrateResaleConfigParams, - CancelOrderListResult, - CancelSpotAlgoOrderResponse, - CancelSpotOrderResult, - ChangeAutoCompoundStatusParams, - ChangeAutoCompoundStatusResponse, - ChangePermissionApiKeyBrokerSubAccountParams, - ChangePermissionApiKeyBrokerSubAccountResponse, - ChangePlanStatusParams, - ChangePlanStatusResponse, - ChangeSubAccountCoinFuturesCommissionParams, - ChangeSubAccountCommissionParams, - ChangeSubAccountCommissionResponse, - ChangeSubAccountFuturesCommissionParams, - ChangeSubAccountFuturesCommissionResponse, - CheckCollateralRepayRateParams, - CheckCollateralRepayRateResponse, - CheckDualInvestmentAccountsResponse, - CheckVipCollateralAccountParams, - CloseInstitutionalLoanRiskUnitResponse, - CloudMining, - CloudMiningHistoryParams, - CoinMarginedFuturesResponse, - Collateral, - CollateralAssetData, - CollateralRecord, - CommissionRates, - ConvertDustParams, - ConvertibleCoinsParams, - ConvertibleCoinsResponse, - ConvertLimitOpenOrder, - ConvertQuoteRequestParams, - ConvertTransfer, - ConvertTransferResponse, - CreateApiKeyBrokerSubAccountParams, - CreateApiKeyBrokerSubAccountResponse, - CreateBrokerSubAccountParams, - CreateDualTokenGiftCardParams, - CreateGiftCardParams, - CreateInvestmentPlanParams, - CreateInvestmentPlanResponse, - CreateSpecialLowLatencyKeyParams, - CreateSubAccountParams, - CrossMarginFeeData, - CrossMarginTransferHistory, - CurrentAvgPrice, - CustomizeMarginCall, - CustomizeMarginCallParams, - DailyAccountSnapshot, - DailyAccountSnapshotParams, - DelegationHistory, - DelegationHistoryParams, - DeleteApiKeyBrokerSubAccountParams, - DelistScheduleResponse, - DepositAddress, - DepositAddressListParams, - DepositAddressParams, - DepositAddressResponse, - DepositHistory, - DepositHistoryParams, - DualInvestmentPosition, - DualInvestmentProduct, - DustConversion, - DustConvertibleAssetsParams, - DustConvertibleAssetsResponse, - DustConvertParams, - DustInfo, - DustLog, - EditInvestmentPlanParams, - EditInvestmentPlanResponse, - EnableConvertSubAccountParams, - EnableFuturesBrokerSubAccountParams, - EnableFuturesBrokerSubAccountResponse, - EnableMarginApiKeyBrokerSubAccountParams, - EnableMarginBrokerSubAccountParams, - EnableMarginBrokerSubAccountResponse, - EnableOptionsForSubAccountResponse, - EnableOrDisableIPRestrictionForSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountParams, - EnableUniversalTransferApiKeyBrokerSubAccountResponse, - ETHRateHistory, - EthRedemptionHistory, - EthStakingHistory, - ExchangeInfo, - ExchangeInfoParams, - FiatDepositParams, - FiatDepositResponse, - FixedAndActivityProjectParams, - FixedAndActivityProjectPositionParams, - FlexibleCryptoLoanBorrowHistory, - FlexibleLoanAssetData, - FlexibleLoanCollateralAssetData, - FlexibleLoanLiquidationHistoryRecord, - FlexibleLoanLTVAdjustmentHistory, - FlexibleLoanOngoingOrder, - FlexibleRedemptionRecord, - FlexibleRewardsHistory, - FlexibleSubscriptionPreview, - ForceLiquidationRecord, - FundingAsset, - FutureAccountTransfer, - FuturesPositionRisk, - GetAlgoHistoricalOrdersParams, - GetAlgoSubOrdersParams, - GetAlgoSubOrdersResponse, - GetAllConvertPairsParams, - GetApiKeyBrokerSubAccountParams, - GetApplicationStatusParams, - GetAssetParams, - GetBethRewardsHistoryParams, - GetBfusdRateHistoryParams, - GetBfusdRedemptionHistoryParams, - GetBfusdRewardsHistoryParams, - GetBfusdSubscriptionHistoryParams, - GetBlvtRedemptionRecordParams, - GetBlvtSubscriptionRecordParams, - GetBnsolRateHistoryReq, - GetBnsolRewardsHistoryReq, - GetBrokerInfoResponse, - GetBrokerSubAccountDepositHistoryParams, - GetBrokerSubAccountHistoryParams, - GetBrokerSubAccountParams, - GetC2CTradeHistoryParams, - GetC2CTradeHistoryResponse, - GetClosedInstitutionalLoanRiskUnitsParams, - GetClosedInstitutionalLoanRiskUnitsResponse, - GetCollateralAssetDataParams, - GetCollateralRecordParams, - GetConvertBUSDHistoryParams, - GetConvertTradeHistoryParams, - GetCrossMarginTransferHistoryParams, - GetCryptoLoansIncomeHistoryParams, - GetCryptoLoansIncomeHistoryResponse, - GetDualInvestmentPositionsParams, - GetDualInvestmentProductListParams, - GetEarningsListParams, - GetEarningsListResponse, - GetETHRateHistoryParams, - GetEthRedemptionHistoryParams, - GetEthStakingAccountResponse, - GetEthStakingAccountV2Response, - GetEthStakingHistoryParams, - GetEthStakingQuotaResponse, - GetExtraBonusListParams, - GetExtraBonusListResponse, - GetFiatOrderDetailParams, - GetFiatOrderDetailResponse, - GetFiatOrderHistoryParams, - GetFiatOrderHistoryResponse, - GetFiatPaymentsHistoryResponse, - GetFlexibleCryptoLoanBorrowHistoryParams, - GetFlexibleLoanLiquidationHistoryParams, - GetFlexibleLoanLTVAdjustmentHistoryParams, - GetFlexibleLoanOngoingOrdersParams, - GetFlexibleRedemptionRecordParams, - GetFlexibleRewardsHistoryParams, - GetFlexibleSubscriptionPreviewParams, - GetFlexibleSubscriptionRecordParams, - GetFlexibleSubscriptionRecordResponse, - GetForceLiquidationRecordParams, - GetFutureAccountTransferHistoryParams, - GetFuturesLeadTraderStatusResponse, - GetFuturesLeadTradingSymbolWhitelistResponse, - GetFutureTickLevelOrderbookDataLinkParams, - GetHashrateResaleDetailParams, - GetHashrateResaleDetailResponse, - GetHashrateResaleListParams, - GetHashrateResaleListResponse, - GetIndexDetailsResponse, - GetIndexLinkedPlanPositionDetailsResponse, - GetIndexLinkedPlanRebalanceHistoryParams, - GetIndexLinkedPlanRedemptionHistoryParams, - GetInstitutionalLoanBorrowRepayRecordsParams, - GetInstitutionalLoanBorrowRepayRecordsResponse, - GetInstitutionalLoanForceLiquidationParams, - GetInstitutionalLoanForceLiquidationResponse, - GetInstitutionalLoanInterestHistoryParams, - GetInstitutionalLoanMaxBorrowableParams, - GetInstitutionalLoanRiskUnitDetailsParams, - GetLoanableAssetsDataParams, - GetLoanBorrowHistoryParams, - GetLoanCoinPaginatedHistoryParams, - GetLoanLTVAdjustmentHistoryParams, - GetLoanOngoingOrdersParams, - GetLoanRepaymentHistoryParams, - GetLockedRedemptionRecordParams, - GetLockedRewardsHistory, - GetLockedRewardsHistoryParams, - GetLockedSubscriptionPreviewParams, - GetLockedSubscriptionRecordParams, - GetMarginAccountBorrowRepayRecordsParams, - GetMarginCapitalFlowParams, - GetMarginInterestHistoryParams, - GetMarginInterestRebateBalanceRecordsParams, - GetMarginLiquidationLoanRepayHistoryParams, - GetMarginOrderCountUsageParams, - GetMinerDetailsParams, - GetMinerDetailsResponse, - GetMinerListParams, - GetMinerListResponse, - GetMiningAccountEarningParams, - GetMiningAccountEarningResponse, - getMiningAccountsListParams, - getMiningAccountsListResponse, - GetMiningAlgoListResponse, - GetMiningCoinListResponse, - GetNextHourlyInterestRateParams, - GetNftAssetParams, - GetNftDepositHistoryParams, - GetNftTransactionHistoryParams, - GetNftWithdrawHistoryParams, - GetOCOParams, - GetOneTimeTransactionStatusParams, - GetOneTimeTransactionStatusResponse, - GetOrderStatusParams, - GetPayTradeHistoryParams, - GetPlanDetailsParams, - GetPortfolioMarginAssetIndexPriceResponse, - GetPortfolioMarginAssetLeverageResponse, - GetPortfolioMarginProAccountInfoResponse, - GetPortfolioMarginProBankruptcyLoanAmountResponse, - GetPortfolioMarginProCollateralRateResponse, - GetPortfolioMarginProInterestHistoryParams, - GetPortfolioMarginProInterestHistoryResponse, - GetRateHistory, - GetRateHistoryParams, - GetRwusdRateHistoryParams, - GetRwusdRedemptionHistoryParams, - GetRwusdRewardsHistoryParams, - GetRwusdSubscriptionHistoryParams, - GetSmallLiabilityExchangeHistoryParams, - GetSoftStakingProductListParams, - GetSoftStakingProductListResponse, - GetSoftStakingRewardsHistoryParams, - GetSoftStakingRewardsHistoryResponse, - GetSolStakingHistoryReq, - GetSourceAssetListParams, - GetSourceAssetListResponse, - GetSpotAlgoHistoricalOrdersParams, - GetSpotAlgoSubOrdersParams, - GetSpotAlgoSubOrdersResponse, - GetSpotRebateHistoryRecordsParams, - GetSpotRebateHistoryRecordsResponse, - GetStatisticListParams, - GetStatisticListResponse, - GetSubAccountDepositHistoryParams, - GetSubscriptionTransactionHistoryParams, - GetTargetAssetListParams, - GetTargetAssetListResponse, - GetTargetAssetROIParams, - GetTravelRuleDepositHistoryParams, - GetTravelRuleRegionListParams, - GetTravelRuleWithdrawHistoryParams, - GetTravelRuleWithdrawHistoryV2Params, - GetUniversalTransferBrokerParams, - GetVipLoanFixedRateMarketParams, - GetVipLoanOngoingOrdersParams, - GetVipLoanRepaymentHistoryParams, - GetWbethRewardsHistoryResponse, - GetWrapHistoryParams, - HistoricalAlgoOrder, - HistoricalBlockTradesParams, - HistoricalDataLink, - HistoricalSpotAlgoOrder, - IndexLinkedPlanRedemptionRecord, - InstitutionalLoanBorrowParams, - InstitutionalLoanBorrowResponse, - InstitutionalLoanInterestHistoryResponse, - InstitutionalLoanMaxBorrowableResponse, - InstitutionalLoanRepayParams, - InstitutionalLoanRepayResponse, - InstitutionalLoanRiskUnitDetails, - InstitutionalLoanRiskUnitTransferParams, - IsolatedMarginAccountInfo, - IsolatedMarginAccountTransferParams, - IsolatedMarginFeeData, - IsolatedMarginSymbol, - IsolatedMarginTierData, - LeftDailyPurchaseQuotaFlexibleProductResponse, - LiabilityCoinLeverageBracket, - LoanableAssetData, - LoanBorrowHistory, - LoanLTVAdjustmentHistory, - LoanOngoingOrder, - LoanRepaymentHistory, - LockedRedemptionRecord, - LockedSubscriptionPreview, - LockedSubscriptionRecord, - ManagedSubAccountDepositAddress, - ManagedSubAccountDepositAddressParams, - ManagedSubAccountFuturesAssetsResponse, - ManagedSubAccountListParams, - ManagedSubAccountMarginAssetsResponse, - ManagedSubAccountSnapshot, - ManagedSubAccountSnapshotParams, - ManagedSubAccountTransferLogParams, - ManagedSubAccountTransferTTLogParams, - ManagerSubTransferHistoryVos, - ManagerSubUserInfoVo, - ManualLiquidationParams, - ManualLiquidationResponse, - MarginAccountLoanParams, - MarginAccountRecord, - MarginAvailableInventoryResponse, - MarginCapitalFlow, - MarginDelistSchedule, - MarginInterestHistory, - MarginInterestRateHistory, - MarginInterestRebateBalanceRecordsResponse, - MarginInterestRebateBalanceResponse, - MarginLiquidationLoan, - MarginLiquidationLoanRepayHistoryResponse, - MarginLiquidationLoanRepayResponse, - MarginOpenOTOOrderList, - MarginOrderCountUsageResponse, - MarginOTOCOOrder, - MarginOTOOrder, - MarginTransactionResponse, - NewFutureAccountTransferParams, - NewOrderListOPOCOParams, - NewOrderListOPOCOResponse, - NewOrderListOPOParams, - NewOrderListOPOResponse, - NewOrderListOTOCOParams, - NewOrderListOTOCOResponse, - NewOrderListOTOParams, - NewOrderListOTOResponse, - NewSpotOrderParams, - NewSpotSOROrderParams, - NextHourlyInterestRate, - NftAsset, - NftDeposit, - NftTransaction, - NftWithdraw, - OnchainYieldsAccountResponse, - OnchainYieldsLockedPersonalLeftQuotaParams, - OnchainYieldsLockedPersonalLeftQuotaResponse, - OnchainYieldsLockedPositionParams, - OnchainYieldsLockedPositionResponse, - OnchainYieldsLockedProductListParams, - OnchainYieldsLockedProductListResponse, - OnchainYieldsLockedRedeemParams, - OnchainYieldsLockedRedeemResponse, - OnchainYieldsLockedRedemptionRecordParams, - OnchainYieldsLockedRedemptionRecordResponse, - OnchainYieldsLockedRewardsHistoryParams, - OnchainYieldsLockedRewardsHistoryResponse, - OnchainYieldsLockedSetAutoSubscribeParams, - OnchainYieldsLockedSetAutoSubscribeResponse, - OnchainYieldsLockedSetRedeemOptionParams, - OnchainYieldsLockedSetRedeemOptionResponse, - OnchainYieldsLockedSubscribeParams, - OnchainYieldsLockedSubscribeResponse, - OnchainYieldsLockedSubscriptionPreviewParams, - OnchainYieldsLockedSubscriptionPreviewResponse, - OnchainYieldsLockedSubscriptionRecordParams, - OnchainYieldsLockedSubscriptionRecordResponse, - OrderBookResponse, - OrderList, - OrderListResponse, - OrderRateLimitUsage, - OrderResponseTypeFor, - PMProBankruptcyLoanRepaymentHistory, - PMProMintBFUSDParams, - PMProMintBFUSDResponse, - PMProRedeemBFUSDResponse, - PortfolioDeltaModeStatus, - PortfolioMarginMarginCallLevelDeleteResponse, - PortfolioMarginMarginCallLevelGetResponse, - PortfolioMarginMarginCallLevelResponse, - PortfolioMarginProAccountBalance, - PortfolioMarginProSpanAccountInfo, - PreventedMatch, - PreventedMatchesParams, - PurchaseFlexibleProductResponse, - PurchaseRecordParams, - QueryBrokerFuturesCommissionRebateParams, - QueryBrokerSpotCommissionRebateParams, - QueryCrossMarginAccountDetailsParams, - QueryCrossMarginFeeDataParams, - QueryCrossMarginPairResponse, - QueryIsolatedMarginTierDataParams, - QueryMarginAccountAllOCOParams, - QueryMarginAccountTradeListParams, - QueryMarginAssetResponse, - QueryMarginInterestRateHistoryParams, - QueryMarginOpenOTOOrderListsParams, - QueryMarginPriceIndexResponse, - QueryMarginRecordParams, - QueryMaxBorrowResponse, - QueryMaxTransferOutAmountResponse, - QuerySubAccountCoinFuturesCommissionParams, - QuerySubAccountFuturesAssetInfoParams, - QuerySubAccountFuturesCommissionParams, - QuerySubAccountSpotMarginAssetInfoParams, - RawAccountTrade, - RawTrade, - RedeemBlvtParams, - RedeemBlvtResponse, - RedeemEthParams, - RedeemEthResponse, - RedeemGiftCardParams, - RedeemSolResponse, - RemoveBSwapLiquidityParams, - RepayCryptoFlexibleLoanParams, - RepayCryptoFlexibleLoanResponse, - RepayCryptoLoanFlexibleWithCollateralParams, - RepayCryptoLoanFlexibleWithCollateralResponse, - RepayCryptoLoanParams, - RepayCryptoLoanResponse, - RepayMarginLiquidationLoanParams, - ReplaceSpotOrderParams, - ReplaceSpotOrderResultSuccess, - RollingWindowTickerParams, - RwusdAccountResponse, - RwusdQuotaResponse, - RwusdRateHistoryRow, - RwusdRedeemParams, - RwusdRedeemResponse, - RwusdRedemptionHistoryRow, - RwusdRewardsHistoryRow, - RwusdSubscribeParams, - RwusdSubscribeResponse, - RwusdSubscriptionHistoryRow, - SetAutoSubscribeParams, - SetPortfolioMarginMarginCallLevelParams, - SetSoftStakingParams, - SetSoftStakingResponse, - SimpleEarnAccountResponse, - SimpleEarnFlexibleProduct, - SimpleEarnFlexibleProductPositionParams, - SimpleEarnLockedProduct, - SimpleEarnLockedProductPosition, - SimpleEarnLockedProductPositionParams, - SimpleEarnProductListParams, - SimpleEarnRedeemFlexibleProductParams, - SimpleEarnRedeemResponse, - SimpleEarnSubscribeFlexibleProductResponse, - SimpleEarnSubscribeLockedProductResponse, - SimpleEarnSubscribeProductParams, - SmallLiabilityExchangeCoin, - SmallLiabilityExchangeHistory, - SolBoostRewardsHistoryRecord, - SolBoostRewardsHistoryReq, - SolRedemptionHistoryRecord, - SolStakingAccount, - SolStakingHistoryRecord, - SolStakingQuota, - SOROrderResponseFull, - SORTestOrderResponse, - SpecialLowLatencyKeyInfo, - SpecialLowLatencyKeyResponse, - SpotAlgoOrder, - SpotAmendKeepPriorityResult, - SpotAssetTag, - SpotAssetTagsParams, - SpotExecutionRulesParams, - SpotExecutionRulesResponse, - SpotOrder, - SpotReferencePriceCalculationResponse, - SpotReferencePriceResult, - StakingBasicParams, - StakingHistory, - StakingHistoryParams, - StakingPersonalLeftQuota, - StakingProduct, - StakingProductPosition, - StakingProductType, - SubAccountAddOrDeleteIPList, - SubAccountAssetDetails, - SubAccountAssets, - SubAccountAssetsParams, - SubaccountBalances, - SubAccountBrokerMarginAsset, - SubaccountBrokerSpotAsset, - SubAccountCOINMDetail, - SubAccountCOINMPositionRisk, - SubAccountCOINMSummary, - SubAccountDeposit, - SubAccountDepositAddress, - SubAccountDepositAddressParams, - SubAccountDepositHistoryList, - SubAccountDepositHistoryParams, - SubAccountEnableFutures, - SubAccountEnableLeverageToken, - SubAccountEnableMargin, - SubAccountEnableOrDisableIPRestriction, - SubAccountFuturesAccountDetail, - SubAccountFuturesAccountSummary, - SubAccountFuturesAssetTransfer, - SubAccountFuturesAssetTransferHistory, - SubAccountFuturesAssetTransferHistoryParams, - SubAccountFuturesAssetTransferParams, - SubAccountListParams, - SubAccountListResponse, - SubAccountMarginAccountDetail, - SubAccountMovePosition, - SubAccountMovePositionHistory, - SubAccountMovePositionHistoryParams, - SubAccountMovePositionParams, - SubAccountsMarginAccountSummary, - SubAccountSpotAssetsSummary, - SubAccountSpotAssetsSummaryParams, - SubAccountSpotAssetTransferHistory, - SubAccountSpotAssetTransferHistoryParams, - SubAccountStatus, - SubAccountSummaryOnFuturesAccountV2Params, - SubAccountTransactionStatistics, - SubAccountTransfer, - SubAccountTransferHistory, - SubAccountTransferHistoryParams, - SubAccountTransferParams, - SubAccountTransferToMasterParams, - SubAccountTransferToSameMasterParams, - SubAccountUniversalTransfer, - SubAccountUniversalTransferHistoryParams, - SubAccountUniversalTransferHistoryResponse, - SubAccountUniversalTransferParams, - SubAccountUSDMDetail, - SubAccountUSDMPositionRisk, - SubAccountUSDMSummary, - SubmitConvertLimitOrderParams, - SubmitDepositCreditParams, - SubmitDepositCreditResponse, - SubmitHashrateResaleParams, - SubmitIndexLinkedPlanRedemptionParams, - SubmitMarginOTOCOOrderParams, - SubmitMarginOTOOrderParams, - SubmitOneTimeTransactionParams, - SubmitOneTimeTransactionResponse, - SubmitSpotTwapNewOrderParams, - SubmitSpotTwapNewOrderResponse, - SubmitTravelRuleDepositQuestionnaireParams, - SubmitTravelRuleDepositQuestionnaireResponse, - SubmitTwapNewOrderParams, - SubmitTwapNewOrderResponse, - SubmitVpNewOrderParams, - SubmitVpNewOrderResponse, - SubscribeBlvtParams, - SubscribeBlvtResponse, - SubscribeDualInvestmentProductParams, - SubscribeDualInvestmentProductResponse, - SubscribeEthStakingV2Response, - SubscribeSolStakingResponse, - SwitchPortfolioDeltaModeParams, - SymbolOrderBookTicker, - SymbolTradeFee, - SystemStatusResponse, - TargetAssetROI, - Ticker24hrResponse, - ToggleBNBBurnParams, - TradingDayTickerArray, - TradingDayTickerFull, - TradingDayTickerMini, - TradingDayTickerParams, - TradingDayTickerSingle, - TransferBrokerSubAccount, - TransferBrokerSubAccountParams, - TravelRuleCountryListResponse, - TravelRuleDepositHistoryRecord, - TravelRuleRegionListResponse, - TravelRuleWithdrawHistoryRecord, - UniversalTransferBrokerParams, - UniversalTransferHistoryParams, - UniversalTransferParams, - UpdateIpRestrictionForSubApiKey, - UsdtMarginedFuturesResponse, - UserAsset, - VASPInfo, - VipCollateralAccount, - VipLoanAccruedInterestParams, - VipLoanAccruedInterestRecord, - VipLoanBorrowParams, - VipLoanBorrowResponse, - VipLoanFixedRateBorrowParams, - VipLoanFixedRateBorrowResponse, - VipLoanFixedRateMarketRecord, - VipLoanInterestRateHistoryParams, - VipLoanInterestRateRecord, - VipLoanRenewParams, - VipLoanRenewResponse, - VipLoanRepaymentHistory, - VipLoanRepayParams, - VipLoanRepayResponse, - VipOngoingOrder, - VirtualSubAccount, - WalletBalance, - WithdrawAddress, - WithdrawAssetsFromManagedSubAccountParams, - WithdrawFiatParams, - WithdrawHistory, - WithdrawHistoryParams, - WithdrawParams, - WithdrawTravelRuleParams, - WrapBethResponse, - WrapHistory, -} from './types/spot'; -import BaseRestClient from './util/BaseRestClient'; +export interface WsMessageFuturesUserDataAccountUpdateRaw extends WsSharedBase { + e: 'ACCOUNT_UPDATE'; + E: number; + T: number; + a: { + m: AccountUpdateEventType; + S?: string; // symbol; only when m is FUNDING_FEE + B: WsMessageFuturesAccountUpdateBalanceRaw[]; + P: WsMessageFuturesAccountUpdatePositionRaw[]; + }; +} +⋮---- +S?: string; // symbol; only when m is FUNDING_FEE +⋮---- +export interface WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw + extends WsSharedBase { + e: 'CONDITIONAL_ORDER_TRIGGER_REJECT'; + E: number; + T: number; + or: { + s: string; + i: number; + r: string; + }; +} +⋮---- +export interface WsMessageFuturesUserDataOrderTradeUpdateEventRaw + extends WsSharedBase { + e: 'ORDER_TRADE_UPDATE'; + E: number; + T: number; + o: { + s: string; + c: string; + S: OrderSide; + o: FuturesOrderType; + f: OrderTimeInForce; + q: numberInString; + p: numberInString; + ap: numberInString; + sp: numberInString; + x: OrderExecutionType; + X: OrderStatus; + i: number; + l: numberInString; + z: numberInString; + L: numberInString; + N: string; + n: numberInString; + T: numberInString; + t: number; + b: numberInString; + a: numberInString; + m: boolean; + R: boolean; + wt: WorkingType; + ot: FuturesOrderType; + ps: PositionSide; + cp: boolean; + AP: numberInString; + cr: numberInString; + rp: numberInString; + pP: boolean; // ignore + si: numberInString; // ignore + ss: numberInString; // ignore + V: string; + pm: string; + gtd: number; + er?: string; // Order expire reason (available effective 2025-10-23) + M?: string; // modifyId from modify request; only when x is AMENDMENT + }; +} +⋮---- +pP: boolean; // ignore +si: numberInString; // ignore +ss: numberInString; // ignore +⋮---- +er?: string; // Order expire reason (available effective 2025-10-23) +M?: string; // modifyId from modify request; only when x is AMENDMENT +⋮---- +export interface WsMessageFuturesUserDataAlgoUpdateRaw extends WsSharedBase { + e: 'ALGO_UPDATE'; + E: number; + T: number; + o: { + caid: string; + aid: number; + at: FuturesAlgoOrderType; + o: FuturesAlgoConditionalOrderTypes; + s: string; + S: OrderSide; + ps: PositionSide; + f: OrderTimeInForce; + q: numberInString; + X: FuturesAlgoOrderStatus; + ai: string; + tp: numberInString; + p: numberInString; + V: SelfTradePreventionMode; + wt: WorkingType; + pm: PriceMatchMode; + cp: boolean; + pP: boolean; + R: boolean; + tt: number; + gtd: number; + ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now + // As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). + }; +} +⋮---- +ia?: boolean; // whether trailing stop algo has activated; placeholder, always false for now +// As of 2026-08-21 this is fully active for trailing stop orders (false then true while status stays NEW). +⋮---- +export interface WsMessageFuturesUserDataTradeLiteEventRaw + extends WsSharedBase { + e: 'TRADE_LITE'; // Event Type + E: number; // Event Time + T: number; // Transaction Time + s: string; // Symbol + q: string; // Original Quantity + p: string; // Original Price + m: boolean; // Is this trade the maker side? + c: string; // Client Order Id + S: 'BUY' | 'SELL'; // Side + L: string; // Last Filled Price + l: string; // Order Last Filled Quantity + t: number; // Trade Id + i: number; // Order Id +} +⋮---- +e: 'TRADE_LITE'; // Event Type +E: number; // Event Time +T: number; // Transaction Time +s: string; // Symbol +q: string; // Original Quantity +p: string; // Original Price +m: boolean; // Is this trade the maker side? +c: string; // Client Order Id +S: 'BUY' | 'SELL'; // Side +L: string; // Last Filled Price +l: string; // Order Last Filled Quantity +t: number; // Trade Id +i: number; // Order Id +⋮---- +export interface WsMessageFuturesUserDataAccountConfigUpdateEventRaw + extends WsSharedBase { + e: 'ACCOUNT_CONFIG_UPDATE'; + E: number; + T: number; + ac?: { + s: string; + l: number; + }; + ai?: { + j: boolean; + }; +} +⋮---- +export interface WsMessageIndexPriceUpdateEventRaw extends WsSharedBase { + e: 'indexPriceUpdate'; + E: number; + i?: string; + s?: string; + p: numberInString; +} +⋮---- +export interface WsMessageMarkPriceUpdateEventRaw extends WsSharedBase { + e: 'markPriceUpdate'; + E: number; + s: string; + p: string; + /** Mark price moving average (USDⓈ-M mark price stream). */ + ap?: string; + P: string; + i: string; + r: string; + T: number; + st?: FuturesMarketSymbolType; +} +⋮---- +/** Mark price moving average (USDⓈ-M mark price stream). */ +⋮---- +export interface WsMessageForceOrderRaw extends WsSharedBase { + e: 'forceOrder'; + E: number; + o: { + s: string; + S: string; + o: string; + f: string; + q: string; + p: string; + ap: string; + X: string; + l: string; + z: string; + T: number; + }; + st?: FuturesMarketSymbolType; +} +⋮---- +export interface WsMessageFuturesUserDataStrategyUpdateRaw + extends WsSharedBase { + e: 'STRATEGY_UPDATE'; // Event Type + T: number; // Transaction Time + E: number; // Event Time + su: { + si: number; // Strategy ID + st: string; // Strategy Type + ss: string; // Strategy Status + s: string; // Symbol + ut: number; // Update Time + c: number; // opCode + }; +} +⋮---- +e: 'STRATEGY_UPDATE'; // Event Type +T: number; // Transaction Time +E: number; // Event Time +⋮---- +si: number; // Strategy ID +st: string; // Strategy Type +ss: string; // Strategy Status +s: string; // Symbol +ut: number; // Update Time +c: number; // opCode +⋮---- +export interface WsMessageFuturesUserDataGridUpdateRaw extends WsSharedBase { + e: 'GRID_UPDATE'; // Event Type + T: number; // Transaction Time + E: number; // Event Time + gu: { + si: number; // Strategy ID + st: string; // Strategy Type + ss: string; // Strategy Status + s: string; // Symbol + r: numberInString; // Realized PNL + up: numberInString; // Unmatched Average Price + uq: numberInString; // Unmatched Qty + uf: numberInString; // Unmatched Fee + mp: numberInString; // Matched PNL + ut: number; // Update Time + }; +} +⋮---- +e: 'GRID_UPDATE'; // Event Type +T: number; // Transaction Time +E: number; // Event Time +⋮---- +si: number; // Strategy ID +st: string; // Strategy Type +ss: string; // Strategy Status +s: string; // Symbol +r: numberInString; // Realized PNL +up: numberInString; // Unmatched Average Price +uq: numberInString; // Unmatched Qty +uf: numberInString; // Unmatched Fee +mp: numberInString; // Matched PNL +ut: number; // Update Time +⋮---- +export interface WsMessageFuturesUserDataContractInfoRaw extends WsSharedBase { + e: 'contractInfo'; // Event Type + E: number; // Event Time + s: string; // Symbol + ps: string; // Pair + ct: string; // Contract type + dt: number; // Delivery date time + ot: number; // onboard date time + cs: string; // Contract status + bks: { + bs: number; // Notional bracket + bnf: number; // Floor notional of this bracket + bnc: number; // Cap notional of this bracket + mmr: number; // Maintenance ratio for this bracket + cf: number; // Auxiliary number for quick calculation + mi: number; // Min leverage for this bracket + ma: number; // Max leverage for this bracket + }[]; + st?: FuturesMarketSymbolType; +} +⋮---- +e: 'contractInfo'; // Event Type +E: number; // Event Time +s: string; // Symbol +ps: string; // Pair +ct: string; // Contract type +dt: number; // Delivery date time +ot: number; // onboard date time +cs: string; // Contract status +⋮---- +bs: number; // Notional bracket +bnf: number; // Floor notional of this bracket +bnc: number; // Cap notional of this bracket +mmr: number; // Maintenance ratio for this bracket +cf: number; // Auxiliary number for quick calculation +mi: number; // Min leverage for this bracket +ma: number; // Max leverage for this bracket +⋮---- +export type WsRawSpotUserDataEventRaw = + | WsMessageSpotUserDataExecutionReportEventRaw + | WsMessageSpotOutboundAccountPositionRaw + | WsMessageSpotBalanceUpdateRaw + | WsMessageSpotUserDataListStatusEventRaw; +⋮---- +export type WsMessageFuturesUserDataEventRaw = + | WsMessageFuturesUserDataAccountUpdateRaw + | WsMessageFuturesUserDataListenKeyExpiredRaw + | WsMessageFuturesUserDataMarginCallRaw + | WsMessageFuturesUserDataOrderTradeUpdateEventRaw + | WsMessageFuturesUserDataAlgoUpdateRaw + | WsMessageFuturesUserDataAccountConfigUpdateEventRaw + | WsMessageFuturesUserDataCondOrderTriggerRejectEventRaw + | WsMessageFuturesUserDataTradeLiteEventRaw + | WsMessageFuturesUserDataStrategyUpdateRaw + | WsMessageFuturesUserDataGridUpdateRaw + | WsMessageFuturesUserDataContractInfoRaw; +⋮---- +export type WsUserDataEventsRaw = + | WsRawSpotUserDataEventRaw + | WsMessageFuturesUserDataEventRaw + | WsMessagePortfolioMarginProAccountUpdateRaw; +⋮---- +export type WsRawMessage = + | WsEventStreamTerminatedRaw + | WsMessageWsapiServerShutdownRaw + | WsUserDataEventsRaw + | WsMessageKlineRaw + | WsMessageAggTradeRaw + | WsMessageTradeRaw + | WsMessageBlockTradeRaw + | WsMessage24hrMiniTickerRaw + | WsMessage24hrMiniTickerRaw[] + | WsMessage24hrTickerRaw + | WsMessage24hrTickerRaw[] + | WsMessageRollingWindowTickerRaw[] + | WsMessageBookTickerEventRaw + | WsMessagePartialBookDepthEventRaw + | WsMessageDiffBookDepthEventRaw + | WsMessageForceOrderRaw + | WsMessageIndexPriceUpdateEventRaw; + +================ +File: docs/BINANCE_SDK_QUICKSTART_GUIDE.md +================ + +# Binance SDK Quickstart Guide + + +> [!TIP] +> This guide can be read in tutorial format on the Siebly Website: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) + + +This guide walks through key pieces of a Binance REST API, WebSocket & WebSocket API integration using [`binance`](https://www.npmjs.com/package/binance), the Binance JavaScript and TypeScript SDK by Siebly.io. It also covers HTTP, HTTPS, and SOCKS proxy configuration for REST API calls, streams, and user-data helpers. + +The SDK handles request building and connectivity for you, including request signing, WebSocket management, healthchecks, heartbeats, product-specific user data startup, listen-key refreshes where Binance still uses them, resubscribe behavior, and WebSocket API response mapping so your code can stay focused on the workflow you are automating. This guide will walk you through installation and client selection, then moves through public calls, private auth, REST API calls, streams, user data, and the WebSocket API. + +**Key links** + +- Binance JavaScript SDK by Siebly: [`binance`](https://www.npmjs.com/package/binance) +- GitHub Repository: [`sieblyio/binance`](https://github.com/sieblyio/binance) +- SDK function-endpoint map: [Binance JavaScript Endpoint Reference](./endpointFunctionList.md) +- REST API examples: [Binance SDK REST API examples](../examples/Rest/Spot/rest-spot-public.ts) +- WebSocket examples: [Binance SDK WebSocket examples](../examples/WebSockets/Public/ws-public.ts) +- More SDKs: [Siebly.io](https://siebly.io) + +--- + + +## Why use the SDK + +A stable Binance integration is more than a handful of HTTP requests. Binance splits behavior across product groups, transports, key types, and environments: + +- Spot, Margin, Wallet, Convert, Earn, and Sub-Account APIs live behind the main REST API client, but not all of them share the same endpoint prefix or permission model. +- Some of these product groups expect API calls to reach different subdomains. +- USD-M Futures and COIN-M Futures have separate REST API clients, symbols, endpoint prefixes, and WebSocket endpoints. +- Both have their own subdomains as well. +- Portfolio Margin uses a dedicated REST API client and its own account model. +- Public streams, private user data streams, and WebSocket API commands are different flows. +- Private REST API and WebSocket API requests must be signed. +- User data streams can involve listen keys, WebSocket API subscriptions, token refreshes, and reconnect handling. + +Most of that work is handled for you, while the grouping & naming stays close to Binance's API naming. The SDK gives you dedicated REST API clients for the major product groups, `WebsocketClient` for streaming, `WebsocketAPIClient` for awaitable WebSocket API requests. It also includes TypeScript definitions, ESM/CJS support, proxy support, and optional response beautification. + +--- + + +## Install and API keys + +If you do not have Node.js installed yet, install it first. The SDK is published to both [GitHub](https://github.com/sieblyio/binance) and [npm](https://www.npmjs.com/package/binance), and can therefore be installed with your favourite Node.js compatible package manager. + +Install the SDK with npm: + +```bash +npm install binance +``` + +Or use another npm-compatible package manager: + +```bash +pnpm install binance +yarn add binance +``` + +Create API keys from the relevant Binance page: + +- Binance live API keys: [Binance API Management](https://www.binance.com/en/my/settings/api-management) +- Binance Spot testnet: [Spot Test Network](https://testnet.binance.vision/) +- Binance Futures testnet: [Futures Testnet](https://testnet.binancefuture.com/) +- Binance demo trading: [Binance Demo Trading](https://demo.binance.com/) + +> Always use the minimum permissions needed for your scenario. Trading does not require withdrawal permissions. Analytics does not require trading permissions. +> Always require strict IP whitelisting for any API keys that you create. + +The main auth and environment rules are: + +- Public market data does not require API keys. +- Private REST APIs require `api_key` and `api_secret`. +- Live, testnet, and demo trading credentials are separate, as they are separate environments. +- API permissions must match the product and action your code is using. +- HMAC keys are the common API key + secret flow. These are the "system generated" API keys, selected by default when creating new API keys for Binance. +- RSA and Ed25519 keys use self-generated private keys. +- Ed25519 is recommended for latency-sensitive integrations with the WebSocket API, as this enables session-based WebSocket API authentication, instead of having to authenticate every request. + +All supported key types use the same SDK constructor shape. The SDK will automatically detect your key type and adjust request building and signing automatically: + +```typescript +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` + +For HMAC, `api_secret` is your Binance API secret. For RSA or Ed25519, `api_secret` is your PEM private key. + +Typical environment variables: + +```bash +export BINANCE_API_KEY='your-api-key' +export BINANCE_API_SECRET='your-api-secret-or-private-key' +``` + +If you are only testing public endpoints, you do not need any keys at all. + +--- + + +## Products and clients + +Binance is not one single API. The SDK splits API clients around Binance's product groups: + +| Product group | API client | Common usage | +| -------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------- | +| REST API: Spot, Margin, Wallet, Convert, Earn, Sub-accounts, Broker, Alpha | `MainClient` | Spot trading, account data, wallet flows, margin trading, transfers, savings/earn, sub-account management | +| REST API: USD-M Futures | `USDMClient` | USDT/USDC margined futures market data, account data, positions, orders | +| REST API: COIN-M Futures | `CoinMClient` | Coin-margined futures market data, account data, positions, orders | +| REST API: Portfolio Margin | `PortfolioClient` | Portfolio Margin account, UM/CM/margin orders, balances, positions | +| WebSocket streams | `WebsocketClient` | Public market data streams and private user data streams | +| WebSocket API | `WebsocketAPIClient` | REST API-like Spot and Futures commands over persistent WebSocket API connections | + +As a rule of thumb: + +- Use `MainClient` when the Binance docs path starts with `api/` or `sapi/`, including Spot and many account/wallet APIs. +- Use `USDMClient` when the Binance docs path starts with `fapi/`. +- Use `CoinMClient` when the Binance docs path starts with `dapi/`. +- Use `PortfolioClient` when the Binance docs path starts with `papi/`. +- Use `WebsocketClient` when you want to subscribe to streams and receive events. +- Use `WebsocketAPIClient` when you want to send commands over WebSocket and await responses like REST API calls. + +For a complete method map, see [docs/endpointFunctionList.md](./endpointFunctionList.md). If any endpoints or properties seem to be missing, please open an issue on GitHub and we'll look into it. Targeted PRs are also welcome. + + +### REST API, streams, listen keys, and WebSocket API + +Binance uses several related but different integration patterns. It helps to keep them separate: + +| Flow | SDK surface | Best for | What the SDK handles | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| REST API | `MainClient`, `USDMClient`, `CoinMClient`, `PortfolioClient` | Request/response calls, broad API coverage, occasional reads/writes, fallback reconciliation | Base URLs, request signing, timestamps, response parsing, errors | +| Public WebSocket streams | `WebsocketClient.subscribe(...)` | Live market data such as trades, klines, tickers, order book updates | Connection routing, subscribe requests, heartbeats, reconnects, resubscribe | +| Listen-key user data streams | `WebsocketClient.subscribeUsdFuturesUserDataStream()`, `subscribeCoinFuturesUserDataStream()`, portfolio helpers | Private account events where Binance still uses listen keys, especially Futures and Portfolio Margin streams | Listen-key creation, keepalive, refresh, reconnect, stream teardown | +| WebSocket API user data | `WebsocketAPIClient.subscribeUserDataStream(...)` | Spot user data and some newer private stream flows without the old Spot listen-key workflow | WebSocket API auth, subscription command, reconnect/resubscribe behavior | +| WebSocket API commands | `WebsocketAPIClient` methods or `WebsocketClient.sendWSAPIRequest(...)` | Lower-latency request/response commands over an already-open WebSocket, such as order tests, order placement, cancellation, status, account reads | WebSocket connection persistence, auth, request IDs, promise resolution, response/error correlation | + +The WebSocket API uses WebSocket transport for request/response commands such as order tests, order placement, cancellation, status, and account reads. Since much of this surface is a lower-latency alternative to REST, we've introduced the promise-driven `WebsocketAPIClient`. It lets you call a function, send a command over WS, and await the matched response without managing asynchronous WebSocket messaging or connection lifecycle details yourself. + +```typescript +const result = await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), +}); +``` + +Use the REST API when you want maximum endpoint coverage, simple one-off calls, or reconciliation after reconnects. Use the WebSocket API when you want persistent connectivity, lower request overhead, WebSocket API-only features, or a promise-driven command path that can share the same event-driven architecture as your streams. With Ed25519 keys, authentication can happen once per WebSocket API connection, which can improve latency in mid-to-high frequency systems. Removing repeated authentication work from every request can save time cumulatively. + +--- + + +## Start building: first calls + +If you only want the fastest path to a working integration, start here. + +### 1. First Spot REST API request + + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient(); + +async function main() { + const serverTime = await client.getServerTime(); + const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); + const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); + const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); + const candles = await client.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 5, + }); + + console.log({ + serverTime, + symbol: exchangeInfo.symbols?.[0]?.symbol, + ticker, + orderBook, + candles, + }); +} + +main().catch(console.error); +``` + +That confirms public Spot REST API access is wired correctly. + +See also: [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) + +### 2. First public Spot WebSocket stream + + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ + beautify: true, +}); + +ws.on('open', (data) => console.log('connected', data.wsKey, data.wsUrl)); +ws.on('message', (data) => console.log('raw message', JSON.stringify(data))); +ws.on('formattedMessage', (data) => console.log('formatted', data)); +ws.on('response', (data) => console.log('response', JSON.stringify(data))); +ws.on('reconnecting', (data) => console.log('reconnecting', data?.wsKey)); +ws.on('reconnected', (data) => console.log('reconnected', data?.wsKey)); +ws.on('exception', console.error); + +ws.subscribe(['btcusdt@trade', 'btcusdt@bookTicker'], WS_KEY_MAP.main); +``` + +That gives you a live public Spot stream without any API keys. + +See also: [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) + +### 3. First private Spot user data stream + +For Spot user data streams, prefer the WebSocket API user data flow. It avoids the older Spot listen-key flow and keeps the stream on a managed WebSocket API connection. + + +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +wsApi.getWSClient().on('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +wsApi.getWSClient().on('open', (data) => { + console.log('ws api open: ', data.wsKey); +}); + +wsApi.getWSClient().on('formattedUserDataMessage', (data) => { + console.log('on formattedUserDataMessage: ', data); +}); + +wsApi.getWSClient().on('exception', console.error); + +async function main() { + await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); +} + +main().catch(console.error); +``` + +The SDK handles authentication and resubscribe behavior for the WebSocket API connection. With Ed25519 keys it can authenticate the WebSocket API session once. With HMAC or RSA keys it signs private WebSocket API commands individually, although that primarily matters in the context of sending regular commands (such as order submissions) via WebSocket API. + +See also: [Spot user data stream over WebSocket API](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) + +### 4. First Spot order over REST API + + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +async function placeOrder() { + const orderRequest = { + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + newOrderRespType: 'FULL', + } as const; + + // Validate the request without sending it to the matching engine. + await client.testNewOrder(orderRequest); + + // Remove this comment when you are ready to place a real order. + // const result = await client.submitNewOrder(orderRequest); + // console.log(result); +} + +placeOrder().catch(console.error); +``` + +Use `testNewOrder()` when you want to validate the request shape and signature without placing a live Spot order. Use `submitNewOrder()` only when you are ready to send the order. + +See also: [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) + +### 5. First USD-M Futures order + +For strategy testing, `demoTrading: true` is usually more realistic than testnet because demo trading uses live market data with simulated trading. + + +```typescript +import { USDMClient } from 'binance'; + +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); + +async function placeFuturesOrder() { + const account = await client.getAccountInformation(); + console.log('demo futures account can trade:', account.canTrade); + + const result = await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: 0.001, + }); + + console.log(result); +} + +placeFuturesOrder().catch(console.error); +``` + +See also: [USD-M Futures demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) + +### 6. First WebSocket API request + +The WebSocket API lets you send requests over a persistent WebSocket connection and await responses, similar to REST API calls. This is useful for lower-latency workflows and for WebSocket API-only features. + + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +async function main() { + const time = await wsApi.getSpotServerTime(); + + const orderTest = await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), + }); + + console.log({ time, orderTest }); +} + +main() + .catch(console.error) + .finally(() => wsApi.disconnectAll()); +``` + +See also: [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) + +--- + + +## Spot, Margin, and Wallet REST API + +Most Binance integrations start with `MainClient`. It covers Spot trading and many account APIs under Binance's main REST API families. + +### Create a public `MainClient` + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient(); +``` + +Public calls do not require keys. + +### Create a private `MainClient` + +If you plan on making private API calls, include API keys when creating the client: + +```typescript +import { MainClient } from 'binance'; + +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautifyResponses: true, +}); +``` + +Private REST API methods are signed automatically. You do not need to manually add timestamps, signatures, or `X-MBX-APIKEY` headers. + +### Common public Spot market data calls + +```typescript +const serverTime = await client.getServerTime(); +const ping = await client.testConnectivity(); +const exchangeInfo = await client.getExchangeInfo({ symbol: 'BTCUSDT' }); +const orderBook = await client.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); +const recentTrades = await client.getRecentTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const aggregateTrades = await client.getAggregateTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const candles = await client.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 10, +}); +const averagePrice = await client.getAvgPrice({ symbol: 'BTCUSDT' }); +const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +const bookTicker = await client.getSymbolOrderBookTicker({ + symbol: 'BTCUSDT', +}); +``` + +### Common private Spot account and order calls + +```typescript +const account = await client.getAccountInformation(); +const balances = await client.getBalances(); +const accountInfo = await client.getAccountInfo(); +const openOrders = await client.getOpenOrders({ symbol: 'BTCUSDT' }); +const allOrders = await client.getAllOrders({ symbol: 'BTCUSDT', limit: 10 }); +const myTrades = await client.getAccountTradeList({ + symbol: 'BTCUSDT', + limit: 10, +}); +const tradeFee = await client.getTradeFee({ symbol: 'BTCUSDT' }); +const apiPermissions = await client.getApiKeyPermissions(); +``` + +See also: + +- [Spot public REST API example](../examples/Rest/Spot/rest-spot-public.ts) +- [Spot exchange info example](../examples/Rest/Spot/rest-spot-exchange-info.ts) +- [Spot private trading example](../examples/Rest/Spot/rest-spot-private-trade.ts) +- [Spot private miscellaneous account example](../examples/Rest/Spot/rest-spot-private-misc.ts) + +### Spot order examples + +Market order: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'MARKET', + quantity: 0.001, + newOrderRespType: 'FULL', +}); +``` + +Limit order: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` + +Limit maker order: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT_MAKER', + quantity: 0.001, + price: 10000, +}); +``` + +Test an order without sending it: + +```typescript +await client.testNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` + +Cancel an order: + +```typescript +await client.cancelOrder({ + symbol: 'BTCUSDT', + orderId: 123456789, +}); +``` + +**Custom client order IDs** + +You do not always need to set a custom client order ID. Most of the time, the cleanest option is to send the order without `newClientOrderId` or the equivalent custom ID field for that endpoint, and let the SDK handle the request normally: + +```typescript +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', +}); +``` + +If your system needs to know the client order ID before the order is sent, but the ID does not need to carry any meaning, ask the REST API client to generate one: + +```typescript +const newClientOrderId = client.generateNewOrderId(); + +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + newClientOrderId, +}); +``` + +`generateNewOrderId()` is available on every REST API client, including `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. The client already knows its product group, so the generated ID uses the right Binance-compatible prefix. + +If you want to include a small piece of your own context in the client order ID, such as a take-profit marker or strategy step, use the product prefix from the client and append your suffix: + +```typescript +const prefix = client.getOrderIdPrefix(); +const suffix = `tp1_${Date.now()}`; +const newClientOrderId = `${prefix}${suffix}`; +const validBinanceClientOrderId = /^[.A-Z:/a-z0-9_-]{1,32}$/; + +if (!validBinanceClientOrderId.test(newClientOrderId)) { + throw new Error(`Invalid Binance client order ID: ${newClientOrderId}`); +} + +await client.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + newClientOrderId, +}); +``` + +The prefix returned by `getOrderIdPrefix()` is 10 characters long. For endpoints with Binance's common 32-character client order ID limit, that leaves 22 characters for your own suffix. Keep the suffix short and use only characters Binance allows for that field. + +If you need to track richer metadata than will comfortably fit in the client order ID, do not try to squeeze it into these custom order ID fields. Instead, generate an ID with `client.generateNewOrderId()` before placing the order, use that value as the key for your own metadata, and store the metadata locally or in an external store such as Redis. Later, when order updates arrive through REST API polling or user data events, you can look up the richer context using the seen Binance client ID value like a primary key, while keeping the exchange-facing ID short and valid. + +Regular Spot, Futures, and Portfolio orders usually use `newClientOrderId`; newer Futures algo or conditional flows may use `clientAlgoId` instead. Treat both fields, and any similar Binance custom order ID field, as the same kind of SDK-prefixed client ID. The same rule applies: omit it unless you need it, use `generateNewOrderId()` when any unique ID is fine, and use `getOrderIdPrefix()` when building your own value. Do not bypass the SDK prefix, length, or character checks just because the endpoint uses a different field name. + +### Margin REST API examples + +Margin APIs also live on `MainClient`. + +```typescript +const marginAssets = await client.getAllMarginAssets(); +const marginPairs = await client.getAllCrossMarginPairs(); +const priceIndex = await client.queryMarginPriceIndex({ symbol: 'BTCUSDT' }); + +const crossMarginAccount = await client.queryCrossMarginAccountDetails(); +const isolatedMarginAccount = await client.getIsolatedMarginAccountInfo({ + symbols: 'BTCUSDT', +}); +const openMarginOrders = await client.queryMarginAccountOpenOrders({ + symbol: 'BTCUSDT', +}); +``` + +Margin order: + +```typescript +await client.marginAccountNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + isIsolated: 'FALSE', + sideEffectType: 'NO_SIDE_EFFECT', +}); +``` + +Borrow or repay: + +```typescript +await client.submitMarginAccountBorrowRepay({ + asset: 'USDT', + symbol: 'BTCUSDT', + amount: 25, + type: 'BORROW', + isIsolated: 'FALSE', +}); +``` + +Margin permissions, collateral, interest, and liquidation behavior are account-specific. Keep margin trading code separate from ordinary Spot trading code even though both use `MainClient`. + +### Wallet and transfer examples + +Wallet and transfer APIs also live on `MainClient`. + +```typescript +const balances = await client.getBalances(); +const depositAddress = await client.getDepositAddress({ + coin: 'USDT', + network: 'ETH', +}); +const depositHistory = await client.getDepositHistory({ coin: 'USDT' }); +const withdrawHistory = await client.getWithdrawHistory({ coin: 'USDT' }); + +const transferHistory = await client.getUniversalTransferHistory({ + type: 'MAIN_UMFUTURE', +}); +``` + +Withdrawal calls are intentionally not shown as a quickstart. Use withdrawal permissions only when your system truly needs them, and isolate those keys from trading keys. + +--- + + +## Futures REST API + +Binance Futures are split into USD-M and COIN-M product groups. Use the dedicated client for the product you are integrating. + +### Create public Futures clients + +```typescript +import { CoinMClient, USDMClient } from 'binance'; + +const usdm = new USDMClient(); +const coinm = new CoinMClient(); +``` + +Public futures market data does not require keys. + +### Create private Futures clients + +```typescript +import { CoinMClient, USDMClient } from 'binance'; + +const usdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +const coinm = new CoinMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` + +Use `demoTrading: true` for Binance demo trading or `testnet: true` for testnet where supported: + +```typescript +const demoUsdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); + +const testnetUsdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + testnet: true, +}); +``` + +Do not enable both `demoTrading` and `testnet` on the same client. + +### Common public USD-M Futures market data calls + +```typescript +const serverTime = await usdm.getServerTime(); +const exchangeInfo = await usdm.getExchangeInfo(); +const orderBook = await usdm.getOrderBook({ symbol: 'BTCUSDT', limit: 10 }); +const recentTrades = await usdm.getRecentTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const candles = await usdm.getKlines({ + symbol: 'BTCUSDT', + interval: '1m', + limit: 10, +}); +const markPrice = await usdm.getMarkPrice({ symbol: 'BTCUSDT' }); +const fundingHistory = await usdm.getFundingRateHistory({ + symbol: 'BTCUSDT', + limit: 10, +}); +const ticker = await usdm.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +``` + +### Common public COIN-M Futures market data calls + +```typescript +const serverTime = await coinm.getServerTime(); +const exchangeInfo = await coinm.getExchangeInfo(); +const orderBook = await coinm.getOrderBook({ + symbol: 'BTCUSD_PERP', + limit: 10, +}); +const candles = await coinm.getKlines({ + symbol: 'BTCUSD_PERP', + interval: '1m', + limit: 10, +}); +const markPrice = await coinm.getMarkPrice({ symbol: 'BTCUSD_PERP' }); +const ticker = await coinm.getSymbolPriceTicker({ symbol: 'BTCUSD_PERP' }); +``` + +See also: + +- [USD-M public REST API example](../examples/Rest/Futures/rest-usdm-public.ts) +- [USD-M demo trading example](../examples/Rest/Futures/rest-usdm-demo.ts) +- [USD-M testnet example](../examples/Rest/Futures/rest-usdm-testnet.ts) + +### Common private Futures account calls + +```typescript +const balance = await usdm.getBalance(); +const account = await usdm.getAccountInformation(); +const positions = await usdm.getPositions({ symbol: 'BTCUSDT' }); +const openOrders = await usdm.getAllOpenOrders({ symbol: 'BTCUSDT' }); +const tradeHistory = await usdm.getAccountTrades({ + symbol: 'BTCUSDT', + limit: 10, +}); +const income = await usdm.getIncomeHistory({ + symbol: 'BTCUSDT', + limit: 10, +}); +``` + +### Futures order examples + +Market order: + +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: 0.001, +}); +``` + +Limit order: + +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', +}); +``` + +Reduce-only limit order: + +```typescript +await usdm.submitNewOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + reduceOnly: 'true', +}); +``` + +Batch order management: + +```typescript +await usdm.submitMultipleOrders([ + { + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: 0.001, + price: 10000, + timeInForce: 'GTC', + }, + { + symbol: 'BTCUSDT', + side: 'SELL', + type: 'LIMIT', + quantity: 0.001, + price: 13000, + timeInForce: 'GTC', + }, +]); +``` + +See also: + +- [USD-M order example](../examples/Rest/Futures/rest-usdm-order.ts) +- [USD-M stop-loss order example](../examples/Rest/Futures/rest-usdm-order-sl.ts) +- [USD-M bracket order example](../examples/Rest/Futures/rest-future-bracket-order.ts) + +--- + + +## Portfolio Margin REST API + +Portfolio Margin has its own account model and a dedicated `PortfolioClient`. + +### Create a Portfolio Margin client + +```typescript +import { PortfolioClient } from 'binance'; + +const portfolio = new PortfolioClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); +``` + +### Common Portfolio Margin calls + +```typescript +const ping = await portfolio.testConnectivity(); +const serverTime = await portfolio.getServerTime(); +const balance = await portfolio.getBalance(); +const account = await portfolio.getAccountInfo(); +const umPositions = await portfolio.getUMPosition({ symbol: 'BTCUSDT' }); +const cmPositions = await portfolio.getCMPosition({ pair: 'BTCUSD' }); +const umOpenOrders = await portfolio.getAllUMOpenOrders({ + symbol: 'BTCUSDT', +}); +const marginOpenOrders = await portfolio.getMarginOpenOrders({ + symbol: 'BTCUSDT', +}); +``` + +Portfolio Margin order examples: + +```typescript +await portfolio.submitNewUMOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', +}); + +await portfolio.submitNewCMOrder({ + symbol: 'BTCUSD_PERP', + side: 'SELL', + type: 'MARKET', + quantity: '1', +}); + +await portfolio.submitNewMarginOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'MARKET', + quantity: '0.001', + sideEffectType: 'NO_SIDE_EFFECT', +}); +``` + +See also: + +- [Portfolio Margin public REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-public.ts) +- [Portfolio Margin private REST API example](../examples/Rest/Portfolio%20Margin/rest-portfoliomargin-private.ts) + +--- + + +## WebSocket Streams + +Use `WebsocketClient` when you want event-driven updates instead of polling the REST API. It is the shared client for public market streams and for the product areas where Binance still uses listen-key style user data streams. + +The workflow is simple: create a client, add event handlers, provide API keys if you need private user data, and subscribe to the streams you want. The SDK opens the correct Binance endpoint, applies proxy settings if configured, fetches and refreshes listen keys where required, monitors heartbeats, reconnects stale sockets, and resubscribes cached topics after reconnect. + +### Common `WebsocketClient` events + +| Event | Meaning | +| -------------------------- | --------------------------------------------------------------- | +| `open` | Connection established | +| `message` | Raw streaming data received | +| `formattedMessage` | Beautified public stream data when `beautify: true` | +| `formattedUserDataMessage` | Beautified private user data stream event when `beautify: true` | +| `response` | Subscribe, unsubscribe, auth, or WebSocket API acknowledgement | +| `reconnecting` | Connection dropped and retrying | +| `reconnected` | Connection restored and subscriptions resynced | +| `close` | Socket closed | +| `authenticated` | WebSocket API session authentication succeeded | +| `exception` | Errors and unexpected conditions | + +### Understanding `WS_KEY_MAP` + +[`WS_KEY_MAP`](/reference/glossary#ws-key) tells the SDK which Binance WebSocket endpoint family to use. This matters because Spot, USD-M Futures, COIN-M Futures, Options, Portfolio Margin, and WebSocket API traffic do not all live on the same endpoint. + +Common `WS_KEY_MAP` entries: + +| Key | Use | +| ---------------------------- | ----------------------------------------------------------------------- | +| `main` | Spot, margin, and isolated margin market data streams | +| `main2` | Alternate Spot stream port | +| `main3` | Spot market-data-only stream endpoint | +| `mainWSAPI` | Spot and margin WebSocket API | +| `mainWSAPITestnet` | Spot WebSocket API testnet | +| `marginUserData` | Margin user data over WebSocket API listen-token flow | +| `marginRiskUserData` | Cross-margin risk data stream | +| `usdmPublic` | USD-M high-frequency public market data, such as book and depth streams | +| `usdmMarket` | USD-M regular market data, such as trades, klines, tickers, mark price | +| `usdmPrivate` | USD-M private user data stream endpoint | +| `usdmWSAPI` | USD-M Futures WebSocket API | +| `coinm` | COIN-M market data and user data stream endpoint | +| `coinmWSAPI` | COIN-M Futures WebSocket API | +| `eoptions` | European Options WebSocket streams | +| `portfolioMarginUserData` | Portfolio Margin user data stream | +| `portfolioMarginProUserData` | Portfolio Margin Pro user data stream | +| `alpha` | Alpha market data streams | + +These keys act like connection IDs. The SDK uses them to track connection state, cached subscriptions, reconnect behavior, and endpoint-specific routing. + +### Public Spot WebSocket topics + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ beautify: true }); + +ws.on('formattedMessage', (data) => console.log(data)); +ws.on('exception', console.error); + +ws.subscribe( + [ + 'btcusdt@trade', + 'btcusdt@aggTrade', + 'btcusdt@kline_1m', + 'btcusdt@bookTicker', + 'btcusdt@depth10@100ms', + ], + WS_KEY_MAP.main, +); +``` + +See also: + +- [General public WebSocket example](../examples/WebSockets/Public/ws-public.ts) +- [Spot order book WebSocket example](../examples/WebSockets/Public/ws-public-spot-orderbook.ts) +- [Spot trades WebSocket example](../examples/WebSockets/Public/ws-public-spot-trades.ts) + +### Public USD-M Futures WebSocket topics + +USD-M Futures WebSockets have dedicated endpoint families for high-frequency public data and regular market data. + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ beautify: true }); + +ws.on('formattedMessage', (data) => console.log(data)); +ws.on('exception', console.error); + +// High-frequency public data: book ticker and order book depth. +ws.subscribe( + ['btcusdt@bookTicker', 'btcusdt@depth10@100ms', 'btcusdt@depth@100ms'], + WS_KEY_MAP.usdmPublic, +); + +// Regular market data: trades, mark price, klines, mini tickers, liquidations. +ws.subscribe(['btcusdt@aggTrade', 'btcusdt@markPrice', 'btcusdt@kline_1m'], WS_KEY_MAP.usdmMarket); +``` + +See also: + +- [USD-M public WebSocket example](https://siebly.io/examples/Binance/WebSockets/Public/ws-public) +- [USD-M funding stream example](../examples/WebSockets/Public/ws-public-usdm-funding.ts) + +### Public COIN-M Futures WebSocket topics + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ beautify: true }); + +ws.on('message', (data) => console.log(JSON.stringify(data))); +ws.on('exception', console.error); + +ws.subscribe( + ['btcusd_perp@aggTrade', 'btcusd_perp@markPrice', 'btcusd_perp@kline_1m'], + WS_KEY_MAP.coinm, +); +``` + +COIN-M symbols and stream names are not the same as Spot or USD-M symbols. Treat symbols as product-specific strings. + +--- + + +## User Data Streams + +User data streams are how Binance pushes private account events: order updates, execution updates, balance changes, position changes, margin events, and listen-key or subscription expiry events. + +Binance uses two patterns for these streams: WebSocket API user data subscriptions and listen-key user data streams. The SDK supports both; the product group determines which path you should use. + +For either pattern, listen for the WebSocket lifecycle events as well as account events. The event names are `reconnecting` and `reconnected`. `reconnecting` fires when the SDK starts replacing a dropped connection; `reconnected` fires after the replacement connection is open. Both include the [`wsKey`](/reference/glossary#ws-key), which tells you which connection was affected. For user data streams, `reconnected` is the right place to reconcile private state through the REST API in case account events were missed while the socket was down. + +With `WebsocketAPIClient`, attach those handlers to `wsApi.getWSClient()`. With `WebsocketClient`, attach them directly to the client. + +### Preferred Spot user data stream with `WebsocketAPIClient` + +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +const wsClient = wsApi.getWSClient(); + +// raw websocket event, unformatted +wsClient.on('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +// formatted websocket event +wsClient.on('formattedMessage', (data) => { + console.log('on formattedMessage: ', data); +}); + +// reconnection has started +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('spot user data reconnecting', wsKey); +}); + +// reconnection has completed +wsClient.on('reconnected', ({ wsKey }) => { + console.log('spot user data reconnected', wsKey); + // Fetch account state, open orders, or recent fills here if needed. +}); + +wsClient.on('exception', console.error); + +await wsApi.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI); +``` + +Binance announced deprecation of the old listenKey workflow for Spot and Margin user data streams on April 7, 2025. From February 20, 2026 at 07:00 UTC, the old Spot `POST /api/v3/userDataStream` path returns `410 Gone`; use the WebSocket API user data stream instead. At the time of writing, Spot and Margin are the affected user data stream families. Futures and Portfolio Margin streams still use their existing listenKey-backed workflows. For the migration timeline and JavaScript fix, see [Binance User Data Stream 410 Gone: Fix Spot listenKey in JavaScript](/blog/binance-user-data-stream-410-gone-listenkey-javascript). + +### Margin user data stream with `WebsocketAPIClient` + +```typescript +import { WebsocketAPIClient, WS_KEY_MAP } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +const wsClient = wsApi.getWSClient(); + +// raw websocket event, unformatted +wsClient.on('message', (data) => { + console.log('on message event: ', data.wsKey); +}); + +// formatted websocket event +wsClient.on('formattedMessage', (data) => { + console.log('on formattedMessage: ', data); +}); + +// reconnection has started +wsClient.on('reconnecting', ({ wsKey }) => { + console.log('spot user data reconnecting', wsKey); +}); + +// reconnection has completed +wsClient.on('reconnected', ({ wsKey }) => { + console.log('spot user data reconnected', wsKey); + // Fetch account state, open orders, or recent fills here if needed. +}); + +await wsApi.subscribeUserDataStream(WS_KEY_MAP.marginUserData); +``` + +For margin, the SDK handles the listen-token workflow used by Binance's margin WebSocket API user data endpoint. + +### Futures user data streams with `WebsocketClient` + +Futures user data streams are conveniently available through `WebsocketClient` in the [Binance JavaScript SDK](https://siebly.io/sdk/binance/javascript). Both USD-M and COIN-M Futures user data streams on Binance follow a listenKey mechanic. The SDK automates the life cycle and maintenance of this listenKey for you. Request the subscription and handle incoming events, as shown in the following example: + +```typescript +import { WebsocketClient } from 'binance'; + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +ws.on('formattedUserDataMessage', (data) => { + console.log('futures account event', data); +}); + +ws.on('reconnecting', ({ wsKey }) => { + console.log('futures user data reconnecting', wsKey); +}); + +ws.on('reconnected', ({ wsKey }) => { + console.log('futures user data reconnected', wsKey); + // Fetch positions, balances, open orders, or fills here if needed. +}); + +ws.on('exception', console.error); + +await ws.subscribeUsdFuturesUserDataStream(); +// await ws.subscribeCoinFuturesUserDataStream(); +``` + +The SDK will fetch the listen key, keep it alive, refresh it when needed, reconnect after network issues, and resubscribe where possible. + +### Portfolio Margin user data stream + +```typescript +import { WebsocketClient, WS_KEY_MAP } from 'binance'; + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, +}); + +ws.on('formattedUserDataMessage', (data) => { + console.log('portfolio margin event', data); +}); + +ws.on('reconnecting', ({ wsKey }) => { + console.log('portfolio margin user data reconnecting', wsKey); +}); + +ws.on('reconnected', ({ wsKey }) => { + console.log('portfolio margin user data reconnected', wsKey); +}); + +ws.on('exception', console.error); + +await ws.subscribePortfolioMarginUserDataStream(WS_KEY_MAP.portfolioMarginUserData); +``` + +See also: + +- [User data connection safety example]() +- [Listen-key user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-listenkey.ts>) +- [WebSocket API user data example](<../examples/WebSockets/Private(userdata)/ws-userdata-wsapi.ts>) + +--- + + +## WebSocket API + +Binance's WebSocket API is a request/response API over a persistent WebSocket connection. It is useful when you want lower request overhead than REST API calls, or when a Binance feature is exposed through the WebSocket API flow. + +`WebsocketAPIClient` wraps that in a promise-driven interface: call a method, await a promise, receive the response, and let the SDK manage the underlying WebSocket connection. + +### Authentication + +The SDK supports HMAC, RSA, and Ed25519 keys: + +- HMAC: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. +- RSA: supported for REST API and WebSocket API, but WebSocket API private commands are signed individually. +- Ed25519: recommended for WebSocket API because the SDK can authenticate the WebSocket API session once and then send private commands without signing every command. + +If your `api_secret` contains a PEM private key, the SDK automatically detects whether it should use RSA or Ed25519 signing. + +See also: + +- [Ed25519 auth example](../examples/auth/rest-private-ed25519.md) +- [RSA auth example](../examples/auth/rest-private-rsa.md) + +### Spot examples + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +const exchangeInfo = await wsApi.getSpotExchangeInfo({ + symbol: 'BTCUSDT', +}); + +const orderBook = await wsApi.getSpotOrderBook({ + symbol: 'BTCUSDT', + limit: 10, +}); + +const account = await wsApi.getSpotAccountInformation({ + timestamp: Date.now(), +}); + +await wsApi.testSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', + timestamp: Date.now(), +}); +``` + +Submit a Spot order over the WebSocket API: + +```typescript +await wsApi.submitNewSpotOrder({ + symbol: 'BTCUSDT', + side: 'BUY', + type: 'LIMIT', + quantity: '0.001', + price: '10000', + timeInForce: 'GTC', +}); +``` + +### Futures examples + +```typescript +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, +}); + +const book = await wsApi.getFuturesOrderBook({ + symbol: 'BTCUSDT', + limit: 10, +}); + +const balance = await wsApi.getFuturesAccountBalance('usdm', { + timestamp: Date.now(), +}); + +await wsApi.submitNewFuturesOrder('usdm', { + symbol: 'BTCUSDT', + side: 'SELL', + type: 'MARKET', + quantity: '0.001', + timestamp: Date.now(), +}); +``` + +See also: + +- [WebSocket API client example](../examples/WebSockets/WS-API/ws-api-client.ts) +- [Raw WebSocket API promises example](../examples/WebSockets/WS-API/ws-api-raw-promises.ts) + +--- + + +## Environments and Special Endpoints + +### Demo trading + +Demo trading uses real market data with simulated trading. For strategy testing, this is usually more useful than testnet. + +```typescript +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + demoTrading: true, +}); +``` + +Demo trading is supported by SDK options for REST API and WebSocket clients where Binance provides demo endpoints. + +### Testnet + +Testnet uses separate credentials and simulated market conditions. + +```typescript +const client = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + testnet: true, +}); +``` + +Use testnet for endpoint wiring and permission checks. Do not use testnet market behavior as evidence that a live strategy is profitable or safe. + +### Market maker endpoints + +Binance provides market maker endpoints for eligible futures users. If you qualify and need those endpoints, enable them with `useMMSubdomain: true`. + +```typescript +const usdm = new USDMClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + useMMSubdomain: true, +}); + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + useMMSubdomain: true, +}); +``` + +Market maker endpoints are for supported futures products. They are not a general Spot endpoint override and are not available on testnet. + +--- + + +## Proxies for REST API and WebSocket + +Use a proxy when the process needs a fixed egress IP, must cross an approved corporate network, or has a controlled network failover path. A proxy does not select a Binance product, enable a market-maker endpoint, change account eligibility, or replace the `testnet` and `demoTrading` options. + +The broader [Using proxy with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) article covers the shared constructor pattern. The Binance examples below also cover the extra REST API request used by listen-key and listen-token helpers. + +Proxy agents are a Node.js networking feature. Browser applications cannot select a raw socket agent. + +### HTTP or HTTPS proxy + +Install the agent: + +```bash +npm install binance https-proxy-agent +``` + +Set `BINANCE_PROXY_URL` to the full proxy URL, including URL-encoded credentials when required. + +This public check sends one Spot REST API call and one Spot stream through the same proxy: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; + +const proxyUrl = process.env.BINANCE_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_PROXY_URL before running this example.'); +} + +const proxyAgent = new HttpsProxyAgent(proxyUrl); + +const rest = new MainClient( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through proxy:', wsKey); +}); +ws.on('formattedMessage', (event) => { + console.log('stream update', event); +}); +ws.on('exception', console.error); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through proxy:', serverTime); + + ws.subscribe(['btcusdt@trade'], WS_KEY_MAP.main); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +REST API networking options belong in the second constructor argument for `MainClient`, `USDMClient`, `CoinMClient`, and `PortfolioClient`. + +- `httpsAgent` sends the HTTPS request through the agent. +- `proxy: false` prevents Axios from applying another proxy configuration on top of that agent. +- `wsOptions.agent` controls the WebSocket connection. + +Public streams, normal WebSocket API commands, and the current Spot WebSocket API user-data subscription only use the socket path. Those workflows need `wsOptions.agent`, but do not make an auxiliary REST API request. + +### Listen-key and listen-token helpers through a proxy + +Some user-data helpers use two network paths. The SDK opens the WebSocket through `wsOptions.agent`, then uses REST API calls to create or renew a listen key or token through `requestOptions`. + +This example authenticates a USD-M Futures user-data stream without placing an order: + + + +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { WebsocketClient } from 'binance'; + +const proxyUrl = process.env.BINANCE_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_PROXY_URL before running this example.'); +} + +const proxyAgent = new HttpsProxyAgent(proxyUrl); + +const ws = new WebsocketClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + wsOptions: { + agent: proxyAgent, + }, + requestOptions: { + httpsAgent: proxyAgent, + proxy: false, + }, +}); + +ws.on('open', ({ wsKey }) => { + console.log('user-data socket connected:', wsKey); +}); +ws.on('formattedUserDataMessage', (event) => { + console.log('user-data event', event); +}); +ws.on('exception', console.error); + +async function main() { + await ws.subscribeUsdFuturesUserDataStream(); + console.log('USD-M Futures user-data stream is ready'); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +Use both settings for the legacy Spot listen-key helpers, Margin listen-token or listen-key helpers, USD-M and COIN-M user-data helpers, and Portfolio Margin user-data helpers. The same rule applies when `WebsocketAPIClient.subscribeUserDataStream(...)` falls back to one of those helpers. + +Ordinary `WebsocketAPIClient` request and order methods send authentication and commands over the socket. They only need `wsOptions.agent`. The preferred Spot WebSocket API user-data subscription also stays on the socket. + +### SOCKS5 proxy + +Install the SOCKS agent: + +```bash +npm install binance socks-proxy-agent +``` + +Use `SocksProxyAgent` in the same REST API and WebSocket positions: + + + +```typescript +import { MainClient, WebsocketClient, WS_KEY_MAP } from 'binance'; +import { SocksProxyAgent } from 'socks-proxy-agent'; + +const proxyUrl = process.env.BINANCE_SOCKS_PROXY_URL; + +if (!proxyUrl) { + throw new Error('Set BINANCE_SOCKS_PROXY_URL before running this example.'); +} + +const proxyAgent = new SocksProxyAgent(proxyUrl); + +const rest = new MainClient( + {}, + { + httpsAgent: proxyAgent, + proxy: false, + }, +); + +const ws = new WebsocketClient({ + wsOptions: { + agent: proxyAgent, + }, +}); + +async function main() { + const serverTime = await rest.getServerTime(); + console.log('REST API connected through SOCKS5:', serverTime); + + ws.subscribe(['btcusdt@bookTicker'], WS_KEY_MAP.main); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); + +main().catch(console.error); +``` + +See also: + +- [SOCKS WebSocket proxy example](../examples/WebSockets/Misc/ws-proxy-socks.ts) +- [REST API and WebSocket proxy test configuration](../test/proxy.util.ts) + +### Proxy checks + +- Keep proxy URLs and credentials in environment variables or a secret manager. +- URL-encode usernames and passwords when constructing a proxy URL from separate values. +- Make sure the proxy egress IP matches the Binance API key's IP whitelist. +- Test a public REST API call and public WebSocket subscription before private authentication. +- Confirm that every listen-key or listen-token REST API call uses the same intended network path as its socket. +- Measure request, connection, and reconnect latency through the proxy. +- Treat repeated HTTP 407 responses, TLS errors, and WebSocket reconnect loops as network failures. +- Keep the host clock synchronized. Change `recvWindow` only after measuring timestamp failures and proxy latency. +- The SDK does not rotate proxy endpoints. Handle endpoint selection outside the client when rotation is required. + +--- + + +## Production Notes + +Before a Binance integration trades unattended, these are the parts worth making explicit. + +### 1. Roll out in layers + +Move from public reads to private actions one layer at a time: + +1. Public REST APIs +2. Public WebSockets +3. Private REST API account reads +4. Private account/user data streams +5. Order validation +6. Tiny demo or live trading tests + +For Futures, prefer demo trading before live trading if it fits your setup. + +### 2. Reconnect, then backfill + +Listen for `reconnecting` and `reconnected`. A dropped WebSocket connection is a normal production condition, especially during volatility or scheduled exchange disconnects. + +If your system uses WebSockets for account or market state, a reconnect should usually trigger a REST API backfill: + +1. Pause risky order actions when `reconnecting` fires. +2. On `reconnected`, query the REST API for account state, orders, fills, positions, and any market state you depend on. +3. Reconcile internal state. +4. React to any discrepancies in internal vs exchange state, as needed. +5. Resume normal processing. + +### 3. Keep credentials scoped + +Live, demo trading, Spot testnet, and Futures testnet credentials are different. Keep them separate in your secrets manager and deployment configuration. + +Use the minimum permissions needed for each key. A market-data key should not be able to trade. A trading key should not have withdrawal permissions. Do not put live secrets in frontend code. Make use of IP whitelisting for any API keys. These must be protected, treat them like passwords. + +### 4. Keep streams and commands separate + +Use `WebsocketClient` for streams. Use `WebsocketAPIClient` for commands you want to await. They share WebSocket infrastructure, but they solve different problems. + +### 5. Treat symbols and order IDs as product-specific state + +Spot, USD-M Futures, COIN-M Futures, Options, and Portfolio Margin do not all use the same symbol conventions: + +- Spot: `BTCUSDT` +- USD-M Futures: `BTCUSDT` +- COIN-M Futures: `BTCUSD_PERP` +- Stream names are usually lowercase, such as `btcusdt@trade`. Refer to the examples and/or exchange API docs for exact stream names. + +Client order IDs deserve the same care. If you do not need a custom client order ID, omit it. If your strategy relies on idempotency, retries, or reconciliation, generate an ID before sending the order and persist it using the restClient.generateNewOrderId() method. If you build your own value, keep the SDK's product prefix in place (query it using restClient.getOrderIdPrefix()) and stay within Binance's length and character constraints. + +### 6. Watch clocks and rate limits + +Private Binance requests are timestamp-sensitive. Keep your system clock synced and set `recvWindow` intentionally: + +```typescript +const client = new MainClient({ + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + recvWindow: 5000, +}); + +await client.fetchLatencySummary(); + +// For WebSocket API clients: +wsApi.setTimeOffsetMs(-500); +``` + +The REST API client also tracks Binance rate-limit headers it sees: + +```typescript +const ticker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' }); +console.log(ticker); + +console.log(client.getRateLimitStates()); +``` + +If you see timestamp errors, fix system clock sync first. If you see rate-limit pressure, reduce polling, batch where the API allows it, and design around Binance's documented request weights. + +For more guidance on resolving timestamp & recvWindow issues, refer to the following guidance: +https://github.com/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow + +### 7. Logging and large integers + +If you want SDK logs in your own monitoring stack, pass a logger: + +```typescript +import { DefaultLogger, WebsocketClient } from 'binance'; + +const customLogger: typeof DefaultLogger = { + ...DefaultLogger, + trace: () => {}, + info: (...params) => console.info(new Date(), ...params), + error: (...params) => console.error(new Date(), ...params), +}; + +const ws = new WebsocketClient( + { + api_key: process.env.BINANCE_API_KEY!, + api_secret: process.env.BINANCE_API_SECRET!, + beautify: true, + }, + customLogger, +); +``` + +JavaScript cannot precisely represent integers above `Number.MAX_SAFE_INTEGER`. If you need to preserve very large order IDs from WebSocket messages, provide a custom parser: + +```typescript +import { WebsocketClient } from 'binance'; + +const ws = new WebsocketClient({ + customParseJSONFn: (rawEvent) => { + return JSON.parse(rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"')); + }, +}); +``` + +See also: [custom parser example](../examples/WebSockets/Misc/ws-custom-parser.ts) + +--- + + +## FAQ + +**Which REST API client should I use?** + +Use `MainClient` for Spot, margin, wallet, Convert, Earn, sub-account, and many account APIs. Use `USDMClient` for USD-M Futures. Use `CoinMClient` for COIN-M Futures. Use `PortfolioClient` for Portfolio Margin. + +**Do I need API keys for public market data?** + +No. Public REST API market data and public WebSocket market data do not require API keys. + +**Can I use one Binance API key for every product group?** + +Sometimes, but only when the key belongs to the right environment and has the required product permissions enabled. Keep live, demo, and testnet credentials separate. Also keep high-risk permissions, especially withdrawals, separate from ordinary trading keys. + +**What is the difference between HMAC, RSA, and Ed25519?** + +HMAC is the standard API key + secret flow. RSA and Ed25519 use self-generated private keys. The SDK detects PEM private keys automatically when they are passed as `api_secret`. Ed25519 is recommended for latency-sensitive WebSocket API usage because it supports WebSocket API session authentication. + +**Why both `WebsocketClient` and `WebsocketAPIClient`?** + +- `WebsocketClient` is for subscriptions and streaming topics. +- `WebsocketAPIClient` is for commands over Binance's WebSocket API. Think "REST API" but over persistent WebSockets. + +**Should I use listen keys for Spot user data?** + +Use `WebsocketAPIClient.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI)` for Spot user data. Binance retired the older Spot listen-key workflow, so JavaScript apps should not start new Spot user data streams with `POST /api/v3/userDataStream`. + +**What happens if a WebSocket connection drops?** + +The SDK supports reconnect and resubscribe flows. Listen for `reconnecting` and `reconnected`. Use `reconnected` as a trigger to reconcile state through the REST API before resuming risky trading actions. + +**Should I use demo trading or testnet?** + +Use demo trading when you want simulated trading with real market data. Use testnet for API wiring, endpoint behavior, and permission checks. Do not treat testnet market behavior as representative of live market behavior. + +**Can I use this Binance API SDK in TypeScript projects?** + +Yes. The package is TypeScript-first and publishes type declarations. + +**Do I need TypeScript to use this JavaScript Binance SDK?** + +No. Pure JavaScript projects can use this SDK too. Type declarations are included and will help your IDE, but TypeScript is not required. + +**Can I use this package in both ESM and CommonJS projects?** + +Yes. The package supports both ESM-style imports and CommonJS `require()`. + +**Does this guide cover every SDK method?** + +No. This guide covers the common first steps and production concerns. For full method coverage, see: + +- [Binance JavaScript endpoint reference](./endpointFunctionList.md) +- [Binance SDK examples](../examples) +- [Binance SDK source on GitHub](https://github.com/sieblyio/binance) + +--- + + +## Next steps + +If you want to learn more about integrating with Binance APIs and WebSockets: + +- Explore the [Binance JavaScript examples on GitHub](../examples) +- Review the full endpoint list: [Binance JavaScript endpoint reference](./endpointFunctionList.md) +- Check the Binance JavaScript SDK on npm: [`binance`](https://www.npmjs.com/package/binance) +- Browse the source code of the Binance JavaScript SDK on GitHub: [`sieblyio/binance`](https://github.com/sieblyio/binance) +- Review auth examples: [Ed25519](../examples/auth/rest-private-ed25519.md) and [RSA](../examples/auth/rest-private-rsa.md) +- Explore the wider SDK ecosystem: [Siebly.io](https://siebly.io) + +================ +File: src/types/websockets/ws-api-requests.ts +================ +import { + FuturesAlgoConditionalOrderTypes, + FuturesAlgoOrderType, + FuturesOrderType, + PositionSide, + PriceMatchMode, + WorkingType, +} from '../futures'; +import { + BooleanString, + KlineInterval, + numberInString, + OrderResponseType, + OrderSide, + OrderTimeInForce, + OrderType, + SelfTradePreventionMode, +} from '../shared'; +⋮---- +/** + * Simple request params with timestamp (required) & recv window (optional) + */ +export type WSAPIRecvWindowTimestamp = { + recvWindow?: number; + timestamp: number; +}; +⋮---- +/** + * + * Authentication request types + * + */ +export interface WSAPISessionLogonRequest { + timestamp: number; +} +⋮---- +/** + * + * General request types + * + */ +export interface WSAPIExchangeInfoRequest { + symbol?: string; + symbols?: string[]; + permissions?: string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} +⋮---- +/** + * + * Market data request types + * + */ +⋮---- +export interface WSAPIOrderBookRequest { + symbol: string; + limit?: number; + symbolStatus?: string; +} +⋮---- +export interface WSAPITradesRecentRequest { + symbol: string; + limit?: number; +} +⋮---- +export interface WSAPITradesHistoricalRequest { + symbol: string; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIBlockTradesHistoricalRequest { + symbol: string; + fromId: number; + limit?: number; +} +⋮---- +export interface WSAPITradesAggregateRequest { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIKlinesRequest { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} +⋮---- +export interface WSAPIAvgPriceRequest { + symbol: string; +} +⋮---- +/** + * Query execution rules (e.g. PRICE_RANGE). Only one of symbol, symbols, or symbolStatus per request. + */ +export interface WSAPIExecutionRulesRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +} +⋮---- +export interface WSAPIReferencePriceRequest { + symbol: string; +} +⋮---- +export interface WSAPIReferencePriceCalculationRequest { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITicker24hrRequest { + symbol?: string; + symbols?: string[]; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerTradingDayRequest { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerRequest { + symbol?: string; + symbols?: string[]; + windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} +⋮---- +windowSize?: string; // '1m', '2m' ... '59m', '1h', '2h' ... '23h', '1d', '2d' ... '7d' +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerPriceRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} +⋮---- +/** + * Symbol for single symbol, or symbols for multiple symbols + */ +export interface WSAPITickerBookRequest { + symbol?: string; + symbols?: string[]; + symbolStatus?: string; +} +⋮---- +/** + * + * Account request types - Spot + * + */ +⋮---- +export interface WSAPIAllOrdersRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIAllOrderListsRequest { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyTradesRequest { + symbol: string; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyPreventedMatchesRequest { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} +⋮---- +export interface WSAPIMyAllocationsRequest { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} +⋮---- +/** + * Trading request types + */ +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; +⋮---- +export interface WSAPINewSpotOrderRequest { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; +} +⋮---- +export interface WSAPIOrderTestRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + computeCommissionRates?: boolean; + timestamp: number; + recvWindow?: number; +} +⋮---- +export interface WSAPIOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + newClientOrderId?: string; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderCancelReplaceRequest { + symbol: string; + cancelReplaceMode: 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; + cancelOrderId?: number; + cancelOrigClientOrderId?: string; + cancelNewClientOrderId?: string; + side: 'BUY' | 'SELL'; + type: string; + timeInForce?: string; + price?: numberInString; + quantity?: numberInString; + quoteOrderQty?: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + stopPrice?: numberInString; + trailingDelta?: number; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + cancelRestrictions?: 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; + orderRateLimitExceededMode?: 'DO_NOTHING' | 'CANCEL_ONLY'; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderAmendKeepPriorityRequest { + symbol: string; + orderId?: number | string; + origClientOrderId?: string; + newClientOrderId?: string; + newQty?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersStatusRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOpenOrdersCancelAllRequest { + symbol: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * Order list request types + */ +export interface WSAPIOrderListPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + price: numberInString; + quantity: numberInString; + listClientOrderId?: string; + limitClientOrderId?: string; + limitIcebergQty?: numberInString; + limitStrategyId?: number; + limitStrategyType?: number; + stopPrice?: numberInString; + trailingDelta?: number; + stopClientOrderId?: string; + stopLimitPrice?: numberInString; + stopLimitTimeInForce?: string; + stopIcebergQty?: numberInString; + stopStrategyId?: number; + stopStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOCORequest { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; + listClientOrderId?: string; + aboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + aboveClientOrderId?: string; + aboveIcebergQty?: numberInString; + abovePrice?: numberInString; + aboveStopPrice?: numberInString; + aboveTrailingDelta?: number; + aboveTimeInForce?: string; + aboveStrategyId?: number; + aboveStrategyType?: number; + belowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + belowClientOrderId?: string; + belowIcebergQty?: numberInString; + belowPrice?: numberInString; + belowStopPrice?: numberInString; + belowTrailingDelta?: number; + belowTimeInForce?: string; + belowStrategyId?: number; + belowStrategyType?: number; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOTORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingQuantity: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOTOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: number | string; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOPORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: numberInString; + pendingStopPrice?: numberInString; + pendingTrailingDelta?: numberInString; + pendingIcebergQty?: numberInString; + pendingTimeInForce?: string; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListPlaceOPOCORequest { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: numberInString; + workingQuantity: numberInString; + workingIcebergQty?: numberInString; + workingTimeInForce?: string; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: numberInString; + pendingAboveStopPrice?: numberInString; + pendingAboveTrailingDelta?: numberInString; + pendingAboveIcebergQty?: numberInString; + pendingAboveTimeInForce?: string; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: numberInString; + pendingBelowStopPrice?: numberInString; + pendingBelowTrailingDelta?: numberInString; + pendingBelowIcebergQty?: numberInString; + pendingBelowTimeInForce?: string; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListStatusRequest { + origClientOrderId?: string; + orderListId?: number; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIOrderListCancelRequest { + symbol: string; + orderListId?: number; + listClientOrderId?: string; + newClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +/** + * SOR request types + */ +export interface WSAPISOROrderPlaceRequest { + symbol: string; + side: 'BUY' | 'SELL'; + type: 'LIMIT' | 'MARKET'; + timeInForce?: string; + price?: numberInString; + quantity: numberInString; + newClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + icebergQty?: numberInString; + strategyId?: number; + strategyType?: number; + selfTradePreventionMode?: string; + timestamp: number; + recvWindow?: number; +} +⋮---- +export type WSAPISOROrderTestRequest = WSAPISOROrderPlaceRequest & { + computeCommissionRates?: boolean; +}; +⋮---- +/** + * Futures market data request types + */ +⋮---- +export interface WSAPIFuturesOrderBookRequest { + symbol: string; + limit?: number; +} +⋮---- +export interface WSAPIFuturesTickerPriceRequest { + symbol?: string; +} +⋮---- +export interface WSAPIFuturesTickerBookRequest { + symbol?: string; +} +⋮---- +/** + * Futures trading request types + */ +⋮---- +export interface WSAPINewFuturesOrderRequest { + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesOrderType; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; + newClientOrderId?: string; + stopPrice?: numberType; + closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: SelfTradePreventionMode; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD + recvWindow?: number; + timestamp: number; +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface WSAPIFuturesOrderModifyRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + side: 'BUY' | 'SELL'; + quantity: numberInString; + price: numberInString; + priceMatch?: + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; + origType?: string; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + modifyId?: number; + reduceOnly?: BooleanString; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesOrderCancelRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesOrderStatusRequest { + symbol: string; + orderId?: number; + origClientOrderId?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionRequest { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIFuturesPositionV2Request { + symbol?: string; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountInformationRequest { + omitZeroBalances?: boolean; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface WSAPIAccountCommissionWSAPIRequest { + symbol: string; +} +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api + */ +export interface WSAPINewFuturesAlgoOrderRequest { + algoType: FuturesAlgoOrderType; + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesAlgoConditionalOrderTypes; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberInString; + clientAlgoId?: string; + triggerPrice?: numberInString; + closePosition?: BooleanString; + activatePrice?: numberInString; + callbackRate?: numberInString; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: OrderResponseType; + priceMatch?: PriceMatchMode; + selfTradePreventionMode?: SelfTradePreventionMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD + recvWindow?: number; + timestamp: number; +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Algo-Order + */ +export interface WSAPIFuturesAlgoOrderCancelRequest { + algoid?: number; + clientalgoid?: string; + recvWindow?: number; + timestamp: number; +} + +================ +File: src/types/futures.ts +================ +import { + BooleanString, + ExchangeFilter, + KlineInterval, + numberInString, + OrderBookRow, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SymbolIcebergPartsFilter, + SymbolLotSizeFilter, + SymbolMarketLotSizeFilter, + SymbolMaxIcebergOrdersFilter, + SymbolMaxPositionFilter, + SymbolPriceFilter, +} from './shared'; +⋮---- +export type FuturesContractType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; +⋮---- +export interface ContinuousContractKlinesParams { + pair: string; + contractType: FuturesContractType; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface IndexPriceKlinesParams { + pair: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface SymbolKlinePaginatedParams { + symbol: string; + interval: KlineInterval; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface FuturesDataPaginatedParams { + symbol: string; + contractType?: string; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface FuturesCoinMTakerBuySellVolumeParams { + pair: string; + contractType: 'ALL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface FuturesCoinMBasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface FuturesCoinMLongShortAccountRatioParams { + pair: string; + contractType?: 'PERPETUAL' | 'CURRENT_QUARTER' | 'NEXT_QUARTER'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit?: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface GetFuturesAllOrdersParams { + symbol?: string; + orderId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export enum EnumDualSideMode { + HedgeMode = 'true', + OneWayMode = 'false', +} +⋮---- +export type DualSideMode = `${EnumDualSideMode}`; +⋮---- +export enum EnumMultiAssetMode { + MultiAssetsMode = 'true', + SingleAssetsMode = 'false', +} +⋮---- +export type MultiAssetsMode = `${EnumMultiAssetMode}`; +⋮---- +export type PositionSide = 'BOTH' | 'LONG' | 'SHORT'; +⋮---- +export type MarginType = 'ISOLATED' | 'CROSSED'; +⋮---- +export type WorkingType = 'MARK_PRICE' | 'CONTRACT_PRICE'; +⋮---- +export type FuturesOrderType = + | 'LIMIT' + | 'MARKET' + | 'STOP' + | 'STOP_MARKET' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_MARKET' + | 'TRAILING_STOP_MARKET'; +⋮---- +export type PriceMatchMode = + | 'NONE' + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; +⋮---- +// When using the submitMultipleOrders() endpoint, it seems to expect strings instead of numbers. All other endpoints use numbers. +export interface NewFuturesOrderParams { + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesOrderType; + timeInForce?: OrderTimeInForce; + quantity?: numberType; + reduceOnly?: BooleanString; + price?: numberType; + newClientOrderId?: string; + stopPrice?: numberType; + closePosition?: BooleanString; + activationPrice?: numberType; + callbackRate?: numberType; + workingType?: WorkingType; + priceProtect?: BooleanString; + newOrderRespType?: 'ACK' | 'RESULT'; + selfTradePreventionMode?: SelfTradePreventionMode; + priceMatch?: PriceMatchMode; + goodTillDate?: number; // Mandatory when timeInForce is GTD +} +⋮---- +goodTillDate?: number; // Mandatory when timeInForce is GTD +⋮---- +export interface ModifyFuturesOrderParams { + orderId?: number; + origClientOrderId?: string; + symbol: string; + side: OrderSide; + quantity?: numberType; + price?: numberType; + priceMatch?: PriceMatchMode; + modifyId?: number; + reduceOnly?: BooleanString; +} +⋮---- +export enum EnumPositionMarginChangeType { + AddPositionMargin = 1, + ReducePositionMargin = 0, +} +⋮---- +export type PositionMarginChangeType = `${EnumPositionMarginChangeType}`; +⋮---- +export type IncomeType = + | 'TRANSFER' + | 'WELCOME_BONUS' + | 'REALIZED_PNL' + | 'FUNDING_FEE' + | 'SPECIAL_FUNDING_FEE' + | 'COMMISSION' + | 'INSURANCE_CLEAR'; +⋮---- +export interface CancelMultipleOrdersParams { + symbol: string; + orderIdList?: number[]; + origClientOrderIdList?: string[]; +} +⋮---- +export interface CancelOrdersTimeoutParams { + symbol: string; + countdownTime?: 0 | number; +} +⋮---- +export interface SetLeverageParams { + symbol: string; + leverage: number; +} +⋮---- +export interface SetLeverageResult { + leverage: number; + maxNotionalValue: numberInString; + symbol: string; +} +⋮---- +export interface SetMarginTypeParams { + symbol: string; + marginType: MarginType; +} +⋮---- +export interface SetIsolatedMarginParams { + symbol: string; + positionSide?: PositionSide; + amount: number; + type: PositionMarginChangeType; +} +⋮---- +export interface SetIsolatedMarginResult { + amount: numberInString; + code: 200 | number; + msg: string; + type: 1 | 2; +} +⋮---- +export interface GetPositionMarginChangeHistoryParams { + symbol: string; + type?: PositionMarginChangeType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +/** + * Income history query for `GET /fapi/v1/income` and `GET /dapi/v1/income`. + * Paginate with `startTime` and `endTime`. `page` is not accepted. + */ +export interface GetIncomeHistoryParams { + symbol?: string; + incomeType?: IncomeType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface IncomeHistory { + symbol?: string; + incomeType: IncomeType; + income: string; + asset: string; + time: number; + info: string; + tranId: number; + tradeId: string; +} +⋮---- +export type ForceOrderCloseType = 'LIQUIDATION' | 'ADL'; +⋮---- +export interface GetForceOrdersParams { + symbol?: string; + autoCloseType?: ForceOrderCloseType; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export type ContactType = + | 'PERPETUAL' + | 'CURRENT_MONTH' + | 'NEXT_MONTH' + | 'CURRENT_QUARTER' + | 'NEXT_QUARTER'; +⋮---- +export type ContractStatus = + | 'PENDING_TRADING' + | 'TRADING' + | 'PRE_DELIVERING' + | 'DELIVERING' + | 'DELIVERED' + | 'CANCELLED' + | 'PRE_SETTLE' + | 'SETTLING' + | 'CLOSE'; +⋮---- +export interface FuturesSymbolPercentPriceFilter { + filterType: 'PERCENT_PRICE'; + multiplierUp: numberInString; + multiplierDown: numberInString; + multiplierDecimal: numberInString; +} +⋮---- +export interface FuturesSymbolMaxOrdersFilter { + filterType: 'MAX_NUM_ORDERS'; + limit: number; +} +⋮---- +export interface FuturesSymbolMaxAlgoOrdersFilter { + filterType: 'MAX_NUM_ALGO_ORDERS'; + limit: number; +} +⋮---- +export interface FuturesSymbolMinNotionalFilter { + filterType: 'MIN_NOTIONAL'; + notional: numberInString; +} +⋮---- +/** + * Undocumented USDⓈ-M `exchangeInfo` filter. Not in the published filter schema. + * Observed on live symbols (for example BTCUSDT) with `positionControlSide: "NONE"`. + * connector-python leaves it in `additional_properties`. + */ +export interface FuturesSymbolPositionRiskControlFilter { + filterType: 'POSITION_RISK_CONTROL'; + /** + * Undocumented. Observed value: `NONE`. + */ + positionControlSide: string; +} +⋮---- +/** + * Undocumented. Observed value: `NONE`. + */ +⋮---- +export type FuturesSymbolFilter = + | SymbolPriceFilter + | FuturesSymbolPercentPriceFilter + | SymbolLotSizeFilter + | FuturesSymbolMinNotionalFilter + | SymbolIcebergPartsFilter + | SymbolMarketLotSizeFilter + | FuturesSymbolMaxOrdersFilter + | FuturesSymbolMaxAlgoOrdersFilter + | SymbolMaxIcebergOrdersFilter + | SymbolMaxPositionFilter + | FuturesSymbolPositionRiskControlFilter; +⋮---- +export interface FuturesSymbolExchangeInfo { + symbol: string; + pair: string; + contractType: ContactType; + deliveryDate: number; + onboardDate: number; + status: ContractStatus; + maintMarginPercent: numberInString; + requiredMarginPercent: numberInString; + baseAsset: string; + quoteAsset: string; + marginAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + underlyingType: 'COIN' | 'INDEX'; // No other known values + underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc + settlePlan: number; + triggerProtect: numberInString; + filters: FuturesSymbolFilter[]; + OrderType: OrderType[]; + timeInForce: OrderTimeInForce[]; + liquidationFee: numberInString; + marketTakeBound: numberInString; + contractSize?: number; +} +⋮---- +underlyingType: 'COIN' | 'INDEX'; // No other known values +underlyingSubType: string[]; // DEFI / NFT / BSC / HOT / etc +⋮---- +export interface FuturesExchangeInfo { + exchangeFilters: ExchangeFilter[]; + rateLimits: RateLimiter[]; + serverTime: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any[]; + symbols: FuturesSymbolExchangeInfo[]; + timezone: string; +} +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +export interface FuturesOrderBook { + lastUpdateId: number; + E: number; + T: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} +⋮---- +export interface RawFuturesTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} +⋮---- +export interface AggregateFuturesTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; +} +⋮---- +export interface MarkPrice { + symbol: string; + markPrice: numberInString; + indexPrice: numberInString; + estimatedSettlePrice: numberInString; + lastFundingRate: numberInString; + interestRate: numberInString; + nextFundingTime: number; + time: number; +} +⋮---- +export interface FundingRateHistory { + symbol: string; + fundingRate: numberInString; + fundingTime: number; + markPrice: numberInString; + rateType?: 'Regular' | 'Special'; +} +⋮---- +export interface FuturesSymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + time: number; +} +⋮---- +export interface OpenInterest { + openInterest: numberInString; + symbol: string; + time: number; +} +⋮---- +export interface HistoricOpenInterest { + symbol: string; + sumOpenInterest: string; + sumOpenInterestValue: string; + CMCCirculatingSupply: string; + timestamp: number; +} +⋮---- +export interface PositionModeParams { + dualSidePosition: DualSideMode; +} +⋮---- +export interface ModeChangeResult { + code: 200 | number; + msg: 'success' | string; +} +⋮---- +export interface PositionModeResponse { + dualSidePosition: boolean; +} +⋮---- +export interface MultiAssetModeResponse { + multiAssetsMargin: boolean; +} +⋮---- +export interface NewOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote?: numberInString; + executedQty: numberInString; + orderId: number; + avgPrice?: numberInString; + origQty: numberInString; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + origType: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + goodTillDate?: number; +} +⋮---- +export interface NewOrderError { + code: number; + msg: string; +} +⋮---- +export interface OrderResult { + avgPrice: numberInString; + clientOrderId: string; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + origQty: numberInString; + origType: FuturesOrderType; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + time: number; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + goodTillDate: number; + cumBase?: numberInString; + pair?: string; +} +⋮---- +export interface ModifyFuturesOrderResult { + orderId: number; + symbol: string; + pair: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQty: numberInString; + cumBase: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + positionSide: PositionSide; + stopPrice: numberInString; + workingType: WorkingType; + priceProtect: boolean; + origType: FuturesOrderType; + updateTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; + modifyId?: number; +} +⋮---- +export interface CancelFuturesOrderResult { + clientOrderId: string; + cumQty: numberInString; + cumQuote: numberInString; + executedQty: numberInString; + orderId: number; + origQty: numberInString; + origType: FuturesOrderType; + price: numberInString; + reduceOnly: boolean; + side: OrderSide; + positionSide: PositionSide; + status: OrderStatus; + stopPrice: numberInString; + closePosition: boolean; + symbol: string; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + activatePrice: numberInString; + priceRate: numberInString; + updateTime: number; + workingType: WorkingType; + priceProtect: boolean; + selfTradePreventionMode: SelfTradePreventionMode; + priceMatch: PriceMatchMode; +} +⋮---- +export interface CancelAllOpenOrdersResult { + code: 200 | numberInString; + msg: string; +} +⋮---- +export interface FuturesAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + marginAvailable: boolean; + updateTime: numberInString; +} +⋮---- +export interface FuturesCoinMAccountBalance { + accountAlias: string; + asset: string; + balance: numberInString; + withdrawAvailable: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesAccountAsset { + asset: string; + walletBalance: numberInString; + unrealizedProfit: numberInString; + marginBalance: numberInString; + maintMargin: numberInString; + initialMargin: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + maxWithdrawAmount: numberInString; + crossWalletBalance: numberInString; + crossUnPnl: numberInString; + availableBalance: numberInString; + marginAvailable: boolean; + updateTime: number; +} +⋮---- +export interface FuturesAccountPosition { + symbol: string; + initialMargin: numberInString; + maintMargin: numberInString; + unrealizedProfit: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + leverage: numberInString; + isolated: boolean; + entryPrice: numberInString; + maxNotional: numberInString; + positionSide: PositionSide; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; + updateTime: number; + bidNotional: numberInString; + askNotional: numberInString; +} +⋮---- +export interface FuturesCoinMAccountPosition { + symbol: string; + positionAmt: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + unrealizedProfit: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + leverage: numberInString; + isolated: boolean; + positionSide: PositionSide; + entryPrice: numberInString; + maxQty: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesAccountInformation { + feeTier: numberInString; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + updateTime: numberInString; + multiAssetsMargin: boolean; + totalInitialMargin: numberInString; + totalMaintMargin: numberInString; + totalWalletBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalMarginBalance: numberInString; + totalPositionInitialMargin: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalCrossWalletBalance: numberInString; + totalCrossUnPnl: numberInString; + availableBalance: numberInString; + maxWithdrawAmount: numberInString; + assets: FuturesAccountAsset[]; + positions: FuturesAccountPosition[]; +} +⋮---- +export interface FuturesCoinMAccountInformation { + assets: Omit[]; + positions: FuturesCoinMAccountPosition[]; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; +} +⋮---- +export interface FuturesPosition { + entryPrice: numberInString; + marginType: 'isolated' | 'cross'; + isAutoAddMargin: 'false' | 'true'; + isolatedMargin: numberInString; + leverage: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + maxNotionalValue: numberInString; + positionAmt: numberInString; + notional: numberInString; + isolatedWallet: numberInString; + symbol: string; + unRealizedProfit: numberInString; + positionSide: PositionSide; + updateTime: number; +} +⋮---- +export interface FuturesPositionV3 { + symbol: string; + positionSide: PositionSide; + positionAmt: numberInString; + entryPrice: numberInString; + breakEvenPrice: numberInString; + markPrice: numberInString; + unRealizedProfit: numberInString; + liquidationPrice: numberInString; + isolatedMargin: numberInString; + notional: numberInString; + marginAsset: string; + isolatedWallet: numberInString; + initialMargin: numberInString; + maintMargin: numberInString; + positionInitialMargin: numberInString; + openOrderInitialMargin: numberInString; + adl: number; + bidNotional: numberInString; + askNotional: numberInString; + updateTime: number; +} +⋮---- +export interface FuturesPositionTrade { + buyer: boolean; + commission: numberInString; + commissionAsset: string; + id: number; + maker: boolean; + orderId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + realizedPnl: numberInString; + side: OrderSide; + positionSide: PositionSide; + symbol: string; + time: number; + pair?: string; + baseQty?: numberInString; + marginAsset?: string; +} +⋮---- +export interface ForceOrderResult { + orderId: number; + symbol: string; + status: OrderStatus; + clientOrderId: string; + price: numberInString; + avgPrice: numberInString; + origQty: numberInString; + executedQty: numberInString; + cumQuote: numberInString; + timeInForce: OrderTimeInForce; + type: FuturesOrderType; + reduceOnly: boolean; + closePosition: boolean; + side: OrderSide; + stopPrice: numberInString; + workingType: WorkingType; + origType: FuturesOrderType; + time: number; + updateTime: number; + cumBase?: numberInString; + pair?: string; + goodTillDate?: number; +} +⋮---- +export interface SymbolLeverageBracket { + bracket: number; + initialLeverage: number; + notionalCap: number; + notionalFloor: number; + maintMarginRatio: number; + cum: number; +} +⋮---- +export interface SymbolLeverageBracketsResult { + symbol: string; + brackets: SymbolLeverageBracket[]; +} +⋮---- +export interface UserCommissionRate { + symbol: string; + makerCommissionRate: numberInString; + takerCommissionRate: numberInString; + rpiCommissionRate?: numberInString; +} +⋮---- +export interface FuturesAccountConfig { + feeTier: number; + canTrade: boolean; + canDeposit: boolean; + canWithdraw: boolean; + dualSidePosition: boolean; + updateTime: number; + multiAssetsMargin: boolean; + tradeGroupId: number; +} +⋮---- +export interface SymbolConfig { + symbol: string; + marginType: string; + isAutoAddMargin: string; + leverage: number; + maxNotionalValue: string; +} +⋮---- +export interface UserForceOrder { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; +} +⋮---- +export interface RebateDataOverview { + brokerId: string; + newTraderRebateCommission: numberInString; + oldTraderRebateCommission: numberInString; + totalTradeUser: number; + unit: string; + totalTradeVol: numberInString; + totalRebateVol: numberInString; + time: number; +} +⋮---- +export interface SetCancelTimeoutResult { + symbol: string; + countdownTime: numberInString; +} +⋮---- +export interface ChangeStats24hr { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; // First tradeId + lastId: number; // Last tradeId + count: number; +} +⋮---- +firstId: number; // First tradeId +lastId: number; // Last tradeId +⋮---- +export interface OrderAmendmentDetailPrice { + before: numberInString; + after: numberInString; +} +⋮---- +export interface OrderAmendmentDetailQty { + before: numberInString; + after: numberInString; +} +⋮---- +export interface OrderAmendmentDetail { + price: OrderAmendmentDetailPrice; + origQty: OrderAmendmentDetailQty; + count: number; +} +⋮---- +export interface OrderAmendment { + amendmentId: number; + symbol: string; + pair: string; + orderId: number; + clientOrderId: string; + time: number; + amendment: OrderAmendmentDetail; + modifyId?: number; +} +⋮---- +export interface QuarterlyContractSettlementPrice { + deliveryTime: number; + deliveryPrice: number; +} +⋮---- +export interface BasisParams { + pair: string; + contractType: 'CURRENT_QUARTER' | 'NEXT_QUARTER' | 'PERPETUAL'; + period: '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d'; + limit: number; + startTime?: number; + endTime?: number; +} +⋮---- +export interface Basis { + indexPrice: string; + contractType: string; + basisRate: string; + futuresPrice: string; + annualizedBasisRate: string; + basis: string; + pair: string; + timestamp: number; +} +⋮---- +export interface IndexPriceConstituent { + exchange: string; + symbol: string; + price: numberInString; + weight: numberInString; +} +⋮---- +export interface IndexPriceConstituents { + symbol: string; + time: number; + constituents: IndexPriceConstituent[]; +} +⋮---- +export interface InsuranceFundBalance { + symbols: string[]; + assets: { + asset: string; + marginBalance: string; + updateTime: number; + }[]; +} +⋮---- +export interface ModifyOrderParams { + orderId?: number; + origClientOrderId?: string; + symbol: string; + side: 'SELL' | 'BUY'; + quantity: string; + price: string; + priceMatch?: + | 'OPPONENT' + | 'OPPONENT_5' + | 'OPPONENT_10' + | 'OPPONENT_20' + | 'QUEUE' + | 'QUEUE_5' + | 'QUEUE_10' + | 'QUEUE_20'; + modifyId?: number; + reduceOnly?: BooleanString; + recvWindow?: number; + timestamp: number; +} +⋮---- +export interface GetFuturesOrderModifyHistoryParams { + symbol: string; + orderId?: number; + origClientOrderId?: string; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface FuturesTradeHistoryDownloadId { + avgCostTimestampOfLast30d: number; + downloadId: string; +} +⋮---- +export interface FuturesTransactionDownloadLink { + downloadId: string; + status: 'completed' | 'processing'; + url: string; + expirationTimestamp: number; + isExpired: boolean | null; +} +⋮---- +export interface PortfolioMarginProAccountInfo { + maxWithdrawAmountUSD: string; + asset: string; + maxWithdrawAmount: string; // This field will be ignored in the response +} +⋮---- +maxWithdrawAmount: string; // This field will be ignored in the response +⋮---- +export interface FuturesConvertPair { + fromAsset: string; + toAsset: string; + fromAssetMinAmount: string; + fromAssetMaxAmount: string; + toAssetMinAmount: string; + toAssetMaxAmount: string; +} +⋮---- +export interface FuturesConvertQuoteRequest { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + validTime?: '10s' | '30s' | '1m' | '2m'; +} +⋮---- +export interface FuturesConvertQuote { + quoteId: string; + ratio: string; + inverseRatio: string; + validTimestamp: number; + toAmount: string; + fromAmount: string; +} +⋮---- +export interface FuturesConvertOrderStatus { + orderId: string; + orderStatus: 'PROCESS' | 'ACCEPT_SUCCESS' | 'SUCCESS' | 'FAIL'; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; +} +⋮---- +/** + * Algo Order Types (Effective 2025-12-02) + * USDⓈ-M Futures conditional orders migrate to Algo Service + */ +⋮---- +export type FuturesAlgoOrderType = 'CONDITIONAL'; +⋮---- +export type FuturesAlgoConditionalOrderTypes = + | 'STOP_MARKET' + | 'TAKE_PROFIT_MARKET' + | 'STOP' + | 'TAKE_PROFIT' + | 'TRAILING_STOP_MARKET'; +⋮---- +/** + * Ref: https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Event-Algo-Order-Update + */ +export type FuturesAlgoOrderStatus = + | 'NEW' + | 'CANCELED' + | 'TRIGGERING' + | 'TRIGGERED' + | 'FINISHED' + | 'REJECTED' + | 'EXPIRED'; +⋮---- +export interface FuturesNewAlgoOrderParams { + algoType: FuturesAlgoOrderType; + symbol: string; + side: OrderSide; + positionSide?: PositionSide; + type: FuturesAlgoConditionalOrderTypes; + timeInForce?: OrderTimeInForce; + quantity?: numberInString; + price?: numberInString; + triggerPrice?: numberInString; + workingType?: WorkingType; + priceMatch?: PriceMatchMode; + closePosition?: BooleanString; + priceProtect?: BooleanString; + reduceOnly?: BooleanString; + activatePrice?: numberInString; + callbackRate?: numberInString; + clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ + selfTradePreventionMode?: SelfTradePreventionMode; + goodTillDate?: number; +} +⋮---- +clientAlgoId?: string; // ^[\.A-Z\:/a-z0-9_-]{1,36}$ +⋮---- +export interface FuturesAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + algoType: FuturesAlgoOrderType; + orderType: FuturesAlgoConditionalOrderTypes; + symbol: string; + side: OrderSide; + positionSide: PositionSide; + timeInForce: OrderTimeInForce; + quantity: numberInString; + algoStatus: FuturesAlgoOrderStatus; + triggerPrice?: numberInString; + price?: numberInString; + icebergQuantity: numberInString | null; + selfTradePreventionMode: SelfTradePreventionMode; + workingType: WorkingType; + priceMatch: PriceMatchMode; + closePosition: boolean; + priceProtect: boolean; + reduceOnly: boolean; + activatePrice?: numberInString; + callbackRate?: numberInString; + createTime: number; + updateTime: number; + triggerTime: number; + goodTillDate: number; +} +⋮---- +export interface FuturesCancelAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface FuturesCancelAlgoOrderResponse { + algoId: number; + clientAlgoId: string; + code: string; + msg: string; +} +⋮---- +export interface FuturesCancelAllAlgoOpenOrdersResponse { + code: number; + msg: string; +} +⋮---- +export interface FuturesQueryAlgoOrderParams { + algoId?: number; + clientAlgoId?: string; +} +⋮---- +export interface FuturesQueryAlgoOrderResponse + extends FuturesAlgoOrderResponse { + actualOrderId: numberInString; + actualPrice: numberInString; + tpTriggerPrice?: numberInString; + tpPrice?: numberInString; + slTriggerPrice?: numberInString; + slPrice?: numberInString; + tpOrderType?: string; +} +⋮---- +export interface FuturesQueryOpenAlgoOrdersParams { + algoType?: FuturesAlgoOrderType; + symbol?: string; + algoId?: number; +} +⋮---- +export interface FuturesQueryAllAlgoOrdersParams { + symbol: string; + algoId?: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; // Default 500; max 1000 +} +⋮---- +limit?: number; // Default 500; max 1000 +⋮---- +export interface SymbolAdlRisk { + symbol: string; + adlRisk: 'low' | 'medium' | 'high'; + updateTime: number; +} +⋮---- +export interface TradingSession { + startTime: number; + endTime: number; + type: 'PRE_MARKET' | 'REGULAR' | 'AFTER_MARKET' | 'OVERNIGHT' | 'NO_TRADING'; +} +⋮---- +export interface MarketSchedule { + sessions: TradingSession[]; +} +⋮---- +export interface TradingSchedule { + updateTime: number; + marketSchedules: { + EQUITY?: MarketSchedule; + COMMODITY?: MarketSchedule; + KR_EQUITY?: MarketSchedule; + HK_EQUITY?: MarketSchedule; + CN_EQUITY?: MarketSchedule; + FX?: MarketSchedule; + }; +} +⋮---- +export interface RpiOrderBook { + lastUpdateId: number; + E: number; // Message output time + T: number; // Transaction time + bids: [numberInString, numberInString][]; + asks: [numberInString, numberInString][]; +} +⋮---- +E: number; // Message output time +T: number; // Transaction time + +================ +File: src/websocket-client.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { KlineInterval } from './types/shared'; import { - generateNewOrderId, - getOrderIdPrefix, - getServerTimeEndpoint, - logInvalidOrderId, + Exact, + WsAPIOperationResponseMap, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WsOperation, + WsRequestOperationBinance, +} from './types/websockets/ws-api'; +import { + MessageEventLike, + WSClientConfigurableOptions, + WsMarket, + WsTopic, +} from './types/websockets/ws-general'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient'; +import Beautifier from './util/beautifier'; +import { DefaultLogger } from './util/logger'; +import { signMessage } from './util/node-support'; +import { + appendEventIfMissing, + requiresWSAPINewClientOID, RestClientOptions, serialiseParams, + validateWSAPINewClientOID, } from './util/requestUtils'; +import { neverGuard } from './util/typeGuards'; +import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; +import { RestClientCache } from './util/websockets/rest-client-cache'; +import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; +import { + EVENT_TYPES_USER_DATA, + getLegacyWsKeyContext, + getLegacyWsStoreKeyWithContext, + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getRealWsKeyFromDerivedWsKey, + getTestnetWsKey, + getTopicsPerWSKey, + getWsKeyForProductGroup, + getWsUrl, + getWsURLSuffix, + isPrivateWsTopic, + isWSPingFrameAvailable, + isWSPongFrameAvailable, + MiscUserDataConnectionState, + parseEventTypeFromMessage, + parseRawWsMessage, + resolveUserDataMarketForWsKey, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WSAPIWsKey, + WSConnectionCategory, + WsKey, + WsTopicRequest, +} from './util/websockets/websocket-util'; +import { WSConnectedResult } from './util/websockets/WsStore.types'; ⋮---- -export class MainClient extends BaseRestClient +type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; ⋮---- -constructor( - restClientOptions: RestClientOptions = {}, - requestOptions: AxiosRequestConfig = {}, -) +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; +} +⋮---- +/** If true, will skip auth requirement for WS API connection */ ⋮---- /** - * 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 + * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. + * + * When possible, it will subscribe to all requested topics on a single websocket connection. A list of + * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. + * + * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically + * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. + * + * If any connection is reconnected, the WS client will: + * - Emit the "reconnecting" event when the process begins. + * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a + * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed + * while disconnected. + * + * User data streams will use a dedicated connection per stream for increased resilience. + */ ⋮---- -// Adjust server time by adding estimated one-way latency +export class WebsocketClient extends BaseWebsocketClient< ⋮---- -// Calculate time difference between adjusted server time and local time +constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) ⋮---- /** - * Abstraction required by each client to aid with time sync / drift handling - */ -async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise + * Binance uses native WebSocket ping/pong frames, which cannot be directly used in + * some environents (e.g. most browsers do not support sending raw ping/pong frames). + * + * This disables heartbeats in those environments, if ping/pong frames are unavailable. + * + * Some browsers may still handle these automatically. Some discussion around this can + * be found here: https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser + */ ⋮---- -/** - * - * SPOT TRADING Endpoints - General endpoints - * - **/ +// fn pointers: ⋮---- -testConnectivity(): Promise +private getUserDataStreamManager(): UserDataStreamManager ⋮---- -getExchangeInfo(params?: ExchangeInfoParams): Promise +private getRestClientOptions(): RestClientOptions ⋮---- /** + * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting + * for automatic connection by SDK. * - * SPOT TRADING Endpoints - Market endpoints - * - **/ -⋮---- -getOrderBook(params: OrderBookParams): Promise -⋮---- -getRecentTrades(params: RecentTradesParams): Promise -⋮---- -getHistoricalTrades(params: HistoricalTradesParams): Promise -⋮---- -getHistoricalBlockTrades( - params: HistoricalBlockTradesParams, -): Promise -⋮---- -getAggregateTrades( - params: SymbolFromPaginatedRequestFromId, -): Promise -⋮---- -getKlines(params: KlinesParams): Promise + * For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group. + */ +public connectAll(): Promise[] ⋮---- -getUIKlines(params: KlinesParams): Promise +/** + * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if + * you're only working with one product group. + */ +public connectPublic(): Promise[] ⋮---- -getAvgPrice(params: +/** + * This function serves no purpose in the Binance SDK + */ +public async connectPrivate(): Promise ⋮---- -getExecutionRules( - params?: SpotExecutionRulesParams, -): Promise +/** + * Ensures the WS API connection is active and ready. + * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- -getReferencePrice(params: { - symbol: string; -}): Promise +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -getReferencePriceCalculation(params: { - symbol: string; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; -}): Promise +/** + * 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, +): Promise ⋮---- -get24hrChangeStatistics(params?: { - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; +/** + * 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, +) ⋮---- -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL +/** + * + * + * + * WS API Methods - similar to the REST API, but via WebSockets + * https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * + * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/REST-API-vs-WebSockets-vs-WebSocket-API + * + * + * + */ ⋮---- -get24hrChangeStatistics(params: { - symbol: string; // use for single symbol - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; - }): Promise; +/** + * 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: + * + * - Spot: https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * - USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info + * - COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info + * + * + * 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. + * + * Misc options: + * - signRequest: boolean - if included, this request will automatically be signed with the available credentials. + * + * @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 + */ ⋮---- -symbol: string; // use for single symbol -type?: 'FULL' | 'MINI'; // default is FULL +// This overload allows the caller to omit the 3rd param, if it isn't required +sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap + TWSParams extends Exact[TWSOperation]>, + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: TWSKey, + operation: TWSOperation, + params?: TWSParams extends void | never ? undefined : TWSParams, + requestFlags?: WSAPIRequestFlags, + ): Promise; ⋮---- -get24hrChangeStatistics(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - type?: 'FULL' | 'MINI'; // default is FULL - symbolStatus?: string; -}): Promise +// if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols -type?: 'FULL' | 'MINI'; // default is FULL +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends Exact[TWSOperation]>, + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: WsKey, + operation: TWSOperation, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, +): Promise ⋮---- -getTradingDayTicker( - params: TradingDayTickerParams, -): Promise +/** + * Spot: + * -> https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information + * -> https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md#public-api-requests + * USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info + * COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info + */ ⋮---- -getSymbolPriceTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +// If testnet, enforce testnet wskey for WS API calls ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); ⋮---- -getSymbolOrderBookTicker(params?: { - symbol?: string; // use for single symbol - symbols?: string[]; // use for multiple symbols - symbolStatus?: string; -}): Promise +// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); ⋮---- -symbol?: string; // use for single symbol -symbols?: string[]; // use for multiple symbols +// Some commands don't require authentication. ⋮---- -getRollingWindowTicker( - params: RollingWindowTickerParams, -): Promise +// Only if authOnConnect is enabled (aka using Ed25519 keys) +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); ⋮---- /** - * - * SPOT TRADING Endpoints - Trading endpoints - * - **/ + * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated + * can introduce a small delay before the actual request is sent, if not connected before that request is + * made. This can lead to a curious race condition, where the request timestamp is before + * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. + * + * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, + * it offsets that timestamp by the delay. + */ ⋮---- -submitNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +// Sign, if needed ⋮---- -testNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise +// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events ⋮---- -getOrder(params: GetOrderParams): Promise +// Enrich returned promise with request context for easier debugging ⋮---- -cancelOrder(params: CancelOrderParams): Promise +// throw e; ⋮---- -cancelAllSymbolOrders(params: { - symbol: string; -}): Promise +// this.logger.trace( +// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, +// ); ⋮---- -replaceOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, - >( - params: ReplaceSpotOrderParams, -): Promise> +// Send event. +⋮---- +// Return deferred promise, so caller can await this call ⋮---- /** - * Reduce the quantity of an existing open order while keeping its priority in the order book. - * The new quantity must be less than the current quantity. - * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade + * + * + * Internal methods - not intended for public use + * + * */ -amendOrderKeepPriority( - params: AmendKeepPriorityParams, -): Promise ⋮---- -getOpenOrders(params?: +/** + * @returns The WS URL to connect to for this WS key + */ +async getWsUrl( + wsKey: WsKey, + connectionType: 'public' | 'market' | 'private' = 'market', +): Promise ⋮---- -getAllOrders(params: GetAllOrdersParams): Promise +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise +⋮---- +// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); ⋮---- /** - * @deprecated + * Handles request sign, if connection isn't authenticated yet. + * If connection does not need to be authenticated or request doesn't require sign, + * use the requestFlags.authIsOptional flag to skip sign and send the request immediately. */ -submitNewOCO(params: NewOCOParams): Promise +private async signWSAPIRequest( + requestEvent: WsRequestOperationBinance, + requestFlags?: WSAPIRequestFlags, +): Promise> ⋮---- -submitNewOrderList( - params: NewOrderListParams, -): Promise> +/** + * Not really needed for most commands on Binance. Their WS API supports + * sending signed WS API commands, but that adds latency to every request. + * + * Instead, this SDK will authenticate once after connecting. All requests + * after authentication can then be sent without sign for maximum speed. + */ ⋮---- -submitNewOrderListOTO( - params: NewOrderListOTOParams, -): Promise +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise< + WsRequestOperationBinance< + string, + { apiKey: string; signature: string; timestamp: number } + > + > { + try { + // Note: Only Ed25519 keys are supported for this feature. + // RSA & HMAC keys will automatically sign each individual request instead. + + // If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. + + // Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. + + // Note: You still have to specify the timestamp parameter for SIGNED requests. + const timestamp = Date.now() + (this.getTimeOffsetMs() || 0); ⋮---- -submitNewOrderListOTOCO( - params: NewOrderListOTOCOParams, -): Promise +// Note: Only Ed25519 keys are supported for this feature. +// RSA & HMAC keys will automatically sign each individual request instead. ⋮---- -submitNewOrderListOPO( - params: NewOrderListOPOParams, -): Promise +// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. ⋮---- -submitNewOrderListOPOCO( - params: NewOrderListOPOCOParams, -): Promise +// Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. ⋮---- -cancelOCO(params: CancelOCOParams): Promise +// Note: You still have to specify the timestamp parameter for SIGNED requests. ⋮---- -getOCO(params?: GetOCOParams): Promise +protected sendPingEvent(wsKey: WsKey) ⋮---- -getAllOCO(params?: BasicFromPaginatedParams): Promise +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * Query open OCO - */ -getAllOpenOCO(): Promise +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) ⋮---- -/** - * Places an order using smart order routing (SOR). - */ -submitNewSOROrder( - params: NewSpotSOROrderParams, -): Promise +protected sendPongEvent(wsKey: WsKey) ⋮---- -/** - * Test new order creation and signature/recvWindow using smart order routing (SOR). - * Creates and validates a new order but does not send it into the matching engine. - */ -testNewSOROrder( - params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, -): Promise +// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); ⋮---- -/** - * - * SPOT TRADING Endpoints - Account endpoints - * - **/ +// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +⋮---- +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * Get current account information + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. */ -getAccountInformation(params?: { - omitZeroBalances?: boolean; -}): Promise -⋮---- -getAccountTradeList( - params: SymbolFromPaginatedRequestFromId & { orderId?: number }, -): Promise +protected async getWsRequestEvents( + wsKey: WsKey, + operation: WsOperation, + requests: WsTopicRequest[], +): Promise>[]> ⋮---- -getOrderRateLimit(): Promise +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -getPreventedMatches( - params: PreventedMatchesParams, -): Promise +// Cache midflight subs on the req ID +// Enrich response with subs for that req ID ⋮---- -getAllocations(params: AllocationsParams): Promise +protected getPrivateWSKeys(): WsKey[] ⋮---- -getCommissionRates(params: +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- /** - * - * MARGIN TRADING Endpoints - Market Data endpoints - * - **/ -⋮---- -getCrossMarginCollateralRatio(): Promise< - { - collaterals: Collateral[]; - assetNames: string[]; - }[] - > { - return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); -⋮---- -getAllCrossMarginPairs(): Promise -⋮---- -getIsolatedMarginAllSymbols(params?: { - symbol?: string; -}): Promise + * Determines if a topic is for a private channel, using a hardcoded list of strings + */ +protected isPrivateTopicRequest(request: WsTopicRequest): boolean ⋮---- -getAllMarginAssets(): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPing(msg: any): boolean ⋮---- -getMarginDelistSchedule(): Promise +// For binance, all ping/pong events are frame events ⋮---- -getIsolatedMarginTierData( - params: QueryIsolatedMarginTierDataParams, -): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any +protected isWsPong(msg: any): boolean ⋮---- -queryMarginPriceIndex( - params: BasicSymbolParam, -): Promise +// For binance, all ping/pong events are frame events ⋮---- -getMarginAvailableInventory(params: { - type: string; -}): Promise +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] ⋮---- -getLeverageBracket(): Promise +// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); ⋮---- /** - * - * MARGIN TRADING Endpoints - Borrow and Repay endpoints - * - **/ + * + * Extract event from JSON + * + */ ⋮---- -getNextHourlyInterestRate( - params: GetNextHourlyInterestRateParams, -): Promise +/** + * + * Minor data normalisation & preparation + * + */ ⋮---- -getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< +// ws consumers: { data: ... } +// ws api consumers (user data): { event: ... } +// other responses: { ... } ⋮---- -submitMarginAccountBorrowRepay( - params: MarginAccountLoanParams, -): Promise +// First try, the child node ⋮---- -getMarginAccountBorrowRepayRecords( - params: GetMarginAccountBorrowRepayRecordsParams, -): Promise< +// Second try, the parent ⋮---- -getMarginInterestRateHistory( - params: QueryMarginInterestRateHistoryParams, -): Promise +// Some events don't include the topic (event name) +// This tries to extract and append it, using available context ⋮---- -queryMaxBorrow( - params: BasicMarginAssetParams, -): Promise +// This attaches `wsMarket` and `streamName` to incoming events +// If the event is an array, it's attached to each element in the array ⋮---- /** - * - * MARGIN TRADING Endpoints - Trade endpoints - * - **/ + * + * + * Main parsing logic below: + * + * + */ ⋮---- -getMarginForceLiquidationRecord( - params: GetForceLiquidationRecordParams, -): Promise< +// parsed: JSON.stringify(parsed, null, 2), ⋮---- -getSmallLiabilityExchangeCoins(): Promise +// WS API response ⋮---- -getSmallLiabilityExchangeHistory( - params: GetSmallLiabilityExchangeHistoryParams, -): Promise< +/** + * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): + * + * { + * result: null, + * id: 1, + * }; + * + * Currently there's no simple way to tell this apart from an actual WS API response with + * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, + * but that will not affect usage. + * + * Unrelated, example wsapi error for reference: + * + { + id: 1, + status: 400, + error: { + code: -1021, + msg: "Timestamp for this request was 1000ms ahead of the server's time." + }, + rateLimits: [ + { + rateLimitType: 'REQUEST_WEIGHT', + interval: 'MINUTE', + intervalNum: 1, + limit: 6000, + count: 4 + } + ], + wsKey: 'mainWSAPI', + isWSAPIResponse: true + } + */ ⋮---- -marginAccountCancelOpenOrders( - params: BasicSymbolParam, -): Promise +// This is the counterpart to getPromiseRefForWSAPIRequest ⋮---- -marginAccountCancelOCO(params: CancelOCOParams): Promise +// WS API Exception ⋮---- -marginAccountCancelOrder( - params: CancelOrderParams, -): Promise +// authenticated ⋮---- -marginAccountNewOCO(params: NewOCOParams): Promise +// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests ⋮---- -marginAccountNewOrder< - T extends OrderType, - RT extends OrderResponseType | undefined = undefined, ->(params: NewSpotOrderParams): Promise> +// WS API Success ⋮---- -getMarginOrderCountUsage( - params: GetMarginOrderCountUsageParams, -): Promise +// Handle incoming event that listen key expired ⋮---- -queryMarginAccountAllOCO( - params: QueryMarginAccountAllOCOParams, -): Promise +// handle this how? ⋮---- -queryMarginAccountAllOrders( - params: GetAllOrdersParams, -): Promise +// Just closing the connection (with the last parameter as true) will handle cleanup and respawn +// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn ⋮---- -queryMarginAccountOCO(params: GetOCOParams): Promise +// Suffix all events for the beautifier, if market is options +// Options has some conflicting keys with different intentions, so will be suffixed ⋮---- -queryMarginAccountOpenOCO(params: { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -}): Promise +// emit an additional event for user data messages ⋮---- -queryMarginAccountOpenOTOOrderLists( - params: QueryMarginOpenOTOOrderListsParams, -): Promise +// Messages for a subscribed topic all include the "topic" property ⋮---- -queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise +// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property ⋮---- -queryMarginAccountOrder(params: GetOrderParams): Promise +// Failed request ⋮---- -queryMarginAccountTradeList( - params: QueryMarginAccountTradeListParams, -): Promise +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- -submitSmallLiabilityExchange(params: +// Request/reply pattern for authentication success ⋮---- -submitManualLiquidation( - params: ManualLiquidationParams, -): Promise +// In case of catastrophic failure, fallback to noisy emit update ⋮---- /** - * Post a new OTO order for margin account + * + * + * + * + * + * User Data Streams + * + * + * + * + * */ -submitMarginOTOOrder( - params: SubmitMarginOTOOrderParams, -): Promise ⋮---- /** - * Submit a new OTOCO order for margin account + * -------------------------- + * User data listen key tracking & persistence + * -------------------------- + **/ +⋮---- +/** + * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. + * Supports spot, margin & isolated margin listen keys. */ -submitMarginOTOCOOrder( - params: SubmitMarginOTOCOOrderParams, -): Promise +public async subscribeSpotUserDataStreamWithListenKey( + wsKey: WsKey, + listenKey: string, + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise ⋮---- /** - * Create a special key for low-latency trading (VIP 4+ only) + * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ -createMarginSpecialLowLatencyKey( - params: CreateSpecialLowLatencyKeyParams, -): Promise +public async subscribeSpotUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise ⋮---- -deleteMarginSpecialLowLatencyKey(params?: { - apiKey?: string; - apiName?: string; - symbol?: string; -}): Promise +public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise ⋮---- -updateMarginIPForSpecialLowLatencyKey(params: { - apiKey: string; +public async fetchMarginListenToken(params?: { symbol?: string; - ip: string; -}): Promise + isIsolated?: boolean; + validity?: number; +}): Promise< ⋮---- /** - * Query the list of special keys for low-latency trading + * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ -getMarginSpecialLowLatencyKeys(params: { - symbol?: string; -}): Promise +public async subscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise +⋮---- +public unsubscribeCrossMarginUserDataStream( + wsKey: WsKey = 'main', +): Promise ⋮---- /** - * Query information for a specific special key used in low-latency trading + * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ -getMarginSpecialLowLatencyKey(params: { - apiKey: string; - symbol?: string; -}): Promise +public async subscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise +⋮---- +public unsubscribeIsolatedMarginUserDataStream( + symbol: string, + wsKey: WsKey = 'main', +): Promise ⋮---- /** - * Query the current cross-margin liquidation loan status (bankruptcy deficit). + * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) */ -getMarginLiquidationLoan(): Promise +public async subscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise +⋮---- +public unsubscribeMarginRiskUserDataStream( + wsKey: WsKey = 'main', +): Promise ⋮---- /** - * Repay an outstanding cross-margin liquidation loan from the spot wallet. - */ -repayMarginLiquidationLoan( - params: RepayMarginLiquidationLoanParams, -): Promise + * -------------------------- + * End of SPOT market websocket streams + * -------------------------- + **/ ⋮---- /** - * Query cross-margin liquidation loan repayment history. + * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. + * + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. */ -getMarginLiquidationLoanRepayHistory( - params?: GetMarginLiquidationLoanRepayHistoryParams, -): Promise +public async subscribeUsdFuturesUserDataStream( + userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise ⋮---- -/** - * Exit Margin Special Key mode for Cross Margin Classic accounts. - */ -exitMarginSpecialKeyMode(): Promise +userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate +⋮---- +// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. +⋮---- +public unsubscribeUsdFuturesUserDataStream( + wsKey: WsKey = WS_KEY_MAP.usdmPrivate, +): Promise ⋮---- /** + * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * - * MARGIN TRADING Endpoints - Transfer endpoints - * - **/ + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', // coinm | coinmTestnet + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise ⋮---- -getCrossMarginTransferHistory( - params: GetCrossMarginTransferHistoryParams, -): Promise> +wsKey: WsKey = 'coinm', // coinm | coinmTestnet ⋮---- -queryMaxTransferOutAmount( - params: BasicMarginAssetParams, -): Promise +public unsubscribeCoinFuturesUserDataStream( + wsKey: WsKey = 'coinm', +): Promise ⋮---- /** + * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. * - * MARGIN TRADING Endpoints - Account endpoints - * - **/ -⋮---- -updateCrossMarginMaxLeverage(params: + * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. + */ +public async subscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', + forceNewConnection?: boolean, + miscState?: MiscUserDataConnectionState, +): Promise ⋮---- -disableIsolatedMarginAccount(params: +public unsubscribePortfolioMarginUserDataStream( + wsKey: WsKey = 'portfolioMarginUserData', +): Promise ⋮---- -enableIsolatedMarginAccount(params: +/** + * Close an active, dedicated, user data stream connection. + * + * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. + * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). + */ +public async closeUserDataStream( + wsKey: WsKey, + wsMarket: WsMarket, + symbol?: string, +): Promise ⋮---- -getBNBBurn(): Promise +// built around the assumption in how per-connection listen key wskeys are created +// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main +// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm ⋮---- -getMarginSummary(): Promise +protected isCustomReconnectionNeeded(wsKey: string): boolean ⋮---- -queryCrossMarginAccountDetails(): Promise +protected async triggerCustomReconnectionWorkflow( + legacyWsKey: string, +): Promise ⋮---- -getCrossMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise +private async respawnUserDataStream( + wsKey: WsKey, + market: WsMarket, + context: { + symbol?: string; + isTestnet?: boolean; + respawnAttempt?: number; + } = {}, +): Promise ⋮---- -getIsolatedMarginAccountLimit(): Promise< +// Handle corner case where wsKey is still the derived key for some reason... ⋮---- -getIsolatedMarginAccountInfo(params?: { - symbols?: string; -}): Promise +// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key ⋮---- -getIsolatedMarginFeeData( - params: QueryCrossMarginFeeDataParams, -): Promise +// Prevent simultaneous timers in same scope ⋮---- -toggleBNBBurn(params: ToggleBNBBurnParams): Promise +// Execute reconnection workflow after short delay ⋮---- /** - * Possibly @deprecated - * Only existing in old documentation, not in new documentation + * Subscribe to the European Options user data stream - listen key is automatically generated. + * + * Not supported at this time. Please get in touch if you need this. */ -getMarginCapitalFlow( - params: GetMarginCapitalFlowParams, -): Promise +// public async subscribeEuropeanOptionsUserData( +// wsKey: WsKey = 'eoptions', +// forceNewConnection?: boolean, +// isReconnecting?: boolean, +// ): Promise { +// try { +// const { listenKey } = await this.restClientCache +// .getEuropeanOptionsClient( +// this.getRestClientOptions(), +// this.options.requestOptions, +// ) +// .getUserDataListenKey(); ⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryLoanRecord( - params: QueryMarginRecordParams, -): Promise< +// const market: WsMarket = 'options'; ⋮---- -/** - * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead - */ -queryRepayRecord( - params: QueryMarginRecordParams, -): Promise< +// return this.subscribeGeneralUserDataStreamWithListenKey( +// wsKey, +// market, +// listenKey, +// forceNewConnection, +// isReconnecting, +// ); +// } catch (e) { +// this.logger.error('Failed to connect to Options user data', { +// ...WS_LOGGER_CATEGORY, +// error: e, +// }); +// this.emit('exception', { +// functionRef: 'subscribePortfolioMarginUserDataStream()', +// wsKey, +// forceNewConnection, +// isReconnecting, +// error: e?.stack || e, +// }); +// } +// } ⋮---- /** - * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + * + * + * + * + * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. + * + * + * + * */ -isolatedMarginAccountTransfer( - params: IsolatedMarginAccountTransferParams, -): Promise ⋮---- /** - * - * WALLET Endpoints - Capital endpoints - * + * -------------------------- + * Universal market websocket streams (may apply to one or more API markets) + * -------------------------- **/ ⋮---- -getBalances(): Promise -⋮---- -withdraw(params: WithdrawParams): Promise< -⋮---- -getWithdrawHistory( - params?: WithdrawHistoryParams, -): Promise -⋮---- -getWithdrawAddresses(): Promise -⋮---- -getWithdrawQuota(): Promise< -⋮---- -getDepositHistory(params?: DepositHistoryParams): Promise -⋮---- -getDepositAddress( - params: DepositAddressParams, -): Promise -⋮---- -getDepositAddresses( - params: DepositAddressListParams, -): Promise -⋮---- -submitDepositCredit( - params: SubmitDepositCreditParams, -): Promise -⋮---- /** - * @deprecated - deleted as of 2024-11-21 + * Advanced: Subscribe to a universal market websocket stream + * + * This is NOT recommended unless you're very confident with what you're doing. */ -getAutoConvertStablecoins(): Promise +public subscribeEndpoint( + endpoint: string, + market: 'spot' | 'usdm' | 'coinm', +): Promise ⋮---- /** - * @deprecated - deleted as of 2024-11-21 + * Subscribe to aggregate trades for a symbol in a market category */ -setConvertibleCoins(params: ConvertibleCoinsParams): Promise +public subscribeAggregateTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * - * WALLET Endpoints - Asset endpoints - * - **/ -⋮---- -getAssetDetail( - params?: Partial, -): Promise> -⋮---- -getWalletBalances(params?: { - quoteAsset?: string; -}): Promise -⋮---- -getUserAsset(params: GetAssetParams): Promise -⋮---- -getSpotAssetTags(params?: SpotAssetTagsParams): Promise -⋮---- -submitUniversalTransfer( - params: UniversalTransferParams, -): Promise< -⋮---- -getUniversalTransferHistory( - params: UniversalTransferHistoryParams, -): Promise -⋮---- -getDust(params: -⋮---- -convertDustToBnb(params: ConvertDustParams): Promise + * Subscribe to trades for a symbol in a market category + * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning + */ +public subscribeTrades( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Convert dust assets to a target asset (e.g. BNB, USDT). + * Subscribe to block trades for a symbol in spot markets. */ -convertDustAssets(params: DustConvertParams): Promise +public subscribeBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Query assets eligible for dust conversion. + * Subscribe to coin index for a symbol in COINM Futures markets + * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. */ -queryDustConvertibleAssets( - params: DustConvertibleAssetsParams, -): Promise +public subscribeCoinIndexPrice( + symbol: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, +): Promise ⋮---- -getDustLog(params?: BasicTimeRangeParam): Promise +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise +/** + * Subscribe to mark price for a symbol in a market category + */ +public subscribeMarkPrice( + symbol: string, + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, +): Promise ⋮---- -getTradeFee(params?: +/** + * Subscribe to mark price for all symbols in a market category + */ +public subscribeAllMarketMarkPrice( + market: 'usdm' | 'coinm', + updateSpeedMs: 1000 | 3000 = 3000, + wsKeyOverride?: WsKey, +): Promise ⋮---- -getFundingAsset(params: GetAssetParams): Promise +/** + * Subscribe to klines(candles) for a symbol in a market category + */ +public subscribeKlines( + symbol: string, + interval: KlineInterval, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< +/** + * Subscribe to continuous contract klines(candles) for a symbol futures + */ +public subscribeContinuousContractKlines( + symbol: string, + contractType: 'perpetual' | 'current_quarter' | 'next_quarter', + interval: KlineInterval, + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -getDelegationHistory( - params: DelegationHistoryParams, -): Promise> +/** + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeIndexKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * - * Futures Management Endpoints: - * https://binance-docs.github.io/apidocs/spot/en/#futures - * - * Note: to trade futures use the usdm-client or coinm-client. - * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. - * - **/ + * Subscribe to index klines(candles) for a symbol in a coinm futures + */ +public subscribeMarkPriceKlines( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Execute transfer between spot account and futures account. - * - * Type: - * - 1: transfer from spot account to USDT-Ⓜ futures account. - * - 2: transfer from USDT-Ⓜ futures account to spot account. - * - 3: transfer from spot account to COIN-Ⓜ futures account. - * - 4: transfer from COIN-Ⓜ futures account to spot account. + * Subscribe to mini 24hr ticker for a symbol in market category. */ +public subscribeSymbolMini24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead + * Subscribe to mini 24hr mini ticker in market category. */ -submitNewFutureAccountTransfer( - params: NewFutureAccountTransferParams, -): Promise< +public subscribeAllMini24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Possibly @deprecated, found only in old docs only - * Use sapi/v1/asset/transfer instead + * Subscribe to 24hr ticker for a symbol in any market. */ -getFutureAccountTransferHistory( - params: GetFutureAccountTransferHistoryParams, -): Promise> +public subscribeSymbol24hrTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to Alpha Trading WebSocket Market Data streams. + * Base URL: wss://nbstream.binance.com/w3w/wsa/stream */ -getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise +public subscribeAlpha(topics: string | string[]): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) */ -getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise +public subscribeAlphaAllTokensTicker24(): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to Alpha aggregate trades for a symbol + * @param symbol e.g. ALPHA_474USDT */ -getCrossCollateralWalletV2(): Promise +public subscribeAlphaAggTrade(symbol: string): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to Alpha full depth for a symbol + * @param symbol e.g. ALPHA_474USDT + * @param intervalMs 0, 100, or 500 */ -getAdjustCrossCollateralLTVHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +public subscribeAlphaFulldepth( + symbol: string, + intervalMs: 0 | 100 | 500 = 500, +): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to Alpha klines for a contract + * @param contractAddress Contract address + * @param chainId Chain ID (e.g. CT_501, 56) + * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d */ -getCrossCollateralLiquidationHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +public subscribeAlphaKline( + contractAddress: string, + chainId: string, + interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', +): Promise ⋮---- /** - * @deprecated as of 2023-09-25 + * Subscribe to 24hr ticker in any market. */ -getCrossCollateralInterestHistory( - params?: GetLoanCoinPaginatedHistoryParams, -): Promise +public subscribeAll24hrTickers( + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** + * Subscribe to rolling window ticker statistics for all market symbols, + * computed over multiple windows. Note that only tickers that have + * changed will be present in the array. * - * WALLET Endpoints - Account endpoints - * - **/ -⋮---- -getAccountInfo(): Promise -⋮---- -getDailyAccountSnapshot( - params: DailyAccountSnapshotParams, -): Promise + * Notes: + * - Supported window sizes: 1h,4h,1d. + * - Supported markets: spot + */ +public subscribeAllRollingWindowTickers( + market: 'spot', + windowSize: '1h' | '4h' | '1d', + wsKeyOverride?: WsKey, +): Promise ⋮---- -disableFastWithdrawSwitch(): Promise +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolBookTicker( + symbol: string, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -enableFastWithdrawSwitch(): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllBookTickers( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -getAccountStatus(): Promise< +/** + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSymbolLiquidationOrders( + symbol: string, + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -getApiTradingStatus(): Promise +/** + * Subscribe to best bid/ask for all symbols in spot markets. + */ +public subscribeAllLiquidationOrders( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- -getApiKeyPermissions(): Promise +/** + * Subscribe to partial book depths (snapshots). + * + * Note: + * - spot only supports 1000ms or 100ms for updateMs + * - futures only support 100, 250 or 500ms for updateMs + */ +public subscribePartialBookDepths( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 100 | 250 | 500 | 1000, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** + * Subscribe to orderbook depth updates to locally manage an order book. * - * WALLET Endpoints - Travel Rule endpoints + * Note that the updatems parameter depends on which market you're trading * - **/ + * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams + */ +public subscribeDiffBookDepth( + symbol: string, + updateMs: 100 | 250 | 500 | 1000 = 100, + market: 'spot' | 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Submit a withdrawal request for local entities that require travel rule - * - * For questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire + * Subscribe to best bid/ask for all symbols in spot markets. */ -withdrawTravelRule(params: WithdrawTravelRuleParams): Promise< +public subscribeContractInfoStream( + market: 'usdm' | 'coinm', + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Fetch withdraw history for local entities that require travel rule - */ -getTravelRuleWithdrawHistory( - params?: GetTravelRuleWithdrawHistoryParams, -): Promise + * -------------------------- + * SPOT market websocket streams + * -------------------------- + **/ ⋮---- /** - * Fetch withdraw history for local entities that require travel rule + * Subscribe to aggregate trades for a symbol in spot markets. */ -getTravelRuleWithdrawHistoryV2( - params?: GetTravelRuleWithdrawHistoryV2Params, -): Promise +public subscribeSpotAggregateTrades( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Submit questionnaire for local entities that require travel rule - * - * for questionaire format, please refer to the docs: - * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire + * Subscribe to trades for a symbol in spot markets. */ -submitTravelRuleDepositQuestionnaire( - params: SubmitTravelRuleDepositQuestionnaireParams, -): Promise +public subscribeSpotTrades( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Fetch deposit history for local entities that require travel rule + * Subscribe to block trades for a symbol in spot markets. */ -getTravelRuleDepositHistory( - params?: GetTravelRuleDepositHistoryParams, -): Promise +public subscribeSpotBlockTrades( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * Fetch the onboarded VASP list for local entities that require travel rule. - * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. - * Both vaspCode and identifier accepted until 28 May 2026. + * Subscribe to candles for a symbol in spot markets. */ -getOnboardedVASPList(): Promise -⋮---- -getTravelRuleCountryList(): Promise -⋮---- -getTravelRuleRegionList( - params: GetTravelRuleRegionListParams, -): Promise -⋮---- -/** - * - * WALLET Endpoints - Other endpoints - * - **/ -⋮---- -getSystemStatus(): Promise -⋮---- -getDelistSchedule(): Promise +public subscribeSpotKline( + symbol: string, + interval: KlineInterval, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * - * SUB ACCOUNT Endpoints - Account management - * - **/ -⋮---- -createVirtualSubAccount( - params: CreateSubAccountParams, -): Promise -⋮---- -getSubAccountList( - params?: SubAccountListParams, -): Promise -⋮---- -subAccountEnableFutures(email: string): Promise + * Subscribe to mini 24hr ticker for a symbol in spot markets. + */ +public subscribeSpotSymbolMini24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. + * Subscribe to mini 24hr mini ticker in spot markets. */ -subAccountEnableMargin(email: string): Promise -⋮---- -enableOptionsForSubAccount(params: { - email: string; -}): Promise +public subscribeSpotAllMini24hrTickers( + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * @deprecated as of 2025-06-03 - * User now should make the initial transfer in the Margin account to enable it. + * Subscribe to 24hr ticker for a symbol in spot markets. */ -subAccountEnableLeverageToken( - params: SubAccountEnableLeverageToken, -): Promise -⋮---- -getSubAccountStatusOnMarginOrFutures(params?: { - email?: string; -}): Promise -⋮---- -getSubAccountFuturesPositionRisk( - email: string, -): Promise -⋮---- -getSubAccountFuturesPositionRiskV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountTransactionStatistics(params: { - email: string; -}): Promise +public subscribeSpotSymbol24hrTicker( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * - * SUB ACCOUNT Endpoints - API management - * - **/ -⋮---- -getSubAccountIPRestriction( - params: BasicSubAccount, -): Promise -⋮---- -subAccountDeleteIPList( - params: SubAccountAddOrDeleteIPList, -): Promise -⋮---- -subAccountAddIPRestriction( - params: AddIpRestriction, -): Promise + * Subscribe to 24hr ticker in spot markets. + */ +public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise ⋮---- /** - * @deprecated - * Use subAccountAddIPRestriction instead - **/ -subAccountAddIPList( - params: SubAccountEnableOrDisableIPRestriction, -): Promise + * Subscribe to best bid/ask for symbol in spot markets. + */ +public subscribeSpotSymbolBookTicker( + symbol: string, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * @deprecated - * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList - **/ -subAccountEnableOrDisableIPRestriction( - params: EnableOrDisableIPRestrictionForSubAccountParams, -): Promise + * Subscribe to top bid/ask levels for symbol in spot markets. + */ +public subscribeSpotPartialBookDepth( + symbol: string, + levels: 5 | 10 | 20, + updateMs: 1000 | 100 = 1000, + wsKeyOverride?: WsKey, +): Promise ⋮---- /** - * - * SUB ACCOUNT Endpoints - Asset management - * - **/ -⋮---- -subAccountFuturesTransfer( - params: SubAccountTransferParams, -): Promise -⋮---- -getSubAccountFuturesAccountDetail( - email: string, -): Promise -⋮---- -getSubAccountDetailOnFuturesAccountV2( - params: BasicFuturesSubAccountParams, -): Promise -⋮---- -getSubAccountDetailOnMarginAccount( - email: string, -): Promise -⋮---- -getSubAccountDepositAddress( - params: SubAccountDepositAddressParams, -): Promise + * Subscribe to spot orderbook depth updates to locally manage an order book. + */ +public subscribeSpotDiffBookDepth( + symbol: string, + updateMs: 1000 | 100 = 1000, + wsKeyOverride?: WsKey, +): Promise + +================ +File: src/types/spot.ts +================ +import { + ExchangeFilter, + ExchangeSymbol, + GenericCodeMsgError, + numberInString, + OCOOrderStatus, + OCOStatus, + OrderBookRow, + OrderResponseType, + OrderSide, + OrderStatus, + OrderTimeInForce, + OrderType, + RateLimiter, + SelfTradePreventionMode, + SideEffects, + StringBoolean, + SymbolFilter, +} from './shared'; ⋮---- -getSubAccountDepositHistory( - params: SubAccountDepositHistoryParams, -): Promise +export interface BasicTimeRangeParam { + startTime?: number; + endTime?: number; +} ⋮---- -getSubAccountFuturesAccountSummary(): Promise +export interface BasicFromPaginatedParams { + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getSubAccountSummaryOnFuturesAccountV2( - params: SubAccountSummaryOnFuturesAccountV2Params, -): Promise +export type SymbolStatus = + | 'PRE_TRADING' + | 'TRADING' + | 'POST_TRADING' + | 'END_OF_DAY' + | 'HALT' + | 'AUCTION_MATCH' + | 'BREAK' + | 'CANCEL_ONLY'; ⋮---- -getSubAccountsSummaryOfMarginAccount(): Promise +export interface SystemStatusResponse { + status: 0 | 1; + msg: 'normal' | 'system maintenance'; +} ⋮---- -subAccountMarginTransfer( - params: SubAccountTransferParams, -): Promise +export interface DailyAccountSnapshotParams { + type: 'SPOT' | 'MARGIN' | 'FUTURES'; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getSubAccountAssets( - params: SubAccountAssetsParams, -): Promise +export interface SpotBalance { + asset: string; + free: numberInString; + locked: numberInString; +} ⋮---- -getSubAccountAssetsMaster(params: +export interface MarginBalance { + asset: string; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; +} ⋮---- -getSubAccountFuturesAssetTransferHistory( - params: SubAccountFuturesAssetTransferHistoryParams, -): Promise +export interface DailyFuturesBalance { + asset: string; + marginBalance: numberInString; + walletBalance: numberInString; +} ⋮---- -getSubAccountSpotAssetTransferHistory( - params?: SubAccountSpotAssetTransferHistoryParams, -): Promise +export interface DailyFuturesPositionState { + entryPrice: numberInString; + markPrice: numberInString; + positionAmt: numberInString; + symbol: string; + unRealizedProfit: numberInString; +} ⋮---- -getSubAccountSpotAssetsSummary( - params?: SubAccountSpotAssetsSummaryParams, -): Promise +export interface DailySpotAccountSnapshot { + data: { + balances: SpotBalance[]; + totalAssetOfBtc: numberInString; + }; + type: 'spot'; + updateTime: number; +} ⋮---- -getSubAccountUniversalTransferHistory( - params?: SubAccountUniversalTransferHistoryParams, -): Promise +export interface DailyMarginAccountSnapshot { + data: { + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + userAssets: MarginBalance[]; + }; + type: 'margin'; + updateTime: number; +} ⋮---- -subAccountFuturesAssetTransfer( - params: SubAccountFuturesAssetTransferParams, -): Promise +export interface DailyFuturesAccountSnapshot { + data: { + assets: DailyFuturesBalance[]; + position: DailyFuturesPositionState[]; + }; + type: 'futures'; + updateTime: number; +} ⋮---- -subAccountTransferHistory( - params?: SubAccountTransferHistoryParams, -): Promise +export type DailyAccountSnapshotElement = + | DailySpotAccountSnapshot + | DailyMarginAccountSnapshot + | DailyFuturesAccountSnapshot; ⋮---- -subAccountTransferToMaster( - params: SubAccountTransferToMasterParams, -): Promise +export interface DailyAccountSnapshot { + code: number; + msg: string; + snapshotVos: DailyAccountSnapshotElement[]; +} ⋮---- -subAccountTransferToSameMaster( - params: SubAccountTransferToSameMasterParams, -): Promise +export interface CoinNetwork { + addressRegex: string; + coin: string; + depositDesc: string; + depositEnable: boolean; + isDefault: boolean; + memoRegex: string; + minConfirm: number; + name: string; + network: string; + resetAddressStatus: boolean; + specialTips?: string; + specialWithdrawTips?: string; + unlockConfirm: number; + withdrawDesc: string; + withdrawEnable: boolean; + withdrawFee: numberInString; + withdrawMin: numberInString; + withdrawMax: numberInString; + withdrawInternalMin: numberInString; + withdrawIntegerMultiple: numberInString; + depositDust?: numberInString; + sameAddress: boolean; + estimatedArrivalTime: number; + busy: boolean; + contractAddressUrl?: string; + contractAddress?: string; +} ⋮---- -subAccountUniversalTransfer( - params: SubAccountUniversalTransferParams, -): Promise +export interface AllCoinsInformationResponse { + coin: string; + depositAllEnable: boolean; + free: numberInString; + freeze: numberInString; + ipoable: numberInString; + ipoing: numberInString; + isLegalMoney: boolean; + locked: numberInString; + name: string; + networkList: CoinNetwork[]; + storage: numberInString; + trading: boolean; + withdrawAllEnable: boolean; + withdrawing: numberInString; +} ⋮---- -subAccountMovePosition( - params: SubAccountMovePositionParams, -): Promise< +export interface WithdrawParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; + amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; +} ⋮---- -getSubAccountFuturesPositionMoveHistory( - params: SubAccountMovePositionHistoryParams, -): Promise< +export interface TransferBrokerSubAccountParams { + fromId?: string; + toId?: string; + clientTranId?: string; + asset: string; + amount: number; +} ⋮---- -/** - * - * SUB ACCOUNT Endpoints - Managed Sub Account - * - **/ +export interface ConvertQuoteRequestParams { + fromAsset: string; + toAsset: string; + fromAmount?: number; + toAmount?: number; + walletType?: string; + validTime?: string; +} ⋮---- -depositAssetsIntoManagedSubAccount( - params: SubAccountTransferToSameMasterParams, -): Promise +export interface EnableConvertSubAccountParams { + subAccountId: string; + convert: boolean; +} ⋮---- -getManagedSubAccountDepositAddress( - params: ManagedSubAccountDepositAddressParams, -): Promise +export interface AcceptQuoteRequestParams { + quoteId: string; +} ⋮---- -withdrawAssetsFromManagedSubAccount( - params: WithdrawAssetsFromManagedSubAccountParams, -): Promise +export interface GetOrderStatusParams { + orderId?: string; + quoteId?: string; +} ⋮---- -getManagedSubAccountTransfersParent( - params: ManagedSubAccountTransferLogParams, -): Promise< +export interface GetConvertTradeHistoryParams { + startTime: number; + endTime?: number; + limit?: string; +} ⋮---- -getManagedSubAccountTransferLog( - params: ManagedSubAccountTransferTTLogParams, -): Promise< +export interface TransferBrokerSubAccount { + txnId: numberInString; +} ⋮---- -getManagedSubAccountTransfersInvestor( - params: ManagedSubAccountTransferLogParams, -): Promise< +export enum EnumDepositStatus { + Pending = 0, + CreditedButCannotWithdraw = 6, + WrongDeposit = 7, + WaitingUserConfirm = 8, + Success = 1, + Rejected = 2, +} ⋮---- -getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< +export type DepositStatusCode = `${EnumDepositStatus}`; ⋮---- -getManagedSubAccountSnapshot( - params: ManagedSubAccountSnapshotParams, -): Promise +export interface DepositHistoryParams { + coin?: string; // Optional: Filter by coin + status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) + offset?: number; // Optional: Pagination offset (Default: 0) + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + txId?: string; // Optional: Filter by transaction ID + includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +} +⋮---- +coin?: string; // Optional: Filter by coin +status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +offset?: number; // Optional: Pagination offset (Default: 0) +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +txId?: string; // Optional: Filter by transaction ID +includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) ⋮---- -getManagedSubAccountAssetDetails( - email: string, -): Promise +export interface DepositHistory { + amount: numberInString; + coin: string; + network: string; + status: number; + address: string; + addressTag: string; + txId: string; + insertTime: number; + transferType: number; + confirmTimes: string; +} ⋮---- -getManagedSubAccountMarginAssets(params: { - email: string; - accountType?: string; -}): Promise +export enum EnumWithdrawStatus { + EmailSent = 0, + Cancelled = 1, + AwaitingApproval = 2, + Rejected = 3, + Processing = 4, + Failure = 5, + Completed = 6, +} ⋮---- -getManagedSubAccountFuturesAssets(params: { - email: string; - accountType?: string; -}): Promise +export type WithdrawStatusCode = `${EnumWithdrawStatus}`; ⋮---- -/** - * - * AUTO INVEST Endpoints - Market data - * - **/ +export interface WithdrawHistoryParams { + coin?: string; // Optional: Filter by coin + withdrawOrderId?: string; // Optional: Filter by withdraw order ID + status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) + offset?: number; // Optional: Pagination offset + limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) + idList?: string; // Optional: Comma-separated list of withdrawal IDs + startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) + endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +} ⋮---- -getAutoInvestAssets(): Promise< +coin?: string; // Optional: Filter by coin +withdrawOrderId?: string; // Optional: Filter by withdraw order ID +status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) +offset?: number; // Optional: Pagination offset +limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) +idList?: string; // Optional: Comma-separated list of withdrawal IDs +startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) +endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) ⋮---- -getAutoInvestSourceAssets( - params: GetSourceAssetListParams, -): Promise +export enum EnumWithdrawTransferType { + External = 0, + Interal = 1, +} ⋮---- -getAutoInvestTargetAssets( - params: GetTargetAssetListParams, -): Promise +export type WithdrawTransferType = `${EnumWithdrawTransferType}`; ⋮---- -getAutoInvestTargetAssetsROI( - params: GetTargetAssetROIParams, -): Promise +export interface WithdrawHistory { + address: string; + amount: numberInString; + applyTime: string; + coin: string; + id: string; + withdrawOrderId: string; + network: string; + transferType: WithdrawTransferType; + status: number; + transactionFee: numberInString; + txId: string; +} ⋮---- -getAutoInvestIndex(params: { - indexId: number; -}): Promise +export interface DepositAddressParams { + coin: string; + network?: string; + amount?: number; +} ⋮---- -getAutoInvestPlans(params: { - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; -}): Promise +export interface DepositAddressResponse { + address: string; + coin: string; + tag: string; + url: string; +} ⋮---- -/** - * - * AUTO INVEST Endpoints - Trade - * - **/ +export interface ConvertDustParams { + asset: string[]; + accountType?: 'SPOT' | 'MARGIN'; +} ⋮---- -/** - * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction - * - * @param params - * @returns - */ -submitAutoInvestOneTimeTransaction( - params: SubmitOneTimeTransactionParams, -): Promise +export type DustConvertAccountType = 'SPOT' | 'MARGIN'; ⋮---- -updateAutoInvestPlanStatus( - params: ChangePlanStatusParams, -): Promise +export interface DustConvertParams { + asset: string[]; + accountType?: DustConvertAccountType; + clientId?: string; + targetAsset?: string; + thirdPartyClientId?: string; + dustQuotaAssetToTargetAssetPrice?: numberInString; +} ⋮---- -updateAutoInvestmentPlan( - params: EditInvestmentPlanParams, -): Promise +export interface DustConvertibleAssetsParams { + targetAsset: string; + accountType?: DustConvertAccountType; + dustQuotaAssetToTargetAssetPrice?: numberInString; +} ⋮---- -submitAutoInvestRedemption( - params: SubmitIndexLinkedPlanRedemptionParams, -): Promise< +export interface DustConvertibleAssetDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + exchange: numberInString; + toQuotaAssetAmount: numberInString; + toTargetAssetAmount: numberInString; + toTargetAssetOffExchange: numberInString; +} ⋮---- -getAutoInvestSubscriptionTransactions( - params: GetSubscriptionTransactionHistoryParams, -): Promise +export interface DustConvertibleAssetsResponse { + dribbletPercentage: numberInString; + totalTransferQuotaAssetAmount: numberInString; + totalTransferTargetAssetAmount: numberInString; + dribbletBase: numberInString; + details: DustConvertibleAssetDetail[]; +} ⋮---- -getOneTimeTransactionStatus( - params: GetOneTimeTransactionStatusParams, -): Promise +export interface DustInfoDetail { + asset: string; + assetFullName: string; + amountFree: numberInString; + toBTC: numberInString; + toBNB: numberInString; + toBNBOffExchange: numberInString; + exchange: numberInString; +} ⋮---- -submitAutoInvestmentPlan( - params: CreateInvestmentPlanParams, -): Promise +export interface DustInfo { + details: DustInfoDetail[]; + totalTransferBtc: numberInString; + totalTransferBNB: numberInString; + dribbletPercentage: numberInString; +} ⋮---- -getAutoInvestRedemptionHistory( - params: GetIndexLinkedPlanRedemptionHistoryParams, -): Promise +export interface DustConversionResult { + amount: numberInString; + fromAsset: string; + operateTime: number; + serviceChargeAmount: numberInString; + tranId: number; + transferedAmount: numberInString; +} ⋮---- -getAutoInvestPlan(params: GetPlanDetailsParams): Promise +export interface DustConversion { + totalServiceCharge: numberInString; + totalTransfered: numberInString; + transferResult: DustConversionResult[]; +} ⋮---- -getAutoInvestUserIndex(params: { - indexId: number; -}): Promise +export interface UserAssetDribbletDetail { + transId: number; + serviceChargeAmount: numberInString; + amount: numberInString; + operateTime: number; + transferedAmount: numberInString; + fromAsset: string; +} ⋮---- -getAutoInvestRebalanceHistory( - params: GetIndexLinkedPlanRebalanceHistoryParams, -): Promise +export interface UserAssetDribblet { + operateTime: number; + totalTransferedAmount: numberInString; + totalServiceChargeAmount: numberInString; + transId: number; + userAssetDribbletDetails: UserAssetDribbletDetail[]; +} ⋮---- -/** - * - * CONVERT Endpoints - Market Data - * - **/ +export interface DustLog { + total: number; + userAssetDribblets: UserAssetDribblet[]; +} +⋮---- +export enum EnumUniversalTransferType { + SpotToUSDM = 'MAIN_UMFUTURE', + SpotToCOINM = 'MAIN_CMFUTURE', + SpotToMargin = 'MAIN_MARGIN', + SpotToFunding = 'MAIN_FUNDING', + SpotToOptions = 'MAIN_OPTION', + FundingToSpot = 'FUNDING_MAIN', + FundingToUSDM = 'FUNDING_UMFUTURE', + FundingToCOINM = 'FUNDING_CMFUTURE', + FundingToMargin = 'FUNDING_MARGIN', + FundingToOptions = 'FUNDING_OPTION', + USDMToSpot = 'UMFUTURE_MAIN', + USDMToFunding = 'UMFUTURE_FUNDING', + USDMToMargin = 'UMFUTURE_MARGIN', + USDMToOptions = 'UMFUTURE_OPTION', + COINMToSpot = 'CMFUTURE_MAIN', + COINMToFunding = 'CMFUTURE_FUNDING', + COINMToMargin = 'CMFUTURE_MARGIN', + MarginToSpot = 'MARGIN_MAIN', + MarginToUSDM = 'MARGIN_UMFUTURE', + MarginToCOINM = 'MARGIN_CMFUTURE', + MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', + MarginToFunding = 'MARGIN_FUNDING', + MarginToOptions = 'MARGIN_OPTION', + IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', + IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', + OptionsToSpot = 'OPTION_MAIN', + OptionsToUSDM = 'OPTION_UMFUTURE', + OptionsToFunding = 'OPTION_FUNDING', + OptionsToMargin = 'OPTION_MARGIN', +} ⋮---- -getConvertPairs(params: GetAllConvertPairsParams): Promise +export type UniversalTransferType = `${EnumUniversalTransferType}`; ⋮---- -getConvertAssetInfo(): Promise +export interface UniversalTransferParams { + type: UniversalTransferType; + asset: string; + amount: number; + fromSymbol: string; + toSymbol: string; +} ⋮---- -/** - * - * CONVERT Endpoints - Trade - * - **/ +export interface UniversalTransferHistoryParams { + type: UniversalTransferType; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -convertQuoteRequest(params: ConvertQuoteRequestParams): Promise +export interface ExchangeInfoParams { + symbol?: string; + symbols?: string[]; + permissions?: string | string[]; + showPermissionSets?: boolean; + symbolStatus?: string; +} ⋮---- -acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise +type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; +type SpotPegOffsetType = 'PRICE_LEVEL'; ⋮---- -getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise +export interface NewSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> { + symbol: string; + side: OrderSide; + type: T; + timeInForce?: OrderTimeInForce; + quantity?: number; + quoteOrderQty?: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + stopPrice?: number; + trailingDelta?: number; + icebergQty?: number; + newOrderRespType?: RT; + selfTradePreventionMode?: SelfTradePreventionMode; + pegPriceType?: SpotPegPriceType; + pegOffsetValue?: number; + pegOffsetType?: SpotPegOffsetType; + isIsolated?: StringBoolean; + sideEffectType?: SideEffects; + autoRepayAtCancel?: StringBoolean; +} ⋮---- -getOrderStatus(params: GetOrderStatusParams): Promise +export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; +export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; ⋮---- -submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise +export interface ReplaceSpotOrderParams< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends NewSpotOrderParams { + cancelReplaceMode: CancelReplaceMode; + cancelNewClientOrderId?: string; + cancelOrigClientOrderId?: string; + cancelOrderId?: number; + cancelRestrictions?: CancelRestrictions; +} ⋮---- -cancelConvertLimitOrder(params: +export interface GetOCOParams { + symbol?: string; + orderListId?: number; + origClientOrderId?: string; +} ⋮---- -getConvertLimitOpenOrders(): Promise< +export interface NewSpotSOROrderParams { + symbol: string; + side: OrderSide; + type: OrderType; + timeInForce?: OrderTimeInForce; + quantity: number; + price?: number; + newClientOrderId?: string; + strategyId?: number; + strategyType?: number; + icebergQty?: number; + newOrderRespType?: OrderResponseType; + selfTradePreventionMode?: SelfTradePreventionMode; +} ⋮---- -/** - * - * STAKING Endpoints - ETH Staking - Account - * - **/ +export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; ⋮---- -/** - * @deprecated use getEthStakingAccountV2 instead - **/ -getEthStakingAccount(): Promise +export interface APITriggerConditionSymbolStatus { + i: APILockTriggerCondition; + c: number; + v: number; + t: number; +} ⋮---- -getEthStakingAccountV2(): Promise +export interface APITradingStatus { + data: { + isLocked: boolean; + plannedRecoverTime: number; + triggerCondition: Record; + indicators: Record; + updateTime: number; + }; +} ⋮---- -getEthStakingQuota(): Promise +export interface APIPermissions { + ipRestrict: boolean; + createTime: number; + enableReading: boolean; + enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals + enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly + enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed + enableFutures: boolean; // API Key created before your futures account opened does not support futures API service + permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization + enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading + enableSpotAndMarginTrading: boolean; // Spot and margin trading + tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission + enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading + enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading + enablePortfolioMarginTrading: true; +} ⋮---- -/** - * - * STAKING Endpoints - ETH Staking- Staking - * - **/ +enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals +enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly +enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed +enableFutures: boolean; // API Key created before your futures account opened does not support futures API service +permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization +enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading +enableSpotAndMarginTrading: boolean; // Spot and margin trading +tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission +enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading +enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading ⋮---- -/** - * @deprecated use subscribeEthStakingV2 instead - **/ -subscribeEthStakingV1(params: +export interface AssetDetail { + minWithdrawAmount: numberInString; + depositStatus: boolean; + withdrawFee: number; + withdrawStatus: boolean; + depositTip?: string; +} ⋮---- -subscribeEthStakingV2(params: { - amount: number; -}): Promise +export interface SymbolTradeFee { + symbol: string; + makerCommission: numberInString; + takerCommission: numberInString; +} ⋮---- -redeemEth(params: RedeemEthParams): Promise +export interface SymbolExchangeInfo { + symbol: string; + status: string; + baseAsset: string; + baseAssetPrecision: number; + quoteAsset: string; + quotePrecision: number; + quoteAssetPrecision: number; + baseCommissionPrecision: number; + quoteCommissionPrecision: number; + orderTypes: OrderType[]; + icebergAllowed: boolean; + ocoAllowed: boolean; + opoAllowed: boolean; + quoteOrderQtyMarketAllowed: boolean; + allowTrailingStop: boolean; + cancelReplaceAllowed: boolean; + isSpotTradingAllowed: boolean; + isMarginTradingAllowed: boolean; + filters: SymbolFilter[]; + permissions: ('SPOT' | 'MARGIN')[]; + defaultSelfTradePreventionMode: SelfTradePreventionMode; + allowedSelfTradePreventionModes: SelfTradePreventionMode[]; +} ⋮---- -wrapBeth(params: +export interface ExchangeInfo { + timezone: string; + serverTime: number; + rateLimits: RateLimiter[]; + exchangeFilters: ExchangeFilter[]; + symbols: SymbolExchangeInfo[]; +} ⋮---- -/** - * - * STAKING Endpoints - ETH Staking - History - * - **/ +export interface OrderBookResponse { + lastUpdateId: number; + bids: OrderBookRow[]; + asks: OrderBookRow[]; +} ⋮---- -getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< +export interface RawTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; + isBestMatch: boolean; +} ⋮---- -getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< +export interface BlockTrade { + id: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + time: number; + isBuyerMaker: boolean; +} ⋮---- -getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< +export interface HistoricalBlockTradesParams { + symbol: string; + fromId: number; + limit?: number; +} ⋮---- -getWbethRewardsHistory( - params: GetWrapHistoryParams, -): Promise +export interface RawAccountTrade { + symbol: string; + id: number; + orderId: number; + orderListId: number; + price: numberInString; + qty: numberInString; + quoteQty: numberInString; + commission: numberInString; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isBestMatch: boolean; +} ⋮---- -getEthRateHistory(params: GetETHRateHistoryParams): Promise< +export interface AggregateTrade { + a: number; + p: numberInString; + q: numberInString; + f: number; + l: number; + T: number; + m: boolean; + M: boolean; +} ⋮---- -getBethWrapHistory(params: GetWrapHistoryParams): Promise< +export interface CurrentAvgPrice { + mins: number; + price: numberInString; + closeTime: number; +} ⋮---- -getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< +/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ +export interface SpotPriceRangeExecutionRule { + ruleType: 'PRICE_RANGE'; + bidLimitMultUp: numberInString; + bidLimitMultDown: numberInString; + askLimitMultUp: numberInString; + askLimitMultDown: numberInString; +} ⋮---- -/** - * - * BFUSD (sapi/v1/bfusd) - * - **/ +export interface SpotSymbolExecutionRules { + symbol: string; + rules: SpotPriceRangeExecutionRule[]; +} ⋮---- -getBfusdAccount(): Promise +export interface SpotExecutionRulesResponse { + symbolRules: SpotSymbolExecutionRules[]; +} ⋮---- -getBfusdQuota(): Promise +/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ +export interface SpotExecutionRulesParams { + symbol?: string; + symbols?: string[]; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +} ⋮---- -subscribeBfusd( - params: BfusdSubscribeParams, -): Promise +/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ +export interface SpotReferencePriceResponse { + symbol: string; + referencePrice: numberInString | null; + timestamp: number; +} ⋮---- -redeemBfusd(params: BfusdRedeemParams): Promise +/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ +export interface SpotReferencePriceNeverSetError { + code: -2043; + msg: string; +} ⋮---- -getBfusdSubscriptionHistory( - params: GetBfusdSubscriptionHistoryParams, -): Promise< +export type SpotReferencePriceResult = + | SpotReferencePriceResponse + | SpotReferencePriceNeverSetError; ⋮---- -getBfusdRedemptionHistory( - params: GetBfusdRedemptionHistoryParams, -): Promise< +/** Reference price is computed as an arithmetic mean in the matching engine. */ +export interface SpotReferencePriceCalculationArithmeticMean { + symbol: string; + calculationType: 'ARITHMETIC_MEAN'; + bucketCount: number; + bucketWidthMs: number; +} ⋮---- -getBfusdRewardsHistory( - params: GetBfusdRewardsHistoryParams, -): Promise< +/** Reference price is computed outside the matching engine. */ +export interface SpotReferencePriceCalculationExternal { + symbol: string; + calculationType: 'EXTERNAL'; + externalCalculationId: number; +} ⋮---- -getBfusdRateHistory( - params: GetBfusdRateHistoryParams, -): Promise< +export type SpotReferencePriceCalculationResponse = + | SpotReferencePriceCalculationArithmeticMean + | SpotReferencePriceCalculationExternal + | SpotReferencePriceNeverSetError; ⋮---- -/** - * - * RWUSD (sapi/v1/rwusd) - * - **/ +export interface DailyChangeStatistic { + symbol: string; + priceChange: numberInString; + priceChangePercent: numberInString; + weightedAvgPrice: numberInString; + prevClosePrice: numberInString; + lastPrice: numberInString; + lastQty: numberInString; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; + openPrice: numberInString; + highPrice: numberInString; + lowPrice: numberInString; + volume: numberInString; + quoteVolume: numberInString; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- -getRwusdAccount(): Promise +export interface SymbolOrderBookTicker { + symbol: string; + bidPrice: numberInString; + bidQty: numberInString; + askPrice: numberInString; + askQty: numberInString; +} ⋮---- -getRwusdQuota(): Promise +export interface OrderResponseACK { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; +} ⋮---- -subscribeRwusd( - params: RwusdSubscribeParams, -): Promise +/** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ +export interface SpotNewOrderConditionalFields { + icebergQty?: numberInString; + preventedMatchId?: number; + preventedQuantity?: numberInString; + stopPrice?: numberInString; + strategyId?: number; + strategyType?: number; + trailingDelta?: number; + trailingTime?: number; + pegPriceType?: SpotPegPriceType; + pegOffsetType?: SpotPegOffsetType; + pegOffsetValue?: number; + peggedPrice?: numberInString; +} ⋮---- -redeemRwusd(params: RwusdRedeemParams): Promise +export interface OrderResponseResult extends SpotNewOrderConditionalFields { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; +} ⋮---- -getRwusdSubscriptionHistory( - params: GetRwusdSubscriptionHistoryParams, -): Promise< +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -getRwusdRedemptionHistory( - params: GetRwusdRedemptionHistoryParams, -): Promise< +export interface OrderFill { + price: numberInString; + qty: numberInString; + commission: numberInString | null; + commissionAsset: string | null; + tradeId: number; +} ⋮---- -getRwusdRewardsHistory( - params: GetRwusdRewardsHistoryParams, -): Promise< +export interface OrderResponseFull extends SpotNewOrderConditionalFields { + symbol: string; + orderId: number; + orderListId?: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + origQuoteOrderQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + marginBuyBorrowAmount?: number; + marginBuyBorrowAsset?: string; + isIsolated?: boolean; + workingTime: number; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ + expiryReason?: string; + fills: OrderFill[]; +} ⋮---- -getRwusdRateHistory( - params: GetRwusdRateHistoryParams, -): Promise< +/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ ⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingProducts( - params: StakingBasicParams & { - asset?: string; - }, -): Promise +export type OrderResponse = + | OrderResponseACK + | OrderResponseResult + | OrderResponseFull; ⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingProductPosition( - params: StakingBasicParams & { - productId?: string; - asset?: string; - }, -): Promise +export type OrderResponseTypeFor< + RT extends OrderResponseType | undefined = undefined, + T extends OrderType | undefined = undefined, +> = RT extends 'ACK' + ? OrderResponseACK + : RT extends 'RESULT' + ? OrderResponseResult + : RT extends 'FULL' + ? OrderResponseFull + : T extends 'MARKET' | 'LIMIT' + ? OrderResponseFull + : OrderResponseACK; ⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getStakingHistory(params: StakingHistoryParams): Promise +export interface OrderListOrder { + symbol: string; + orderId: number; + clientOrderId: string; + /** Present only for expired orders. */ + expiryReason?: string; +} ⋮---- -/** - * @deprecated as of 2024-01-19 - */ -getPersonalLeftQuotaOfStakingProduct(params: { - product: StakingProductType; - productId: string; -}): Promise +/** Present only for expired orders. */ ⋮---- -/** - * - * STAKING Endpoints - SOL Staking- Account - * - **/ +export interface OrderListResponse { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: [OrderListOrder, OrderListOrder]; + orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; +} ⋮---- -getSolStakingAccount(): Promise +export interface OrderList { + orderListId: number; + contingencyType: 'OCO'; + listStatusType: OCOStatus; + listOrderStatus: OCOOrderStatus; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: [OrderListOrder, OrderListOrder]; +} +export interface SOROrderFill { + matchType: string; + price: numberInString; + qty: numberInString; + commission: numberInString; + commissionAsset: string; + tradeId: number; + allocId: number; +} ⋮---- -getSolStakingQuota(): Promise +export type SOROrderResponseFull = OrderResponseFull & { + workingTime: number; + fills: SOROrderFill[]; + workingFloor: string; + selfTradePreventionMode: string; + usedSor: true; +}; ⋮---- -/** - * - * STAKING Endpoints - SOL Staking - Staking - * - **/ +export interface SORTestOrderResponse { + standardCommissionForOrder: { + //Standard commission rates on trades from the order. + maker: numberInString; + taker: numberInString; + }; + taxCommissionForOrder: { + //Tax commission rates for trades from the order. + maker: numberInString; + taker: numberInString; + }; + discount: { + //Discount on standard commissions when paying in BNB. + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ + discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. Staff later confirmed this is a multiplier: 0.75 means pay 75% of standard. The FAQ 0.25 example is fictional. + }; +} ⋮---- -subscribeSolStaking(params: { - amount: number; -}): Promise +//Standard commission rates on trades from the order. ⋮---- -redeemSol(params: +//Tax commission rates for trades from the order. ⋮---- -claimSolBoostRewards(): Promise< +//Discount on standard commissions when paying in BNB. ⋮---- /** - * - * STAKING Endpoints - SOL Staking- History - * - **/ + * Multiplier on standard commission when paying in `discountAsset`. + * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. + */ +discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. Staff later confirmed this is a multiplier: 0.75 means pay 75% of standard. The FAQ 0.25 example is fictional. ⋮---- -getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< +export interface CancelSpotOrderResult { + symbol: string; + origClientOrderId: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + selfTradePreventionMode: SelfTradePreventionMode; +} ⋮---- -getSolRedemptionHistory(params?: { - rows: SolRedemptionHistoryRecord[]; - total: number; -}): Promise +export interface CancelOrderListResult extends OrderList { + orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; +} ⋮---- -getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< +export interface GenericReplaceSpotOrderResult { + cancelResult: 'SUCCESS' | 'FAILURE'; + newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; + cancelResponse: C; + newOrderResponse: N; +} ⋮---- -getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< +export interface ReplaceSpotOrderCancelStopFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'NOT_ATTEMPTED'; +} ⋮---- -getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< +export interface ReplaceSpotOrderNewFailure + extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + GenericCodeMsgError + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'FAILURE'; +} ⋮---- -getSolUnclaimedRewards(): Promise< - { - amount: string; - rewardsAsset: string; - }[] +export interface ReplaceSpotOrderCancelAllowFailure + extends GenericReplaceSpotOrderResult { + cancelResult: 'FAILURE'; + newOrderResult: 'SUCCESS'; +} +⋮---- +export interface ReplaceSpotOrderCancelAllFailure + extends GenericReplaceSpotOrderResult< + GenericCodeMsgError, + GenericCodeMsgError > { - return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); + cancelResult: 'FAILURE'; + newOrderResult: 'FAILURE'; +} ⋮---- -/** - * - * STAKING - Onchain Yields - Account - * - **/ +export interface ReplaceSpotOrderResultError { + data: + | ReplaceSpotOrderCancelStopFailure + | ReplaceSpotOrderNewFailure + | ReplaceSpotOrderCancelAllowFailure + | ReplaceSpotOrderCancelAllFailure; +} ⋮---- -getOnchainYieldsLockedProducts( - params?: OnchainYieldsLockedProductListParams, -): Promise +export interface ReplaceSpotOrderResultSuccess< + T extends OrderType = OrderType, + RT extends OrderResponseType | undefined = OrderResponseType, +> extends GenericReplaceSpotOrderResult< + CancelSpotOrderResult, + OrderResponseTypeFor + > { + cancelResult: 'SUCCESS'; + newOrderResult: 'SUCCESS'; +} ⋮---- -getOnchainYieldsLockedPersonalLeftQuota( - params: OnchainYieldsLockedPersonalLeftQuotaParams, -): Promise +export interface SpotOrder { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + price: numberInString; + origQty: numberInString; + executedQty: numberInString; + cummulativeQuoteQty: numberInString; + status: OrderStatus; + timeInForce: OrderTimeInForce; + type: OrderType; + side: OrderSide; + stopPrice: numberInString; + icebergQty: numberInString; + time: number; + updateTime: number; + isWorking: boolean; + origQuoteOrderQty: numberInString; + selfTradePreventionMode: SelfTradePreventionMode; + /** Present only for expired orders. */ + expiryReason?: string; +} ⋮---- -getOnchainYieldsLockedPosition( - params?: OnchainYieldsLockedPositionParams, -): Promise +/** Present only for expired orders. */ +⋮---- +export interface SpotAmendKeepPriorityResult { + transactTime: number; + executionId: number; + amendedOrder: { + symbol: string; + orderId: number; + orderListId: number; + origClientOrderId: string; + clientOrderId: string; + price: string; + qty: string; + executedQty: string; + preventedQty: string; + quoteOrderQty: string; + cumulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }; + listStatus?: { + orderListId: number; + contingencyType: string; + listOrderStatus: string; + listClientOrderId: string; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + }; +} ⋮---- -getOnchainYieldsAccount(): Promise +export interface SpotAssetBalance { + asset: string; + free: numberInString; + locked: numberInString; +} ⋮---- -/** - * - * STAKING - Onchain Yields - Earn - * - **/ +export interface AccountInformation { + makerCommission: number; + takerCommission: number; + buyerCommission: number; + sellerCommission: number; + commissionRates: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + canTrade: boolean; + canWithdraw: boolean; + canDeposit: boolean; + brokered: boolean; + requireSelfTradePrevention: boolean; + preventSor: boolean; + updateTime: number; + accoountType: string; + balances: SpotAssetBalance[]; + permissions: string[]; + uid: number; +} ⋮---- -getOnchainYieldsLockedSubscriptionPreview( - params: OnchainYieldsLockedSubscriptionPreviewParams, -): Promise +export interface CrossMarginAccountTransferParams { + asset: string; + amount: number; + type: 1 | 2; +} ⋮---- -subscribeOnchainYieldsLockedProduct( - params: OnchainYieldsLockedSubscribeParams, -): Promise +export interface MarginTransactionResponse { + tranId: number; +} ⋮---- -setOnchainYieldsLockedAutoSubscribe( - params: OnchainYieldsLockedSetAutoSubscribeParams, -): Promise +export interface MarginAccountLoanParams { + asset: string; + isIsolated: StringBoolean; + symbol: string; + amount: number; + type: 'BORROW' | 'REPAY'; +} ⋮---- -setOnchainYieldsLockedRedeemOption( - params: OnchainYieldsLockedSetRedeemOptionParams, -): Promise +export interface QueryMarginAssetParams { + asset: string; +} ⋮---- -redeemOnchainYieldsLockedProduct( - params: OnchainYieldsLockedRedeemParams, -): Promise +export interface QueryMarginAssetResponse { + assetFullName: string; + assetName: string; + isBorrowable: boolean; + isMortgageable: boolean; + userMinBorrow: numberInString; + userMinRepay: numberInString; + /** + * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. + * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. + */ + delistTime?: number; +} ⋮---- /** - * - * STAKING - Onchain Yields - History - * - **/ + * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. + * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. + */ ⋮---- -getOnchainYieldsLockedSubscriptionRecord( - params?: OnchainYieldsLockedSubscriptionRecordParams, -): Promise +export interface QueryCrossMarginPairParams { + symbol: string; +} ⋮---- -getOnchainYieldsLockedRewardsHistory( - params?: OnchainYieldsLockedRewardsHistoryParams, -): Promise +/** + * Row from `GET /sapi/v1/margin/allPairs`. + * Dev-confirmed: this response has no `delistTime`. Documentation examples that include it are wrong. + */ +export interface QueryCrossMarginPairResponse { + id: number; + symbol: string; + base: string; + quote: string; + isMarginTrade: boolean; + isBuyAllowed: boolean; + isSellAllowed: boolean; +} ⋮---- -getOnchainYieldsLockedRedemptionRecord( - params?: OnchainYieldsLockedRedemptionRecordParams, -): Promise +export interface QueryMarginPriceIndexResponse { + calcTime: number; + price: numberInString; + symbol: string; +} ⋮---- -/** - * - * STAKING - Soft staking - * - **/ +export interface QueryMarginRecordParams { + asset: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + archived?: boolean; +} ⋮---- -getSoftStakingProductList( - params?: GetSoftStakingProductListParams, -): Promise +export interface GetMarginAccountBorrowRepayRecordsParams { + asset?: string; + isolatedSymbol?: string; + txId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + type: 'BORROW' | 'REPAY'; +} ⋮---- -setSoftStaking( - params: SetSoftStakingParams, -): Promise +export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; ⋮---- -getSoftStakingRewardsHistory( - params?: GetSoftStakingRewardsHistoryParams, -): Promise +export interface MarginAccountRecord { + isolatedSymbol?: string; + asset: string; + principal: numberInString; + status: LoanStatus; + timestamp: number; + txId: number; +} ⋮---- -/** - * - * COPY TRADING Endpoints - Future copy trading - * - **/ +export interface QueryCrossMarginAccountDetailsParams { + created: boolean; + borrowEnabled: boolean; + marginLevel: numberInString; + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; + totalCollateralValueInUSDT: numberInString; + totalOpenOrderLossInUSDT: numberInString; + tradeEnabled: boolean; + transferInEnabled: boolean; + transferOutEnabled: boolean; + accountType: string; + userAssets: MarginBalance[]; +} ⋮---- -getFuturesLeadTraderStatus(): Promise +export interface BasicMarginAssetParams { + asset: string; + isolatedSymbol?: string; +} ⋮---- -getFuturesLeadTradingSymbolWhitelist(): Promise< - GetFuturesLeadTradingSymbolWhitelistResponse[] - > { - return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); +export interface QueryMaxBorrowResponse { + amount: numberInString; + borrowLimit: numberInString; +} ⋮---- -/** - * - * MINING Endpoints - rest api - * - **/ +export interface QueryMaxTransferOutAmountResponse { + amount: numberInString; +} ⋮---- -getMiningAlgos(): Promise +export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; ⋮---- -getMiningCoins(): Promise +export interface IsolatedMarginAccountTransferParams { + asset: string; + symbol: string; + transFrom: IsolatedMarginTransfer; + transTo: IsolatedMarginTransfer; + amount: number; +} ⋮---- -getHashrateResales( - params: GetHashrateResaleListParams, -): Promise +export interface IsolatedMarginAccountAsset { + asset: string; + borrowEnabled: boolean; + borrowed: numberInString; + free: numberInString; + interest: numberInString; + locked: numberInString; + netAsset: numberInString; + netAssetOfBtc: numberInString; + repayEnabled: boolean; + totalAsset: numberInString; +} ⋮---- -getMiners(params: GetMinerListParams): Promise +export type IsolatedMarginLevelStatus = + | 'EXCESSIVE' + | 'NORMAL' + | 'MARGIN_CALL' + | 'PRE_LIQUIDATION' + | 'FORCE_LIQUIDATION'; ⋮---- -getMinerDetails( - params: GetMinerDetailsParams, -): Promise +export interface IsolatedMarginAccountAssets { + baseAsset: IsolatedMarginAccountAsset; + quoteAsset: IsolatedMarginAccountAsset; + symbol: string; + isolatedCreated: boolean; + enabled: boolean; + marginLevel: numberInString; + marginLevelStatus: IsolatedMarginLevelStatus; + marginRatio: numberInString; + indexPrice: numberInString; + liquidatePrice: numberInString; + liquidateRate: numberInString; + tradeEnabled: boolean; +} ⋮---- -getExtraBonuses( - params: GetExtraBonusListParams, -): Promise +export interface IsolatedMarginAccountInfo { + assets: IsolatedMarginAccountAssets[]; + totalAssetOfBtc?: numberInString; + totalLiabilityOfBtc?: numberInString; + totalNetAssetOfBtc?: numberInString; +} ⋮---- -getMiningEarnings( - params: GetEarningsListParams, -): Promise +export interface SpotSubUserAssetBtcList { + email: string; + totalAsset: numberInString; +} ⋮---- -cancelHashrateResaleConfig( - params: CancelHashrateResaleConfigParams, -): Promise +export interface SubAccountList { + email: string; + isFreeze: boolean; + createTime: number; + isManagedSubAccount: boolean; + isAssetManagementSubAccount: boolean; +} ⋮---- -getHashrateResale( - params: GetHashrateResaleDetailParams, -): Promise +export interface SubAccountDepositHistoryList { + depositId: number; + subAccountId: string; + amount: string; + coin: string; + network: string; + status: number; + address: string; + addressTag: string; + txId: string; + insertTime: number; + sourceAddress: string; + confirmTimes: string; +} ⋮---- -getMiningAccountEarnings( - params: GetMiningAccountEarningParams, -): Promise +export interface SubAccountTransferHistoryList { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} ⋮---- -getMiningStatistics( - params: GetStatisticListParams, -): Promise +export interface SubAccountBasicTransfer { + from: string; + to: string; + asset: string; + qty: numberInString; + tranId: number; + time: number; +} ⋮---- -submitHashrateResale(params: SubmitHashrateResaleParams): Promise +export interface MarginTradeCoeffVo { + forceLiquidationBar: numberInString; + marginCallBar: numberInString; + normalBar: numberInString; +} ⋮---- -getMiningAccounts( - params: getMiningAccountsListParams, -): Promise +export interface SubAccountStatus { + email: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + insertTime: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + mobile: number; +} ⋮---- -/** - * - * ALGO TRADING Endpoints - Future algo - * - **/ +export interface BasicBtcTotals { + totalAssetOfBtc: numberInString; + totalLiabilityOfBtc: numberInString; + totalNetAssetOfBtc: numberInString; +} ⋮---- -submitVpNewOrder( - params: SubmitVpNewOrderParams, -): Promise +export interface FuturesSubAccountAssets { + asset: string; + initialMargin: numberInString; + maintenanceMargin: numberInString; + marginBalance: numberInString; + maxWithdrawAmount: numberInString; + openOrderInitialMargin: numberInString; + positionInitialMargin: numberInString; + unrealizedProfit: numberInString; + walletBalance: numberInString; +} ⋮---- -submitTwapNewOrder( - params: SubmitTwapNewOrderParams, -): Promise +export interface FuturesSubAccountList { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + email: string; +} ⋮---- -cancelAlgoOrder( - params: - | { algoId: number; clientAlgoId?: string } - | { clientAlgoId: string; algoId?: number }, -): Promise +export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; ⋮---- -getAlgoSubOrders( - params: GetAlgoSubOrdersParams, -): Promise +export interface SubAccountTransferHistory { + counterParty: string; + email: string; + type: number; + asset: string; + qty: numberInString; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + tranId: number; + time: number; +} ⋮---- -getAlgoOpenOrders(): Promise< +export interface SubAccountUniversalTransferHistory { + tranId: number; + fromEmail: string; + toEmail: string; + asset: string; + amount: numberInString; + createTimeStamp: number; + fromAccountType: AccountType; + toAccountType: AccountType; + status: string; + clientTranId?: string; +} ⋮---- -getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< +export interface BasicSubAccount { + email: string; + subAccountApiKey: string; +} ⋮---- -/** - * - * ALGO TRADING Endpoints - Spot algo - * - **/ +export interface CreateSubAccountParams { + subAccountString: string; +} ⋮---- -submitSpotAlgoTwapOrder( - params: SubmitSpotTwapNewOrderParams, -): Promise +export interface EnableOrDisableIPRestrictionForSubAccountParams + extends BasicSubAccount { + ipAddress?: string; +} ⋮---- -cancelSpotAlgoOrder( - params: - | { algoId: number; clientAlgoId?: string } - | { clientAlgoId: string; algoId?: number }, -): Promise +export interface GetBrokerSubAccountHistoryParams { + fromId?: string; + toId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; +} ⋮---- -getSpotAlgoSubOrders( - params: GetSpotAlgoSubOrdersParams, -): Promise +export interface CreateBrokerSubAccountParams { + tag?: string; +} ⋮---- -getSpotAlgoOpenOrders(): Promise< +export interface GetBrokerSubAccountParams { + subAccountId?: string; + page?: number; + size?: number; +} ⋮---- -getSpotAlgoHistoricalOrders( - params: GetSpotAlgoHistoricalOrdersParams, -): Promise< +export interface GetApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey?: string; + page?: number; + size?: number; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Market data - * - **/ +export interface CreateApiKeyBrokerSubAccountParams { + subAccountId: string; + canTrade: boolean; + marginTrade?: boolean; + futuresTrade?: boolean; +} +export interface ApiKeyBrokerSubAccount { + subAccountId: string; + apiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} ⋮---- -getCryptoLoanFlexibleCollateralAssets(params: { - collateralCoin?: string; -}): Promise< +export interface UpdateIpRestrictionForSubApiKey { + subAccountId: string; + ipAddress?: string; + subAccountApiKey: string; + status: string; +} ⋮---- -getCryptoLoanFlexibleAssets(params: +export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canUniversalTransfer: boolean; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - Trade - * - **/ +export interface EnableMarginBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} ⋮---- -borrowCryptoLoanFlexible( - params: BorrowFlexibleLoanParams, -): Promise +export interface EnableMarginBrokerSubAccountResponse { + subAccountId: string; + enableMargin: boolean; + updateTime: number; +} ⋮---- -repayCryptoLoanFlexible( - params: RepayCryptoFlexibleLoanParams, -): Promise +export interface EnableFuturesBrokerSubAccountParams { + subAccountId: string; + futures: boolean; +} ⋮---- -repayCryptoLoanFlexibleWithCollateral( - params: RepayCryptoLoanFlexibleWithCollateralParams, -): Promise +export interface EnableFuturesBrokerSubAccountResponse { + subAccountId: string; + enableFutures: boolean; + updateTime: number; +} ⋮---- -adjustCryptoLoanFlexibleLTV( - params: AdjustFlexibleCryptoLoanLTVParams, -): Promise +export interface EnableMarginApiKeyBrokerSubAccountParams { + subAccountId: string; + margin: boolean; +} +export interface UniversalTransferBrokerParams { + fromId?: string; + toId?: string; + fromAccountType: string; + toAccountType: string; + asset: string; + amount: number; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Flexible rate - User info - * - **/ +export interface GetUniversalTransferBrokerParams { + fromId?: string; + toId?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; + showAllStatus?: boolean; +} ⋮---- -getCryptoLoanFlexibleLTVAdjustmentHistory( - params: GetFlexibleLoanLTVAdjustmentHistoryParams, -): Promise< +export interface GetBrokerSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; +} ⋮---- -getFlexibleLoanCollateralRepayRate(params: { - loanCoin: string; - collateralCoin: string; -}): Promise< +export interface DeleteApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; +} ⋮---- -getLoanFlexibleBorrowHistory( - params: GetFlexibleCryptoLoanBorrowHistoryParams, -): Promise< +export interface ChangePermissionApiKeyBrokerSubAccountParams { + subAccountId: string; + subAccountApiKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} ⋮---- -getCryptoLoanFlexibleOngoingOrders( - params: GetFlexibleLoanOngoingOrdersParams, -): Promise< +export interface ChangePermissionApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} ⋮---- -getFlexibleLoanLiquidationHistory( - params?: GetFlexibleLoanLiquidationHistoryParams, -): Promise< +export interface VirtualSubAccount { + email: string; +} ⋮---- -getLoanFlexibleRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise< +export interface BrokerSubAccountHistory { + subAccountsHistory: SubAccountTransferHistoryList[]; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Market data - * - **/ +export interface BrokerSubAccount { + subaccountId: string; + email: string; + makerCommission?: string; + takerCommission?: string; + marginMakerCommission?: string; + marginTakerCommission?: string; + createTime?: number; + tag: string; +} ⋮---- -/** - * @deprecated - */ -getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +export interface CreateApiKeyBrokerSubAccountResponse { + subaccountId: string; + apiKey: string; + secretKey: string; + canTrade: boolean; + marginTrade: boolean; + futuresTrade: boolean; +} ⋮---- -getCryptoLoanCollateralRepayRate( - params: CheckCollateralRepayRateParams, -): Promise +export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { + subAccountId: string; + apikey: string; + canUniversalTransfer: boolean; +} ⋮---- -/** - * @deprecated - */ -getCryptoLoanCollateralAssetsData( - params: GetCollateralAssetDataParams, -): Promise< +export interface GetBrokerInfoResponse { + maxMakerCommission: string; + minMakerCommission: string; + maxTakerCommission: string; + minTakerCommission: string; + subAccountQty: number; + maxSubAccountQty: number; +} +export interface SubAccountListParams { + email?: string; + isFreeze?: StringBoolean; + page?: number; + limit?: number; +} ⋮---- -getCryptoLoansIncomeHistory( - params: GetCryptoLoansIncomeHistoryParams, -): Promise +export interface SubAccountListResponse { + subAccounts: SubAccountList[]; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - Trade - * - **/ +export interface SubAccountSpotAssetTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} ⋮---- -/** - * @deprecated - */ -borrowCryptoLoan( - params: BorrowCryptoLoanParams, -): Promise +export interface SubAccountSpotAssetTransferHistory + extends SubAccountBasicTransfer { + status: string; +} ⋮---- -/** - * @deprecated - */ -repayCryptoLoan( - params: RepayCryptoLoanParams, -): Promise +export interface SubAccountFuturesAssetTransferHistoryParams { + email: string; + futuresType: number; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} ⋮---- -/** - * @deprecated - */ -adjustCryptoLoanLTV( - params: AdjustCryptoLoanLTVParams, -): Promise +export interface SubAccountFuturesAssetTransferHistory { + success: boolean; + futuresType: number; + transfers: SubAccountBasicTransfer[]; +} ⋮---- -/** - * @deprecated - */ -customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< +export interface SubAccountFuturesAssetTransferParams { + fromEmail: string; + toEmail: string; + futuresType: number; + asset: string; + amount: number; +} ⋮---- -/** - * - * CRYPTO LOAN Endpoints - Stable rate - User info - * - **/ +export interface SubAccountFuturesAssetTransfer { + success: boolean; + txnId: numberInString; +} ⋮---- -/** - * @deprecated - */ -getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< +export interface SubAccountAssetsParams { + email: string; +} ⋮---- -getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< +export interface SubAccountAssets { + balances: SpotBalance[]; +} ⋮---- -getCryptoLoanLTVAdjustmentHistory( - params: GetLoanLTVAdjustmentHistoryParams, -): Promise< +export interface SubAccountSpotAssetsSummaryParams { + email?: string; + page?: number; + size?: number; +} ⋮---- -getCryptoLoanRepaymentHistory( - params: GetLoanRepaymentHistoryParams, -): Promise +export interface SubAccountSpotAssetsSummary { + totalCount: number; + masterAccountTotalAsset: numberInString; + spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; +} ⋮---- -/** - * - * SIMPLE EARN Endpoints - Account - * - **/ +export interface SubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} ⋮---- -getSimpleEarnAccount(): Promise +export interface SubAccountDepositAddress { + address: string; + coin: string; + tag: string; + url: string; +} ⋮---- -getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< +export interface SubAccountDepositHistoryParams extends DepositHistoryParams { + email: string; +} ⋮---- -getSimpleEarnLockedProductList( - params?: SimpleEarnProductListParams, -): Promise< +export interface SubAccountEnableMargin { + email: string; + isMarginEnabled: boolean; +} ⋮---- -getFlexibleProductPosition( - params?: SimpleEarnFlexibleProductPositionParams, -): Promise< +export interface SubAccountMarginAccountDetail extends BasicBtcTotals { + email: string; + marginLevel: numberInString; + marginTradeCoeffVo: MarginTradeCoeffVo; + marginUserAssetVoList: MarginBalance[]; +} ⋮---- -getLockedProductPosition( - params?: SimpleEarnLockedProductPositionParams, -): Promise< +export interface SubAccountListBtc extends BasicBtcTotals { + email: string; +} ⋮---- -getFlexiblePersonalLeftQuota(params: +export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { + subAccountList: SubAccountListBtc; +} ⋮---- -getLockedPersonalLeftQuota(params: +export interface SubAccountEnableFutures { + email: string; + isFuturesEnabled: boolean; +} ⋮---- -/** - * - * SIMPLE EARN Endpoints - Earn - * - **/ +export interface SubAccountFuturesAccountDetail { + email: string; + asset: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; +} ⋮---- -purchaseFlexibleProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { + subAccountList: FuturesSubAccountList[]; +} ⋮---- -subscribeSimpleEarnLockedProduct( - params: SimpleEarnSubscribeProductParams, -): Promise +export interface FuturesPositionRisk { + entryPrice: numberInString; + leverage: numberInString; + maxNotional: numberInString; + liquidationPrice: numberInString; + markPrice: numberInString; + positionAmount: numberInString; + symbol: string; + unrealizedProfit: numberInString; +} ⋮---- -redeemFlexibleProduct( - params: SimpleEarnRedeemFlexibleProductParams, -): Promise +export interface SubAccountTransferParams { + email: string; + asset: string; + amount: number; + type: number; +} ⋮---- -redeemLockedProduct(params: { - positionId: string; -}): Promise +export interface SubAccountTransfer { + txnId: numberInString; +} ⋮---- -setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< +export interface SubAccountTransferToSameMasterParams { + toEmail: string; + asset: string; + amount: number; +} ⋮---- -setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< +export interface SubAccountTransferToMasterParams { + asset: string; + amount: number; +} ⋮---- -getFlexibleSubscriptionPreview( - params: GetFlexibleSubscriptionPreviewParams, -): Promise +export interface SubAccountTransferHistoryParams { + asset?: string; + type?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getLockedSubscriptionPreview( - params: GetLockedSubscriptionPreviewParams, -): Promise +export interface SubAccountUniversalTransferParams { + fromEmail?: string; + toEmail?: string; + fromAccountType: AccountType; + toAccountType: AccountType; + clientTranId?: string; + asset: string; + amount: number; +} ⋮---- -setLockedProductRedeemOption(params: { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -}): Promise< +export interface SubAccountMovePositionParams { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + orderArgs: { + symbol: string; + quantity: number; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + }[]; +} +export interface SubAccountUniversalTransfer extends SubAccountTransfer { + clientTranId?: string; +} ⋮---- -/** - * - * SIMPLE EARN Endpoints - History - * - **/ +export interface SubAccountMovePosition { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + symbol: string; + priceType: string; + price: string; + quantity: string; + positionSide: string | null; + side: string; + success: boolean; +} ⋮---- -getFlexibleSubscriptionRecord( - params: GetFlexibleSubscriptionRecordParams, -): Promise< +export interface SubAccountMovePositionHistoryParams { + symbol: string; + productType?: 'UM' | 'OPTION'; + startTime?: number; + endTime?: number; + page: number; + row: number; +} ⋮---- -getLockedSubscriptionRecord( - params: GetLockedSubscriptionRecordParams, -): Promise< +export interface SubAccountMovePositionHistory { + fromUserEmail: string; + toUserEmail: string; + productType: 'UM' | 'OPTION'; + symbol: string; + price: string; + quantity: string; + positionSide: string | null; + side: string; + timeStamp: number; +} ⋮---- -getFlexibleRedemptionRecord( - params: GetFlexibleRedemptionRecordParams, -): Promise< +export interface SubAccountUniversalTransferHistoryParams { + fromEmail?: string; + toEmail?: string; + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +} ⋮---- -getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< +export interface SubAccountUniversalTransferHistoryResponse { + result: SubAccountUniversalTransferHistory[]; + totalCount: number; +} ⋮---- -getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< +export interface SubAccountEnableLeverageToken { + email: string; + enableBlvt: boolean; +} ⋮---- -getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< +export interface AddIpRestriction extends BasicSubAccount { + status: string; + ipAddress: string; +} ⋮---- -getCollateralRecord(params: GetCollateralRecordParams): Promise< +export interface SubAccountEnableOrDisableIPRestriction { + ipRestrict: boolean; + ipList: string[]; + updateTime: number; + apiKey: string; +} ⋮---- -getRateHistory(params: GetRateHistoryParams): Promise< +export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { + ipAddress: string; +} ⋮---- -/** - * - * VIP LOAN Endpoints - Market Data - * - **/ +export interface AddIPListForSubAccountResponseParams { + ip: string; + updateTime: number; + apiKey: string; +} ⋮---- -getVipBorrowInterestRate(params: { - loanCoin: string; -}): Promise +export interface SubAccountAssetDetails { + coin: string; + name: string; + totalBalance: numberInString; + availableBalance: numberInString; + inOrder: numberInString; + btcValue: numberInString; +} ⋮---- -getVipLoanInterestRateHistory( - params: VipLoanInterestRateHistoryParams, -): Promise< +export interface WithdrawAssetsFromManagedSubAccountParams { + fromEmail: string; + asset: string; + amount: number; + transferDate?: number; +} ⋮---- -getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +export interface BasicFuturesSubAccountParams { + email: string; + futuresType: 1 | 2; +} ⋮---- -getVipCollateralAssets(params: +export interface SubAccountSummaryOnFuturesAccountV2Params { + futuresType: 1 | 2; + page?: number; + limit?: number; +} ⋮---- -/** - * - * VIP LOAN Endpoints - User Info - * - **/ +export interface SubAccountUSDMDetail { + futureAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + maxWithdrawAmount: numberInString; + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + updateTime: number; + }; +} ⋮---- -getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< +export interface COINMSubAccount { + email: string; + totalMarginBalance: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; +} ⋮---- -getVipLoanRepaymentHistory( - params: GetVipLoanRepaymentHistoryParams, -): Promise< +export interface SubAccountCOINMDetail { + deliveryAccountResp: { + email: string; + assets: FuturesSubAccountAssets[]; + canDeposit: boolean; + canWithdraw: boolean; + feeTier: number; + updateTime: number; + }; +} ⋮---- -checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< +export interface SubAccountUSDMSummary { + futureAccountSummaryResp: { + totalInitialMargin: numberInString; + totalMaintenanceMargin: numberInString; + totalMarginBalance: numberInString; + totalOpenOrderInitialMargin: numberInString; + totalPositionInitialMargin: numberInString; + totalUnrealizedProfit: numberInString; + totalWalletBalance: numberInString; + asset: string; + subAccountList: FuturesSubAccountList[]; + }; +} ⋮---- -getVipApplicationStatus(params: GetApplicationStatusParams): Promise< +export interface SubAccountCOINMSummary { + deliveryAccountSummaryResp: { + totalMarginBalanceOfBTC: numberInString; + totalUnrealizedProfitOfBTC: numberInString; + totalWalletBalanceOfBTC: numberInString; + asset: string; + subAccountList: COINMSubAccount[]; + }; +} ⋮---- -/** - * - * VIP LOAN Endpoints - Trade - * - **/ +export interface COINMPositionRisk { + entryPrice: numberInString; + markPrice: numberInString; + leverage: numberInString; + isolated: numberInString; + isolatedWallet: numberInString; + isolatedMargin: numberInString; + isAutoAddMargin: numberInString; + positionSide: string; + positionAmount: numberInString; + symbol: string; + unrealizedProfit: numberInString; +} ⋮---- -renewVipLoan(params: VipLoanRenewParams): Promise +export interface SubAccountUSDMPositionRisk { + futurePositionRiskVos: FuturesPositionRisk[]; +} ⋮---- -repayVipLoan(params: VipLoanRepayParams): Promise +export interface SubAccountCOINMPositionRisk { + deliveryPositionRiskVos: COINMPositionRisk[]; +} ⋮---- -borrowVipLoan(params: VipLoanBorrowParams): Promise +export interface StakingProductDetail { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + apy: numberInString; +} ⋮---- -getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< +export interface StakingProductQuota { + totalPersonalQuota: numberInString; + minimum: numberInString; +} ⋮---- -borrowVipLoanFixedRate( - params: VipLoanFixedRateBorrowParams, -): Promise +export interface StakingProduct { + projectId: string; + detail: StakingProductDetail; + quota: StakingProductQuota; +} ⋮---- -/** - * - * DUAL INVESTMENT Endpoints - Market Data - * - **/ +export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; +export type StakingStatus = 'HOLDING' | 'REDEEMED'; +export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; +export type BSwapType = 'SINGLE' | 'COMBINATION'; +export type BSwapOperationType = 'ADD' | 'REMOVE'; ⋮---- -getDualInvestmentProducts( - params: GetDualInvestmentProductListParams, -): Promise< +export interface StakingProductPosition { + positionId: numberInString; + projectId: string; + asset: string; + amount: numberInString; + purchaseTime: numberInString; + duration: numberInString; + accrualDays: numberInString; + rewardAsset: string; + APY: numberInString; + rewardAmt: numberInString; + extraRewardAsset: string; + extraRewardAPY: numberInString; + estExtraRewardAmt: numberInString; + nextInterestPay: numberInString; + nextInterestPayDate: numberInString; + payInterestPeriod: numberInString; + redeemAmountEarly: numberInString; + interestEndDate: numberInString; + deliverDate: numberInString; + redeemPeriod: numberInString; + redeemingAmt: numberInString; + partialAmtDeliverDate: numberInString; + canRedeemEarly: boolean; + renewable: boolean; + type: string; + status: StakingStatus; +} +export interface StakingBasicParams { + product: StakingProductType; + current?: number; + size?: number; +} ⋮---- -/** - * - * DUAL INVESTMENT Endpoints - Trade - * - **/ +export interface FlexibleSavingBasicParams { + status?: string; + featured?: number; + current?: number; + size?: number; + asset?: string; +} ⋮---- -subscribeDualInvestmentProduct( - params: SubscribeDualInvestmentProductParams, -): Promise +export interface FlexibleProductPositionParams { + status?: string; + featured?: number; + current?: number; + size?: number; +} ⋮---- -getDualInvestmentPositions( - params: GetDualInvestmentPositionsParams, -): Promise< +export interface PurchaseFlexibleProductParams { + productId: string; + amount: number; + autoSubscribe: boolean; +} ⋮---- -getDualInvestmentAccounts(): Promise +export interface PurchaseFlexibleProductResponse { + purchaseId: number; +} ⋮---- -getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< +export interface RedeemFlexibleProductParams { + productId: string; + amount: number; + type: 'FAST' | 'NORMAL'; +} ⋮---- -/** - * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. - * Calls to this method will fail. Configure auto-compound for Dual Investment positions - * in the Binance web UI. This method will be removed in a future major version. - * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published - * binance-api-swagger spec still lists the endpoint, so this method stays deprecated. - */ -updateAutoCompoundStatus( - params: ChangeAutoCompoundStatusParams, -): Promise +export interface LeftDailyPurchaseQuotaFlexibleProductResponse { + asset: string; + leftQuota: string; +} ⋮---- -/** - * - * GIFT CARD Endpoints - Market Data - * - **/ +export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; +export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +export type ProjectSortBy = + | 'START_TIME' + | 'LOT_SIZE' + | 'INTEREST_RATE' + | 'DURATION'; ⋮---- -createGiftCard(params: CreateGiftCardParams): Promise +export interface FixedAndActivityProjectParams { + asset?: string; + type: ProjectType; + status?: ProjectStatus; + isSortAsc?: boolean; + sortBy?: ProjectSortBy; + current?: number; + size?: number; +} +export interface FixedAndActivityProjectPositionParams { + asset?: string; + projectId?: string; + status?: StakingStatus; +} ⋮---- -createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise +export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; ⋮---- -redeemGiftCard(params: RedeemGiftCardParams): Promise +export interface PurchaseRecordParams { + lendingType: LendingType; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -verifyGiftCard(params: +export interface NewFutureAccountTransferParams { + asset: string; + amount: number; + type: 1 | 2 | 3 | 4; +} ⋮---- -getTokenLimit(params: +export interface GetFutureAccountTransferHistoryParams { + asset: string; + startTime: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getRsaPublicKey(): Promise +export interface FutureAccountTransfer { + asset: string; + tranId: number; + amount: string; + type: string; + timestamp: number; + status: 'PENDING' | 'CONFIRMED' | 'FAILED'; +} +⋮---- +export interface GetLoanCoinPaginatedHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- /** - * - * NFT Endpoints - REST api - * - **/ + * + * STAKING + * + */ ⋮---- -getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< +export interface StakingHistory { + positionId: numberInString; + time: number; + asset: string; + project?: string; + amount: numberInString; + lockPeriod?: numberInString; + deliverDate?: numberInString; + type?: string; + status: string; +} ⋮---- -getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< +export interface StakingPersonalLeftQuota { + leftPersonalQuota: numberInString; +} ⋮---- -getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< +export interface StakingHistoryParams extends StakingBasicParams { + txnType: StakingTxnType; + asset?: string; + startTime?: number; + endTime?: number; +} +export interface BSwapOperationsParams { + operationId?: number; + poolId?: number; + operation: BSwapOperationType; + startTime?: number; + endTime?: number; + limit: number; +} ⋮---- -getNftAsset(params: GetNftAssetParams): Promise< +export interface BSwapOperations { + operationId: number; + poolId: number; + poolName: string; + operation: BSwapOperationType; + status: number; + updateTime: number; + shareAmount: numberInString; +} +export interface RemoveBSwapLiquidityParams { + poolId: number; + type: BSwapType; + asset?: string; + shareAmount: number; +} ⋮---- -/** - * - * C2C Endpoints - * - **/ +export interface AddBSwapLiquidityParams { + poolId: number; + type?: BSwapType; + asset: string; + quantity: number; +} ⋮---- -getC2CTradeHistory( - params: GetC2CTradeHistoryParams, -): Promise +export interface BSwapShare { + shareAmount: number; + sharePercentage: number; + asset: { [k: string]: number }; +} ⋮---- -/** - * - * FIAT Endpoints - REST api - * - **/ +export interface BSwapLiquidity { + poolId: number; + poolNmae: string; + updateTime: number; + liquidity: { [k: string]: number }; + share: BSwapShare; +} ⋮---- -getFiatOrderHistory( - params: GetFiatOrderHistoryParams, -): Promise +export interface FundingAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + btcValuation: string; +} ⋮---- -getFiatPaymentsHistory( - params: GetFiatOrderHistoryParams, -): Promise +export interface GetAssetParams { + asset?: string; + needBtcValuation?: boolean; +} ⋮---- -fiatWithdraw(params: WithdrawFiatParams): Promise< +export interface UserAsset { + asset: string; + free: string; + locked: string; + freeze: string; + withdrawing: string; + ipoable: string; + btcValuation: string; +} ⋮---- -fiatDeposit(params: FiatDepositParams): Promise +export interface SpotAssetTagsParams { + tag?: string; +} ⋮---- -getFiatOrderDetail( - params: GetFiatOrderDetailParams, -): Promise +export interface SpotAssetTag { + assetCode: string; + assetName: string; + trading: boolean; + tags: string[]; +} ⋮---- -/** - * - * Rebate Endpoints - * - **/ +export interface ConvertTransfer { + clientTranId: string; + asset: string; + amount: number; + targetAsset: string; + accountType?: string; +} ⋮---- -getSpotRebateHistoryRecords( - params: GetSpotRebateHistoryRecordsParams, -): Promise +export interface ConvertTransferResponse { + tranId: number; + status: string; +} ⋮---- -/** - * - * DERIVATIVES - Portfolio Margin Pro - Market Data - * This is in mainclient because it shares the same base url - * - **/ +export interface GetConvertBUSDHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + accountType?: string; + current?: number; + size?: number; +} ⋮---- -getPortfolioMarginIndexPrice(params?: { - asset?: string; -}): Promise +export interface BUSDConversionRecord { + tranId: number; + type: number; + time: number; + deductedAsset: string; + deductedAmount: string; + targetAsset: string; + targetAmount: string; + status: string; + accountType: string; +} ⋮---- -getPortfolioMarginAssetLeverage(): Promise< - GetPortfolioMarginAssetLeverageResponse[] - > { - return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); +export interface CloudMiningHistoryParams { + tranId?: number; + clientTranId?: string; + asset?: string; + startTime: number; + endTime: number; + current?: number; + size?: number; +} +⋮---- +export interface CloudMining { + createTime: number; + tranId: number; + type: number; + asset: string; + amount: string; + status: string; +} ⋮---- -getPortfolioMarginProCollateralRate(): Promise< - GetPortfolioMarginProCollateralRateResponse[] - > { - return this.get('sapi/v1/portfolio/collateralRate'); +export interface ConvertibleCoinsResponse { + convertEnabled: boolean; + coins: string[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exchangeRates: any; +} ⋮---- -getPortfolioMarginProTieredCollateralRate(): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -/** - * - * DERIVATIVES - Portfolio Margin Pro - Account - * This is in mainclient because it shares the same base url - * - **/ +export interface ConvertibleCoinsParams { + coin: string; + enable: boolean; +} ⋮---- -getPortfolioMarginProAccountInfo(): Promise +export interface SubmitDepositCreditParams { + depositId?: number; + txId?: string; + subAccountId?: number; + subUserId?: number; +} ⋮---- -getPortfolioDeltaMode(): Promise +export interface SubmitDepositCreditResponse { + code: string; + message: string; + data: boolean; + success: boolean; +} ⋮---- -switchPortfolioDeltaMode( - params: SwitchPortfolioDeltaModeParams, -): Promise< +export interface DepositAddressListParams { + coin: string; + network?: string; +} ⋮---- -setPortfolioMarginMarginCallLevel( - params: SetPortfolioMarginMarginCallLevelParams, -): Promise +export interface DepositAddress { + coin: string; + address: string; + tag: string; + isDefault: number; +} ⋮---- -getPortfolioMarginMarginCallLevel(): Promise +export interface WalletBalance { + activate: boolean; + balance: string; + walletName: string; +} ⋮---- -deletePortfolioMarginMarginCallLevel(): Promise +export interface DelegationHistoryParams { + email: string; + startTime: number; + endTime: number; + type?: 'Delegate' | 'Undelegate'; + asset?: string; + current?: number; + size?: number; +} ⋮---- -bnbTransfer(params: BnbTransferParams): Promise< +export interface DelegationHistory { + clientTranId: string; + transferType: 'Delegate' | 'Undelegate'; + asset: string; + amount: string; + time: number; +} ⋮---- -submitPortfolioMarginProFullTransfer(): Promise< +export interface DelistScheduleResponse { + delistTime: number; + symbols: string[]; +} ⋮---- -/** - * Fund collection by asset (`POST /sapi/v1/portfolio/asset-collection`). - * - * Optional `amount` and `futureType` must be sent together. `futureType` - * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). - * If neither is sent, collection behavior is unchanged. - */ -submitPortfolioMarginProSpecificTransfer(params: { - asset: string; - amount?: number; - futureType?: 'UM' | 'CM' | 'OPTION'; -}): Promise< +export interface WithdrawAddress { + address: string; + addressTag: string; + coin: string; + name: string; + network: string; + origin: string; + originType: string; + whiteStatus: boolean; +} ⋮---- -repayPortfolioMarginProBankruptcyLoan(params: { - from?: 'SPOT' | 'MARGIN'; -}): Promise< +export interface AccountInfo { + vipLevel: number; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isOptionsEnabled: boolean; + isPortfolioMarginRetailEnabled: boolean; +} ⋮---- -getPortfolioMarginProBankruptcyLoanAmount(): Promise +export interface ManagedSubAccountSnapshotParams { + email: string; + type: 'SPOT' | 'MARGIN' | 'FUTURES'; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -repayFuturesNegativeBalance(): Promise< +export interface SubaccountBalances { + asset: string; + free: string; + locked: string; +} ⋮---- -updateAutoRepayFuturesStatus(params: +export interface SubaccountUserAssets { + asset: string; + borrowed: string; + free: string; + interest: string; + locked: string; + netAsset: string; +} ⋮---- -getAutoRepayFuturesStatus(): Promise< +export interface SubaccountAssets { + asset: string; + marginBalance: string; + walletBalance: string; +} ⋮---- -getPortfolioMarginProInterestHistory( - params: GetPortfolioMarginProInterestHistoryParams, -): Promise +export interface SubaccountPosition { + entryPrice: string; + markPrice: string; + positionAmt: string; + symbol: string; + unRealizedProfit: string; +} ⋮---- -getPortfolioMarginProSpanAccountInfo(): Promise +export interface ManagedSubAccountSnapshot { + code: number; + msg: string; + snapshotVos: { + data: { + balances?: SubaccountBalances[]; + totalAssetOfBtc?: string; + marginLevel?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + userAssets?: SubaccountUserAssets[]; + assets?: SubaccountAssets[]; + position?: SubaccountPosition[]; + }; + type: string; + updateTime: number; + }[]; +} ⋮---- -getPortfolioMarginProAccountBalance(params?: { - asset?: string; -}): Promise +export interface ManagedSubAccountTransferLogParams { + email: string; + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: 'from' | 'to'; + transferFunctionAccountType?: + | 'SPOT' + | 'MARGIN' + | 'ISOLATED_MARGIN' + | 'USDT_FUTURE' + | 'COIN_FUTURE'; +} ⋮---- -/** - * @deprecated - * Check Simple Earn endpoints for new way of doing it - */ -mintPortfolioMarginBFUSD( - params: PMProMintBFUSDParams, -): Promise +export interface ManagerSubTransferHistoryVos { + fromEmail: string; + fromAccountType: string; + toEmail: string; + toAccountType: string; + asset: string; + amount: string; + scheduledData: number; + createTime: number; + status: string; + tranId: number; +} ⋮---- -/** - * @deprecated - * Check Simple Earn endpointsfor new way of doing it - */ -redeemPortfolioMarginBFUSD(params: { - fromAsset: string; // BFUSD only - targetAsset: string; // USDT only - amount: number; -}): Promise +export interface ManagedSubAccountFuturesAssetsResponse { + code: string; + message: string; + snapshotVos: { + type: string; + updateTime: number; + data: { + assets: SubaccountAssets[]; + position: SubaccountPosition[]; + }; + }[]; +} ⋮---- -fromAsset: string; // BFUSD only -targetAsset: string; // USDT only +export interface ManagedSubAccountMarginAssetsResponse { + marginLevel: string; + totalAssetOfBtc: string; + totalLiabilityOfBtc: string; + totalNetAssetOfBtc: string; + userAssets: SubaccountUserAssets[]; +} ⋮---- -getPortfolioMarginBankruptcyLoanRepayHistory(params?: { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -}): Promise< +export interface ManagedSubAccountListParams { + email?: string; + page?: number; + limit?: number; +} +⋮---- +export interface ManagerSubUserInfoVo { + rootUserId: number; + managersubUserId: number; + bindParentUserId: number; + email: string; + insertTimeStamp: number; + bindParentEmail: string; + isSubUserEnabled: boolean; + isUserActive: boolean; + isMarginEnabled: boolean; + isFutureEnabled: boolean; + isSignedLVTRiskAgreement: boolean; +} ⋮---- -/** - * Transfer LDUSDT as collateral for all types of Portfolio Margin account - */ -transferLDUSDTPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; - amount: number; -}): Promise< +export interface SubaccountTradeInfoVos { + userId: number; + btc: number; + btcFutures: number; + btcMargin: number; + busd: number; + busdFutures: number; + busdMargin: number; + date: number; +} +export interface SubAccountTransactionStatistics { + recent30BtcTotal: string; + recent30BtcFuturesTotal: string; + recent30BtcMarginTotal: string; + recent30BusdTotal: string; + recent30BusdFuturesTotal: string; + recent30BusdMarginTotal: string; + tradeInfoVos: SubaccountTradeInfoVos[]; +} ⋮---- -/** - * Get transferable earn asset balance for all types of Portfolio Margin account - */ -getTransferableEarnAssetBalanceForPortfolioMargin(params: { - asset: string; - transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; -}): Promise< +export interface ManagedSubAccountDepositAddressParams { + email: string; + coin: string; + network?: string; +} ⋮---- -/** - * - * DERIVATIVES - Futures Data - Market - * This is in mainclient because it shares the same base url - * - **/ +export interface ManagedSubAccountDepositAddress { + coin: string; + address: string; + tag: string; + url: string; +} ⋮---- -getFuturesTickLevelOrderbookDataLink( - params: GetFutureTickLevelOrderbookDataLinkParams, -): Promise< +export interface EnableOptionsForSubAccountResponse { + email: string; + isEOptionsEnabled: boolean; +} ⋮---- -/** - * - * BLVT Endpoints - * BLVT category is possibly @deprecated, found only in old docs - **/ +export interface ManagedSubAccountTransferTTLogParams { + startTime: number; + endTime: number; + page: number; + limit: number; + transfers?: string; + transferFunctionAccountType?: string; +} ⋮---- -getBlvtInfo(params?: +export interface UIKlinesParams { + symbol: string; + interval: string; + startTime?: number; + endTime?: number; + timeZone?: string; + limit?: number; +} ⋮---- -subscribeBlvt(params: SubscribeBlvtParams): Promise +export interface Ticker24hrFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + prevClosePrice: string; + lastPrice: string; + lastQty: string; + bidPrice: string; + bidQty: string; + askPrice: string; + askQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- -getBlvtSubscriptionRecord( - params: GetBlvtSubscriptionRecordParams, -): Promise +export interface Ticker24hrMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- -redeemBlvt(params: RedeemBlvtParams): Promise +export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; ⋮---- -getBlvtRedemptionRecord( - params: GetBlvtRedemptionRecordParams, -): Promise +export interface TradingDayTickerParams { + symbol?: string; + symbols?: string[]; + timeZone?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- -getBlvtUserLimitInfo(params: { - tokenName?: string; -}): Promise +export interface TradingDayTickerFull { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- -/** - * - * Pay endpoints - * Found only in old docs, possibly @deprecated - **/ -getPayTransactions(params: GetPayTradeHistoryParams): Promise +export interface TradingDayTickerMini { + symbol: string; + openPrice: string; + highPrice: string; + lowPrice: string; + lastPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; +} ⋮---- -/** - * - * INSTITUTIONAL LOAN - Account Endpoints - * - **/ +export type TradingDayTickerSingle = + | TradingDayTickerFull + | TradingDayTickerMini; ⋮---- -getInstLoanRiskUnit( - params?: GetInstitutionalLoanRiskUnitDetailsParams, -): Promise +export type TradingDayTickerArray = + | TradingDayTickerFull[] + | TradingDayTickerMini[]; ⋮---- -closeInstLoanRiskUnit(): Promise +export interface RollingWindowTickerParams { + symbol?: string; + symbols?: string[]; + windowSize?: string; + type?: 'FULL' | 'MINI'; + symbolStatus?: string; +} ⋮---- -addInstLoanCollateralAccount( - params: AddInstitutionalLoanCollateralAccountParams, -): Promise +export interface NewOrderListOTOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingQuantity: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; +} ⋮---- -getActiveInstLoanRiskUnits(): Promise +export interface NewOrderListOTOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} ⋮---- -getClosedInstLoanRiskUnits( - params?: GetClosedInstitutionalLoanRiskUnitsParams, -): Promise +export interface NewOrderListOTOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; +} ⋮---- -/** - * - * INSTITUTIONAL LOAN - Trade Endpoints - * - **/ +export interface NewOrderListOTOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} ⋮---- -getInstLoanForceLiquidationRecord( - params: GetInstitutionalLoanForceLiquidationParams, -): Promise -/** - * - * INSTITUTIONAL LOAN - TransferEndpoints - * - **/ +export interface NewOrderListOPOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingType: string; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: string; + pendingStopPrice?: string; + pendingTrailingDelta?: string; + pendingIcebergQty?: string; + pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingStrategyId?: number; + pendingStrategyType?: number; + pendingPegPriceType?: string; + pendingPegOffsetType?: string; + pendingPegOffsetValue?: number; +} ⋮---- -transferInstLoanRiskUnit( - params: InstitutionalLoanRiskUnitTransferParams, -): Promise +export interface NewOrderListOPOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} ⋮---- -/** - * - * INSTITUTIONAL LOAN - Borrow/Repay Endpoints - * - **/ +export interface NewOrderListOPOCOParams { + symbol: string; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; + selfTradePreventionMode?: string; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + workingStrategyId?: number; + workingStrategyType?: number; + workingPegPriceType?: string; + workingPegOffsetType?: string; + workingPegOffsetValue?: number; + pendingSide: 'BUY' | 'SELL'; + pendingAboveType: + | 'STOP_LOSS_LIMIT' + | 'STOP_LOSS' + | 'LIMIT_MAKER' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingAboveStrategyId?: number; + pendingAboveStrategyType?: number; + pendingAbovePegPriceType?: string; + pendingAbovePegOffsetType?: string; + pendingAbovePegOffsetValue?: number; + pendingBelowType?: + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; + pendingBelowStrategyId?: number; + pendingBelowStrategyType?: number; + pendingBelowPegPriceType?: string; + pendingBelowPegOffsetType?: string; + pendingBelowPegOffsetValue?: number; +} ⋮---- -getInstitutionalLoanMaxBorrowable( - params: GetInstitutionalLoanMaxBorrowableParams, -): Promise +export interface NewOrderListOPOCOResponse { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; + symbol: string; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty?: string; + executedQty: string; + origQuoteOrderQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + stopPrice?: string; + workingTime: number; + selfTradePreventionMode: string; + }[]; +} ⋮---- -borrowInstitutionalLoan( - params: InstitutionalLoanBorrowParams, -): Promise +export interface OrderRateLimitUsage { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} ⋮---- -getInstLoanInterestHistory( - params?: GetInstitutionalLoanInterestHistoryParams, -): Promise +export interface PreventedMatchesParams { + symbol: string; + preventedMatchId?: number; + orderId?: number; + fromPreventedMatchId?: number; + limit?: number; +} ⋮---- -repayInstitutionalLoan( - params: InstitutionalLoanRepayParams, -): Promise +export interface PreventedMatch { + symbol: string; + preventedMatchId: number; + takerOrderId: number; + makerSymbol: string; + makerOrderId: number; + tradeGroupId: number; + selfTradePreventionMode: SelfTradePreventionMode; + price: string; + makerPreventedQuantity: string; + transactTime: number; +} ⋮---- -getInstLoanBorrowRepayRecords( - params: GetInstitutionalLoanBorrowRepayRecordsParams, -): Promise +export interface AllocationsParams { + symbol: string; + startTime?: number; + endTime?: number; + fromAllocationId?: number; + limit?: number; + orderId?: number; +} ⋮---- -getMarginInterestRebateBalance(): Promise +export interface Allocation { + symbol: string; + allocationId: number; + allocationType: string; + orderId: number; + orderListId: number; + price: string; + qty: string; + quoteQty: string; + commission: string; + commissionAsset: string; + time: number; + isBuyer: boolean; + isMaker: boolean; + isAllocator: boolean; +} ⋮---- -getMarginInterestRebateBalanceRecords( - params?: GetMarginInterestRebateBalanceRecordsParams, -): Promise +export interface CommissionRates { + symbol: string; + standardCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + taxCommission: { + maker: string; + taker: string; + buyer: string; + seller: string; + }; + discount: { + enabledForAccount: boolean; + enabledForSymbol: boolean; + discountAsset: string; + /** + * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). + * `0.75` means pay 75% of the standard commission. It is not a reduction rate. + * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. + * Does not apply to tax or special commission. + */ + discount: string; + }; +} ⋮---- /** - * - * ALPHA TRADING - Market Data - * https://developers.binance.com/docs/alpha - */ -⋮---- -getAlphaTokenList(): Promise + * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). + * `0.75` means pay 75% of the standard commission. It is not a reduction rate. + * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. + * Does not apply to tax or special commission. + */ ⋮---- -getAlphaExchangeInfo(): Promise +export interface GetCrossMarginTransferHistoryParams { + asset?: string; + type?: 'ROLL_IN' | 'ROLL_OUT'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + isolatedSymbol?: string; +} ⋮---- -getAlphaAggTrades(params: AlphaAggTradesParams): Promise +export interface CrossMarginTransferHistory { + amount: string; + asset: string; + status: string; + timestamp: number; + txId: number; + type: 'ROLL_IN' | 'ROLL_OUT'; + transFrom?: string; + transTo?: string; + fromSymbol?: string; + toSymbol?: string; +} ⋮---- -getAlphaKlines(params: AlphaKlinesParams): Promise +export interface GetMarginInterestHistoryParams { + asset?: string; + isolatedSymbol?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getAlphaTicker(params: +export interface MarginInterestHistory { + txId: number; + interestAccuredTime: number; + asset: string; + rawAsset?: string; + principal: string; + interest: string; + interestRate: string; + type: + | 'PERIODIC' + | 'ON_BORROW' + | 'PERIODIC_CONVERTED' + | 'ON_BORROW_CONVERTED' + | 'PORTFOLIO'; + isolatedSymbol?: string; +} ⋮---- -getAlphaFullDepth( - params: AlphaFullDepthParams, -): Promise +export interface GetForceLiquidationRecordParams { + startTime?: number; + endTime?: number; + isolatedSymbol?: string; + current?: number; + size?: number; +} ⋮---- -/** - * - * EXCHANGE LINK - Account Endpoints - * https://developers.binance.com/docs/binance_link - */ +export interface ForceLiquidationRecord { + avgPrice: string; + executedQty: string; + orderId: number; + price: string; + qty: string; + side: 'BUY' | 'SELL'; + symbol: string; + timeInForce: string; + isIsolated: boolean; + updatedTime: number; +} ⋮---- -createBrokerSubAccount( - params: CreateBrokerSubAccountParams, -): Promise +export interface QueryMarginAccountAllOCOParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; + fromId?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -getBrokerSubAccount( - params: GetBrokerSubAccountParams, -): Promise +export interface QueryMarginAccountTradeListParams { + symbol: string; + isIsolated?: 'TRUE' | 'FALSE'; + orderId?: number; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} ⋮---- -enableMarginBrokerSubAccount( - params: EnableMarginBrokerSubAccountParams, -): Promise +export interface IsolatedMarginSymbol { + base: string; + isBuyAllowed: boolean; + isMarginTrade: boolean; + isSellAllowed: boolean; + quote: string; + symbol: string; + delistTime?: number; +} ⋮---- -createApiKeyBrokerSubAccount( - params: CreateApiKeyBrokerSubAccountParams, -): Promise +export interface ToggleBNBBurnParams { + spotBNBBurn?: 'true' | 'false'; + interestBNBBurn?: 'true' | 'false'; +} ⋮---- -changePermissionApiKeyBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise +export interface BNBBurnResponse { + spotBNBBurn: boolean; + interestBNBBurn: boolean; +} ⋮---- -changeComissionBrokerSubAccount( - params: ChangePermissionApiKeyBrokerSubAccountParams, -): Promise +export interface QueryMarginInterestRateHistoryParams { + asset: string; + vipLevel?: number; + startTime?: number; + endTime?: number; +} ⋮---- -enableUniversalTransferApiKeyBrokerSubAccount( - params: EnableUniversalTransferApiKeyBrokerSubAccountParams, -): Promise +export interface MarginInterestRateHistory { + asset: string; + dailyInterestRate: string; + timestamp: number; + vipLevel: number; +} ⋮---- -updateIpRestrictionForSubAccountApiKey( - params: UpdateIpRestrictionForSubApiKey, -): Promise< +export interface QueryCrossMarginFeeDataParams { + vipLevel?: number; + coin?: string; +} ⋮---- -deleteIPRestrictionForSubAccountApiKey(params: { - subAccountId: string; - subAccountApiKey: string; - ipAddress?: string; -}): Promise< +export interface CrossMarginFeeData { + vipLevel: number; + coin: string; + transferIn: boolean; + borrowable: boolean; + dailyInterest: string; + yearlyInterest: string; + borrowLimit: string; + marginablePairs: string[]; +} ⋮---- -deleteApiKeyBrokerSubAccount( - params: DeleteApiKeyBrokerSubAccountParams, -): Promise +export interface IsolatedMarginFeeData { + vipLevel: number; + symbol: string; + leverage: string; + data: { + coin: string; + dailyInterest: string; + borrowLimit: string; + }[]; +} ⋮---- -getSubAccountBrokerIpRestriction(params: { - subAccountId: string; - subAccountApiKey: string; -}): Promise< +export interface QueryIsolatedMarginTierDataParams { + symbol: string; + tier?: number; +} ⋮---- -getApiKeyBrokerSubAccount( - params: GetApiKeyBrokerSubAccountParams, -): Promise +export interface IsolatedMarginTierData { + symbol: string; + tier: number; + effectiveMultiple: string; + initialRiskRatio: string; + liquidationRiskRatio: string; + baseAssetMaxBorrowable: string; + quoteAssetMaxBorrowable: string; +} ⋮---- -getBrokerInfo(): Promise +export interface GetMarginOrderCountUsageParams { + isIsolated?: string; + symbol?: string; +} ⋮---- -updateSubAccountBNBBurn(params: { - subAccountId: string; - spotBNBBurn: 'true' | 'false'; -}): Promise< +export interface MarginOrderCountUsageResponse { + rateLimitType: string; + interval: string; + intervalNum: number; + limit: number; + count: number; +} ⋮---- -updateSubAccountMarginInterestBNBBurn(params: { - subAccountId: string; - interestBNBBurn: 'true' | 'false'; -}): Promise< +export interface Collateral { + minUsdValue: string; + maxUsdValue?: string; + discountRate: string; +} ⋮---- -getSubAccountBNBBurnStatus(params: +export interface SmallLiabilityExchangeCoin { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} +export interface GetSmallLiabilityExchangeHistoryParams { + current: number; + size: number; + startTime?: number; + endTime?: number; +} ⋮---- -/** - * Caution: - * The operation will delete a sub account under your brokerage master account. - * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. - * The deleted sub account CANNOT be reverted. - * The daily deletion limit for a broker Master is 20 sub accounts. - * You need to enable "trade" option for the api key which requests this endpoint. - */ -deleteBrokerSubAccount(params: +export interface SmallLiabilityExchangeHistory { + asset: string; + amount: string; + targetAsset: string; + targetAmount: string; + bizType: string; + timestamp: number; +} ⋮---- -/** - * - * EXCHANGE LINK - Asset Endpoints - * https://developers.binance.com/docs/binance_link - */ +export interface GetNextHourlyInterestRateParams { + assets: string; + isIsolated: boolean; +} ⋮---- -transferBrokerSubAccount( - params: TransferBrokerSubAccountParams, -): Promise +export interface NextHourlyInterestRate { + asset: string; + nextHourlyInterestRate: string; +} ⋮---- -getBrokerSubAccountHistory( - params: GetBrokerSubAccountHistoryParams, -): Promise +export interface GetMarginCapitalFlowParams { + asset?: string; + symbol?: string; + type?: string; + startTime?: number; + endTime?: number; + fromId?: number; + limit?: number; +} ⋮---- -submitBrokerSubFuturesTransfer(params: { - fromId?: string; - toId?: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - asset: string; - amount: number; - clientTranId?: string; // The max length is 32 characters -}): Promise< +export interface MarginCapitalFlow { + id: number; + tranId: number; + timestamp: number; + asset: string; + symbol: string; + type: string; + amount: string; +} ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +export interface MarginDelistSchedule { + delistTime: number; + crossMarginAssets: string[]; + isolatedMarginSymbols: string[]; + updateTime: number; +} ⋮---- -clientTranId?: string; // The max length is 32 characters +export interface MarginAvailableInventoryResponse { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assets: any; + updateTime: number; +} ⋮---- -getSubAccountFuturesTransferHistory(params: { - subAccountId: string; - futuresType: number; // 1: USDT Futures, 2: COIN Futures - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; -}): Promise +// eslint-disable-next-line @typescript-eslint/no-explicit-any ⋮---- -futuresType: number; // 1: USDT Futures, 2: COIN Futures +export interface ManualLiquidationParams { + type: string; + symbol?: string; +} ⋮---- -getBrokerSubDepositHistory( - params: GetSubAccountDepositHistoryParams, -): Promise +export interface ManualLiquidationResponse { + asset: string; + interest: string; + principal: string; + liabilityAsset: string; + liabilityQty: number; +} ⋮---- -getBrokerSubAccountSpotAssets( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +export interface LeverageBracket { + leverage: number; + maxDebt: number; + maintenanceMarginRate: number; + initialMarginRate: number; + fastNum: number; +} ⋮---- -getSubAccountMarginAssetInfo( - params: QuerySubAccountSpotMarginAssetInfoParams, -): Promise< +export interface LiabilityCoinLeverageBracket { + assetNames: string[]; + rank: number; + brackets: LeverageBracket[]; +} +export interface GetFlexibleSubscriptionRecordParams { + productId?: string; + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -querySubAccountFuturesAssetInfo( - params: QuerySubAccountFuturesAssetInfoParams, -): Promise< +export interface GetFlexibleSubscriptionRecordResponse { + amount: string; + asset: string; + time: number; + purchaseId: number; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; +} ⋮---- -universalTransferBroker(params: UniversalTransferBrokerParams): Promise< +export interface GetLockedSubscriptionRecordParams { + purchaseId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getUniversalTransferBroker( - params: GetUniversalTransferBrokerParams, -): Promise +export interface LockedSubscriptionRecord { + positionId: string; + purchaseId: number; + time: number; + asset: string; + amount: string; + lockPeriod: string; + type: string; + sourceAccount: string; + amtFromSpot?: string; + amtFromFunding?: string; + status: string; +} ⋮---- -/** - * - * EXCHANGE LINK - Fee Endpoints - * https://developers.binance.com/docs/binance_link - */ +export interface GetFlexibleRedemptionRecordParams { + productId?: string; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -updateBrokerSubAccountCommission( - params: ChangeSubAccountCommissionParams, -): Promise +export interface FlexibleRedemptionRecord { + amount: string; + asset: string; + time: number; + productId: string; + redeemId: number; + destAccount: string; + status: string; +} ⋮---- -updateBrokerSubAccountFuturesCommission( - params: ChangeSubAccountFuturesCommissionParams, -): Promise +export interface GetLockedRedemptionRecordParams { + positionId?: string; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getBrokerSubAccountFuturesCommission( - params: QuerySubAccountFuturesCommissionParams, -): Promise +export interface LockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; + deliverDate: string; + status: string; +} ⋮---- -updateBrokerSubAccountCoinFuturesCommission( - params: ChangeSubAccountCoinFuturesCommissionParams, -): Promise +export interface GetFlexibleRewardsHistoryParams { + productId?: string; + asset?: string; + startTime?: number; + endTime?: number; + type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; + current?: number; + size?: number; +} ⋮---- -getBrokerSubAccountCoinFuturesCommission( - params: QuerySubAccountCoinFuturesCommissionParams, -): Promise +export interface FlexibleRewardsHistory { + asset: string; + rewards: string; + projectId: string; + type: string; + time: number; +} ⋮---- -getBrokerSpotCommissionRebate( - params: QueryBrokerSpotCommissionRebateParams, -): Promise +export interface GetLockedRewardsHistoryParams { + positionId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -getBrokerFuturesCommissionRebate( - params: QueryBrokerFuturesCommissionRebateParams, -): Promise +export interface GetLockedRewardsHistory { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; + type: string; +} ⋮---- -/** - * - * @deprecated - */ -// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) -getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) +export interface SetAutoSubscribeParams { + productId: string; + autoSubscribe: boolean; +} ⋮---- -/** - * Broker Endpoints - only on old docs - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link - */ +export interface GetFlexibleSubscriptionPreviewParams { + productId: string; + amount: number; +} ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerIfNewSpotUser(): Promise< +export interface FlexibleSubscriptionPreview { + totalAmount: string; + rewardAsset: string; + airDropAsset: string; + estDailyBonusRewards: string; + estDailyRealTimeRewards: string; + estDailyAirdropRewards: string; +} ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerSubAccountDepositHistory( - params?: GetBrokerSubAccountDepositHistoryParams, -): Promise +export interface GetLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; +} ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -getBrokerUserCustomisedId(market: 'spot' | 'futures') +export interface LockedSubscriptionPreview { + rewardAsset: string; + totalRewardAmt: string; + extraRewardAsset: string; + estTotalExtraRewardAmt: string; + nextPay: string; + nextPayDate: string; + valueDate: string; + rewardsEndDate: string; + deliverDate: string; + nextSubscriptionDate: string; + boostRewardAsset: string; + estDailyRewardAmt: string; +} ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableFuturesBrokerSubAccount( - params: EnableFuturesBrokerSubAccountParams, -): Promise +export interface GetRateHistoryParams { + productId: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * @deprecated, found only in old docs - * Use EXCHANGE LINK endpoints instead - **/ -enableMarginApiKeyBrokerSubAccount( - params: EnableMarginApiKeyBrokerSubAccountParams, -): Promise +export interface GetRateHistory { + productId: string; + asset: string; + annualPercentageRate: string; + time: number; +} ⋮---- -/** - * Validate syntax meets requirements set by binance. Log warning if not. - */ -private validateOrderId( - params: - | NewSpotOrderParams - | CancelOrderParams - | NewOCOParams - | CancelOCOParams - | NewOrderListParams, - orderIdProperty: OrderIdProperty, -): void +export interface GetCollateralRecordParams { + productId?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * - * User Data Stream Endpoints - * - **/ +export interface CollateralRecord { + amount: string; + productId: string; + asset: string; + createTime: number; + type: string; + productName: string; + orderId: number; +} ⋮---- -// spot -getSpotUserDataListenKey(): Promise< +export interface GetDualInvestmentProductListParams { + optionType: string; + exercisedCoin: string; + investCoin: string; + pageSize?: number; + pageIndex?: number; +} ⋮---- -keepAliveSpotUserDataListenKey(listenKey: string): Promise +export interface DualInvestmentProduct { + id: string; + investCoin: string; + exercisedCoin: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseDecimal: number; + purchaseEndTime: number; + canPurchase: boolean; + apr: string; + orderId: number; + minAmount: string; + maxAmount: string; + createTimestamp: number; + optionType: string; + isAutoCompoundEnable: boolean; + autoCompoundPlanList: string[]; +} ⋮---- -closeSpotUserDataListenKey(listenKey: string): Promise +export interface SubscribeDualInvestmentProductParams { + id: string; + orderId: string; + depositAmount: number; + /** + * @deprecated Binance removed the `autoCompoundPlan` request parameter from + * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. + * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says + * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec + * still lists the parameter, so this field stays deprecated. + */ + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} ⋮---- /** - * Get a cross margin user data listen key + * @deprecated Binance removed the `autoCompoundPlan` request parameter from + * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. + * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says + * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec + * still lists the parameter, so this field stays deprecated. */ -getMarginUserDataListenKey(): Promise< -⋮---- -keepAliveMarginUserDataListenKey(listenKey: string): Promise ⋮---- -closeMarginUserDataListenKey(listenKey: string): Promise +export interface SubscribeDualInvestmentProductResponse { + positionId: number; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + duration: number; + autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; + strikePrice: string; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseTime: number; + optionType: string; +} ⋮---- -// isolated margin -getIsolatedMarginUserDataListenKey(params: { - symbol: string; -}): Promise< +export interface GetDualInvestmentPositionsParams { + status?: + | 'PENDING' + | 'PURCHASE_SUCCESS' + | 'SETTLED' + | 'PURCHASE_FAIL' + | 'REFUNDING' + | 'REFUND_SUCCESS' + | 'SETTLING'; + pageSize?: number; + pageIndex?: number; +} ⋮---- -keepAliveIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +export interface DualInvestmentPosition { + id: string; + investCoin: string; + exercisedCoin: string; + subscriptionAmount: string; + strikePrice: string; + duration: number; + settleDate: number; + purchaseStatus: string; + apr: string; + orderId: number; + purchaseEndTime: number; + optionType: string; + autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; + settlePrice?: string; + isExercised?: boolean; + settleAsset?: string; + settleAmount?: string; + subscriptionTime?: number; +} ⋮---- -closeIsolatedMarginUserDataListenKey(params: { - symbol: string; - listenKey: string; -}): Promise +export interface CheckDualInvestmentAccountsResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; +} ⋮---- /** - * Get a cross margin risk data listen key - */ -getMarginRiskUserDataListenKey(): Promise< + * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. + * Configure auto-compound for Dual Investment positions in the Binance web UI. + * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published + * binance-api-swagger spec still lists the endpoint, so this type stays deprecated. + */ +export interface ChangeAutoCompoundStatusParams { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} ⋮---- -keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise +export interface ChangeAutoCompoundStatusResponse { + positionId: string; + autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; +} ⋮---- -closeMarginRiskUserDataListenKey(): Promise +export interface GetTargetAssetListParams { + targetAsset?: string; + size?: number; + current?: number; +} ⋮---- -getMarginUtaUserDataListenKey(): Promise< +export interface RoiAndDimensionType { + simulateRoi: string; + dimensionValue: string; + dimensionUnit: string; +} ⋮---- -keepAliveMarginUtaUserDataListenKey(listenKey: string): Promise +export interface AutoInvestAsset { + targetAsset: string; + roiAndDimensionTypeList: RoiAndDimensionType[]; +} ⋮---- -closeMarginUtaUserDataListenKey(): Promise +export interface GetTargetAssetListResponse { + targetAssets: string[]; + autoInvestAssetList: AutoInvestAsset[]; +} ⋮---- -/** - * Get/create margin account listenToken for the user data stream - * https://developers.binance.com/docs/margin_trading/trade-data-stream - */ -getMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; -}): Promise< +export interface GetTargetAssetROIParams { + targetAsset: string; + hisRoiType: + | 'FIVE_YEAR' + | 'THREE_YEAR' + | 'ONE_YEAR' + | 'SIX_MONTH' + | 'THREE_MONTH' + | 'SEVEN_DAY'; +} ⋮---- -/** - * - * DEPRECATED ENDPOINTS - * - **/ -/** - * - * BSwap Endpoints - * @deprecated as of 2024-01-19 - **/ +export interface TargetAssetROI { + date: string; + simulateRoi: string; +} ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapLiquidity(params?: +export interface GetSourceAssetListParams { + targetAsset?: string[]; + indexId?: number; + usageType: 'RECURRING' | 'ONE_TIME'; + flexibleAllowedToUse?: boolean; + sourceType?: 'MAIN_SITE' | 'TR'; +} ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise< +export interface SourceAsset { + sourceAsset: string; + assetMinAmount: string; + assetMaxAmount: string; + scale: string; + flexibleAmount: string; +} ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise< +export interface GetSourceAssetListResponse { + feeRate: string; + taxRate: string; + sourceAssets: SourceAsset[]; +} ⋮---- -/** - * @deprecated as of 2024-01-19 - **/ -getBSwapOperations( - params?: BSwapOperationsParams, -): Promise +export interface AutoInvestPortfolioDetail { + targetAsset: string; + percentage: number; +} ⋮---- -/** - * - * Savings Endpoints - * @deprecated as of 2023-06-22, now Simple Earn - **/ +export interface CreateInvestmentPlanParams { + UID: string; + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; + indexId?: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse: boolean; + details: AutoInvestPortfolioDetail[]; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyPurchaseQuotaFlexibleProduct(params: { - productId: string; -}): Promise +export interface CreateInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} +⋮---- +export interface EditInvestmentPlanParams { + planId: number; + subscriptionAmount: number; + subscriptionCycle: + | 'H1' + | 'H4' + | 'H8' + | 'H12' + | 'WEEKLY' + | 'DAILY' + | 'MONTHLY' + | 'BI_WEEKLY'; + subscriptionStartDay?: number; + subscriptionStartWeekday?: + | 'MON' + | 'TUE' + | 'WED' + | 'THU' + | 'FRI' + | 'SAT' + | 'SUN'; + subscriptionStartTime: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + details: AutoInvestPortfolioDetail[]; +} +⋮---- +export interface EditInvestmentPlanResponse { + planId: number; + nextExecutionDateTime: number; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLeftDailyRedemptionQuotaFlexibleProduct(params: { - productId: string; - }): Promise< - LeftDailyPurchaseQuotaFlexibleProductResponse & { - dailyQuota: string; - minRedemptionAmount: string; - } - > { - return this.getPrivate('sapi/v1/lending/daily/userRedemptionQuota', params); +export interface ChangePlanStatusParams { + planId: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -purchaseFixedAndActivityProject(params: { - projectId: string; - lot: number; -}): Promise +export interface ChangePlanStatusResponse { + planId: number; + nextExecutionDateTime: number; + status: 'ONGOING' | 'PAUSED' | 'REMOVED'; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProjects( - params: FixedAndActivityProjectParams, -): Promise +export interface GetPlanDetailsParams { + planId?: number; + requestId?: string; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getFixedAndActivityProductPosition( - params: FixedAndActivityProjectPositionParams, -): Promise +export interface GetSubscriptionTransactionHistoryParams { + planId?: number; + startTime?: number; + endTime?: number; + targetAsset?: string; + planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; + size?: number; + current?: number; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getLendingAccount(): Promise +export interface AssetAllocation { + targetAsset: string; + allocation: string; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getPurchaseRecord(params: PurchaseRecordParams): Promise +export interface GetIndexDetailsResponse { + indexId: number; + indexName: string; + status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; + assetAllocation: AssetAllocation[]; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getRedemptionRecord(params: PurchaseRecordParams): Promise +export interface IndexLinkedPlanDetail { + targetAsset: string; + averagePriceInUSD: string; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + purchasedAmount: string; + pnlInUSD: string; + roi: string; + percentage: string; + availableAmount: string; + redeemedAmount: string; + assetValueInUSD: string; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -getInterestHistory(params: PurchaseRecordParams): Promise +export interface GetIndexLinkedPlanPositionDetailsResponse { + indexId: number; + totalInvestedInUSD: string; + currentInvestedInUSD: string; + pnlInUSD: string; + roi: string; + assetAllocation: { targetAsset: string; allocation: string }[]; + details: IndexLinkedPlanDetail[]; +} ⋮---- -/** - * @deprecated as of 2023-06-22, now Simple Earn - */ -changeFixedAndActivityPositionToDailyPosition(params: { - projectId: string; - lot: number; - positionId?: number; -}): Promise +export interface SubmitOneTimeTransactionParams { + sourceType: 'MAIN_SITE' | 'TR'; + requestId?: string; + subscriptionAmount: number; + sourceAsset: string; + flexibleAllowedToUse?: boolean; + planId?: number; + indexId?: number; + details: AutoInvestPortfolioDetail[]; +} ⋮---- -/** - * - * Wallet Endpoints - * @deprecated - **/ +export interface SubmitOneTimeTransactionResponse { + transactionId: number; + waitSecond: number; +} ⋮---- -/** - * @deprecated - */ -enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise +export interface GetOneTimeTransactionStatusParams { + transactionId: number; + requestId?: string; +} ⋮---- -/** - * @deprecated - deleted as of 2024-11-21 - * - */ -convertBUSD(params: ConvertTransfer): Promise +export interface GetOneTimeTransactionStatusResponse { + transactionId: number; + status: 'SUCCESS' | 'CONVERTING'; +} ⋮---- -/** - * @deprecated - */ -getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< - -================ -File: src/websocket-client.ts -================ -import WebSocket from 'isomorphic-ws'; +export interface SubmitIndexLinkedPlanRedemptionParams { + indexId: number; + requestId?: string; + redemptionPercentage: number; +} ⋮---- -import { KlineInterval } from './types/shared'; -import { - Exact, - WsAPIOperationResponseMap, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WsOperation, - WsRequestOperationBinance, -} from './types/websockets/ws-api'; -import { - MessageEventLike, - WSClientConfigurableOptions, - WsMarket, - WsTopic, -} from './types/websockets/ws-general'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient'; -import Beautifier from './util/beautifier'; -import { DefaultLogger } from './util/logger'; -import { signMessage } from './util/node-support'; -import { - appendEventIfMissing, - requiresWSAPINewClientOID, - RestClientOptions, - serialiseParams, - validateWSAPINewClientOID, -} from './util/requestUtils'; -import { neverGuard } from './util/typeGuards'; -import { SignAlgorithm, SignEncodeMethod } from './util/webCryptoAPI'; -import { RestClientCache } from './util/websockets/rest-client-cache'; -import { UserDataStreamManager } from './util/websockets/user-data-stream-manager'; -import { - EVENT_TYPES_USER_DATA, - getLegacyWsKeyContext, - getLegacyWsStoreKeyWithContext, - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getRealWsKeyFromDerivedWsKey, - getTestnetWsKey, - getTopicsPerWSKey, - getWsKeyForProductGroup, - getWsUrl, - getWsURLSuffix, - isPrivateWsTopic, - isWSPingFrameAvailable, - isWSPongFrameAvailable, - MiscUserDataConnectionState, - parseEventTypeFromMessage, - parseRawWsMessage, - resolveUserDataMarketForWsKey, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WSAPIWsKey, - WSConnectionCategory, - WsKey, - WsTopicRequest, -} from './util/websockets/websocket-util'; -import { WSConnectedResult } from './util/websockets/WsStore.types'; +export interface GetIndexLinkedPlanRedemptionHistoryParams { + requestId: number; + startTime?: number; + endTime?: number; + current?: number; + asset?: string; + size?: number; +} ⋮---- -type TopicRequestsPerWsKeyEntry = [WsKey, WsTopicRequest[]]; +export interface IndexLinkedPlanRedemptionRecord { + indexId: number; + indexName: string; + redemptionId: number; + status: 'SUCCESS' | 'FAILED'; + asset: string; + amount: string; + redemptionDateTime: number; + transactionFee: string; + transactionFeeUnit: string; +} ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface GetIndexLinkedPlanRebalanceHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} +⋮---- +export interface RebalanceTransactionDetail { + asset: string; + transactionDateTime: number; + rebalanceDirection: 'BUY' | 'SELL'; + rebalanceAmount: string; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ +export interface IndexLinkedPlanRebalanceRecord { + indexId: number; + indexName: string; + rebalanceId: number; + status: 'SUCCESS' | 'INIT'; + rebalanceFee: string; + rebalanceFeeUnit: string; + transactionDetails: RebalanceTransactionDetail[]; +} ⋮---- -/** - * Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets. - * - * When possible, it will subscribe to all requested topics on a single websocket connection. A list of - * all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts. - * - * Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically - * clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics. - * - * If any connection is reconnected, the WS client will: - * - Emit the "reconnecting" event when the process begins. - * - Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a - * good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed - * while disconnected. - * - * User data streams will use a dedicated connection per stream for increased resilience. - */ +export interface SubscribeEthStakingV2Response { + success: boolean; + wbethAmount: string; + conversionRatio: string; +} ⋮---- -export class WebsocketClient extends BaseWebsocketClient< +export interface RedeemEthParams { + asset?: string; + amount: number; +} ⋮---- -constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger) +export interface RedeemEthResponse { + success: boolean; + arrivalTime: number; + ethAmount: string; + conversionRatio: string; +} ⋮---- -/** - * Binance uses native WebSocket ping/pong frames, which cannot be directly used in - * some environents (e.g. most browsers do not support sending raw ping/pong frames). - * - * This disables heartbeats in those environments, if ping/pong frames are unavailable. - * - * Some browsers may still handle these automatically. Some discussion around this can - * be found here: https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser - */ +export interface GetEthStakingHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// fn pointers: +export interface EthStakingHistory { + time: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAmount: string; + conversionRatio: string; +} ⋮---- -private getUserDataStreamManager(): UserDataStreamManager +export interface GetEthRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -private getRestClientOptions(): RestClientOptions +export interface EthRedemptionHistory { + time: number; + arrivalTime: number; + asset: string; + amount: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; + distributeAsset: string; + distributeAmount: string; + conversionRatio: string; +} ⋮---- -/** - * Request connection of all dependent (public & WS API) websockets in prod, instead of waiting - * for automatic connection by SDK. - * - * For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group. - */ -public connectAll(): Promise[] +export interface GetBethRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if - * you're only working with one product group. - */ -public connectPublic(): Promise[] +export interface BethRewardsHistory { + time: number; + asset: string; + holding: string; + amount: string; + annualPercentageRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} ⋮---- -/** - * This function serves no purpose in the Binance SDK - */ -public async connectPrivate(): Promise +export interface GetEthStakingQuotaResponse { + leftStakingPersonalQuota: string; + leftRedemptionPersonalQuota: string; +} ⋮---- -/** - * Ensures the WS API connection is active and ready. - * - * You do not need to call this, but if you call this before making any WS API requests, - * it can accelerate the first request (by preparing the connection in advance). - */ -public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise +export interface GetETHRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +export interface ETHRateHistory { + annualPercentageRate: string; + exchangeRate: string; + time: number; +} ⋮---- -/** - * 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, -): Promise +export interface GetEthStakingAccountResponse { + cumulativeProfitInBETH: string; + lastDayProfitInBETH: string; +} ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +export interface GetEthStakingAccountV2Response { + holdingInETH: string; + holdings: { + wbethAmount: string; + bethAmount: string; + }; + thirtyDaysProfitInETH: string; + profit: { + amountFromWBETH: string; + amountFromBETH: string; + }; +} ⋮---- -/** - * - * - * - * WS API Methods - similar to the REST API, but via WebSockets - * https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * - * https://github.com/tiagosiebler/awesome-crypto-examples/wiki/REST-API-vs-WebSockets-vs-WebSocket-API - * - * - * - */ +export interface WrapBethResponse { + success: boolean; + wbethAmount: string; + exchangeRate: string; +} ⋮---- -/** - * 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: - * - * - Spot: https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * - USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info - * - COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info - * - * - * 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. - * - * Misc options: - * - signRequest: boolean - if included, this request will automatically be signed with the available credentials. - * - * @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 - */ +export interface GetWrapHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// This overload allows the caller to omit the 3rd param, if it isn't required -sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - // if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap - TWSParams extends Exact[TWSOperation]>, - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: TWSKey, - operation: TWSOperation, - params?: TWSParams extends void | never ? undefined : TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; +export interface WrapHistory { + time: number; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + exchangeRate: string; + status: 'PENDING' | 'SUCCESS' | 'FAILED'; +} ⋮---- -// if this throws a type error, probably forgot to add a new operation to WsAPITopicRequestParamMap +export interface WbethRewardsHistory { + time: number; + amountInETH: string; + holding: string; + holdingInETH: string; + annualPercentageRate: string; +} ⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends Exact[TWSOperation]>, - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: WsKey, - operation: TWSOperation, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, -): Promise +export interface GetWbethRewardsHistoryResponse { + estRewardsInETH: string; + rows: WbethRewardsHistory[]; + total: number; +} ⋮---- /** - * Spot: - * -> https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information - * -> https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md#public-api-requests - * USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info - * COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info - */ -⋮---- -// If testnet, enforce testnet wskey for WS API calls + * BFUSD (sapi/v1/bfusd/*) + */ ⋮---- -// this.logger.trace(`sendWSAPIRequest(): assertIsConnected("${wsKey}")...`); +export interface BfusdAccountResponse { + bfusdAmount: string; + usdtProfit: string; + bfusdProfit: string; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsConnected(${wsKey}) ok'); +export interface BfusdSubscriptionQuota { + leftQuota: string; +} ⋮---- -// Some commands don't require authentication. +export interface BfusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; +} ⋮---- -// Only if authOnConnect is enabled (aka using Ed25519 keys) +export interface BfusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +export interface BfusdQuotaResponse { + subscriptionQuota: BfusdSubscriptionQuota; + fastRedemptionQuota: BfusdFastRedemptionQuota; + standardRedemptionQuota: BfusdStandardRedemptionQuota; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +export interface BfusdSubscribeParams { + asset: string; + amount: number; +} ⋮---- -/** - * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated - * can introduce a small delay before the actual request is sent, if not connected before that request is - * made. This can lead to a curious race condition, where the request timestamp is before - * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. - * - * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, - * it offsets that timestamp by the delay. - */ +export interface BfusdSubscribeResponse { + success: boolean; + bfusdAmount: string; +} ⋮---- -// Sign, if needed +export interface BfusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; +} ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +export interface BfusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; +} ⋮---- -// Enrich returned promise with request context for easier debugging +export interface GetBfusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// throw e; +export interface BfusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} ⋮---- -// this.logger.trace( -// `sendWSAPIRequest(): sending raw request: ${JSON.stringify(signedEvent)} with promiseRef(${promiseRef})`, -// ); +export interface GetBfusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// Send event. +export interface BfusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; +} ⋮---- -// Return deferred promise, so caller can await this call +export interface GetBfusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * - * - * Internal methods - not intended for public use - * - * - */ +export interface BfusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + annualPercentageRate: string; + rewardAsset?: string; + /** API may return this casing per Binance docs. */ + BFUSDPosition?: string; +} ⋮---- -/** - * @returns The WS URL to connect to for this WS key - */ -async getWsUrl( - wsKey: WsKey, - connectionType: 'public' | 'market' | 'private' = 'market', -): Promise +/** API may return this casing per Binance docs. */ ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +export interface GetBfusdRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// return await signMessageWebCryptoAPI(paramsStr, secret, method, algorithm); +export interface BfusdRateHistoryRow { + annualPercentageRate: string; + time: number; +} ⋮---- /** - * Handles request sign, if connection isn't authenticated yet. - * If connection does not need to be authenticated or request doesn't require sign, - * use the requestFlags.authIsOptional flag to skip sign and send the request immediately. - */ -private async signWSAPIRequest( - requestEvent: WsRequestOperationBinance, - requestFlags?: WSAPIRequestFlags, -): Promise> + * RWUSD (sapi/v1/rwusd/*) + */ ⋮---- -/** - * Not really needed for most commands on Binance. Their WS API supports - * sending signed WS API commands, but that adds latency to every request. - * - * Instead, this SDK will authenticate once after connecting. All requests - * after authentication can then be sent without sign for maximum speed. - */ +export interface RwusdAccountResponse { + rwusdAmount: string; + totalProfit: string; +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, - ): Promise< - WsRequestOperationBinance< - string, - { apiKey: string; signature: string; timestamp: number } - > - > { - try { - // Note: Only Ed25519 keys are supported for this feature. - // RSA & HMAC keys will automatically sign each individual request instead. - - // If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. - - // Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. - - // Note: You still have to specify the timestamp parameter for SIGNED requests. - const timestamp = Date.now() + (this.getTimeOffsetMs() || 0); +export interface RwusdSubscriptionQuota { + assets: string[]; + leftQuota: string; + minimum: string; +} ⋮---- -// Note: Only Ed25519 keys are supported for this feature. -// RSA & HMAC keys will automatically sign each individual request instead. +export interface RwusdFastRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + freeQuota: string; +} ⋮---- -// If you do not want to specify apiKey and signature in each individual request, you can authenticate your API key for the active WebSocket session. +export interface RwusdStandardRedemptionQuota { + leftQuota: string; + minimum: string; + fee: string; + redeemPeriod: number; +} ⋮---- -// Once authenticated, you no longer have to specify apiKey and signature for those requests that need them. Requests will be performed on behalf of the account owning the authenticated API key. +export interface RwusdQuotaResponse { + subscriptionQuota: RwusdSubscriptionQuota; + fastRedemptionQuota: RwusdFastRedemptionQuota; + standardRedemptionQuota: RwusdStandardRedemptionQuota; + subscribeEnable: boolean; + redeemEnable: boolean; +} ⋮---- -// Note: You still have to specify the timestamp parameter for SIGNED requests. +export interface RwusdSubscribeParams { + asset: string; + amount: number; +} +⋮---- +export interface RwusdSubscribeResponse { + success: boolean; + rwusdAmount: string; +} ⋮---- -protected sendPingEvent(wsKey: WsKey) +export interface RwusdRedeemParams { + amount: number; + type?: 'FAST' | 'STANDARD'; +} ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +export interface RwusdRedeemResponse { + success: boolean; + receiveAmount: string; + fee: string; + arrivalTime: number; +} ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +export interface GetRwusdSubscriptionHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -protected sendPongEvent(wsKey: WsKey) +export interface RwusdSubscriptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + status: 'PENDING' | 'SUCCESS'; +} ⋮---- -// this.logger.trace(`Sending upstream ping: `, { ...loggerCategory, wsKey }); +export interface GetRwusdRedemptionHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// Binance allows unsolicited pongs, so we send both (though we expect a pong in response to our ping if the connection is still alive) +export interface RwusdRedemptionHistoryRow { + time: number; + asset: string; + amount: string; + receiveAsset: string; + receiveAmount: string; + fee: string; + arrivalTime: number; + status: 'PENDING' | 'SUCCESS'; +} ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface GetRwusdRewardsHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - wsKey: WsKey, - operation: WsOperation, - requests: WsTopicRequest[], -): Promise>[]> +export interface RwusdRewardsHistoryRow { + time: number; + rewardsAmount: string; + rwusdPosition: string; + annualPercentageRate: string; +} ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +export interface GetRwusdRateHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -// Cache midflight subs on the req ID -// Enrich response with subs for that req ID +export interface RwusdRateHistoryRow { + annualPercentageRate: string; + time: number; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface GetMiningAlgoListResponse { + algoName: string; // Algorithm name + algoId: number; // Algorithm ID + poolIndex: number; // Sequence + unit: string; // Unit +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +algoName: string; // Algorithm name +algoId: number; // Algorithm ID +poolIndex: number; // Sequence +unit: string; // Unit ⋮---- -/** - * Determines if a topic is for a private channel, using a hardcoded list of strings - */ -protected isPrivateTopicRequest(request: WsTopicRequest): boolean +export interface GetMiningCoinListResponse { + coinName: string; // Coin name + coinId: number; // Coin ID + poolIndex: number; // Sequence + unit: string; // Unit +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPing(msg: any): boolean +coinName: string; // Coin name +coinId: number; // Coin ID +poolIndex: number; // Sequence +unit: string; // Unit ⋮---- -// For binance, all ping/pong events are frame events +export interface GetMinerDetailsParams { + algo: string; + userName: string; + workerName: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any -protected isWsPong(msg: any): boolean +export interface HashrateData { + time: number; + hashrate: string; + reject: number; +} ⋮---- -// For binance, all ping/pong events are frame events +export interface MinerDetail { + workerName: string; + type: string; + hashrateDatas: HashrateData[]; +} ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, -): EmittableEvent[] +export interface GetMinerDetailsResponse { + code: number; + msg: string; + data: MinerDetail[]; +} ⋮---- -// this.logger.trace(`resolveEmittableEvents(${wsKey}): `, event?.data); +export interface GetMinerListParams { + algo: string; + userName: string; + pageIndex?: number; + sort?: number; + sortColumn?: number; + workerStatus?: number; +} ⋮---- -/** - * - * Extract event from JSON - * - */ +export interface WorkerData { + workerId: string; + workerName: string; + status: number; + hashRate: number; + dayHashRate: number; + rejectRate: number; + lastShareTime: number; +} ⋮---- -/** - * - * Minor data normalisation & preparation - * - */ +export interface GetMinerListResponse { + code: number; + msg: string; + data: { + workerDatas: WorkerData[]; + totalNum: number; + pageSize: number; + }; +} ⋮---- -// ws consumers: { data: ... } -// ws api consumers (user data): { event: ... } -// other responses: { ... } +export interface GetEarningsListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} ⋮---- -// First try, the child node +export interface AccountEarningsProfit { + time: number; + type: number; + hashTransfer: number | null; + transferAmount: number | null; + dayHashRate: number; + profitAmount: number; + coinName: string; + status: number; +} ⋮---- -// Second try, the parent +export interface GetEarningsListResponse { + code: number; + msg: string; + data: { + accountProfits: AccountEarningsProfit[]; + totalNum: number; + pageSize: number; + }; +} ⋮---- -// Some events don't include the topic (event name) -// This tries to extract and append it, using available context +export interface GetExtraBonusListParams { + algo: string; + userName: string; + coin?: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} ⋮---- -// This attaches `wsMarket` and `streamName` to incoming events -// If the event is an array, it's attached to each element in the array +export interface OtherProfit { + time: number; + coinName: string; + type: number; + profitAmount: number; + status: number; +} ⋮---- -/** - * - * - * Main parsing logic below: - * - * - */ +export interface GetExtraBonusListResponse { + code: number; + msg: string; + data: { + otherProfits: OtherProfit[]; + totalNum: number; + pageSize: number; + }; +} ⋮---- -// parsed: JSON.stringify(parsed, null, 2), +export interface GetHashrateResaleListParams { + pageIndex?: number; + pageSize?: number; +} ⋮---- -// WS API response +export interface ConfigDetail { + configId: number; + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + startDay: number; + endDay: number; + status: number; +} ⋮---- -/** - * Responses to "subscribe" are quite basic, with no indication of errors (e.g. bad topic): - * - * { - * result: null, - * id: 1, - * }; - * - * Currently there's no simple way to tell this apart from an actual WS API response with - * error. So subscribe/unsubscribe requests will simply look like a WS API response internally, - * but that will not affect usage. - * - * Unrelated, example wsapi error for reference: - * - { - id: 1, - status: 400, - error: { - code: -1021, - msg: "Timestamp for this request was 1000ms ahead of the server's time." - }, - rateLimits: [ - { - rateLimitType: 'REQUEST_WEIGHT', - interval: 'MINUTE', - intervalNum: 1, - limit: 6000, - count: 4 - } - ], - wsKey: 'mainWSAPI', - isWSAPIResponse: true - } - */ +export interface GetHashrateResaleListResponse { + code: number; + msg: string; + data: { + configDetails: ConfigDetail[]; + totalNum: number; + pageSize: number; + }; +} ⋮---- -// This is the counterpart to getPromiseRefForWSAPIRequest +export interface GetHashrateResaleDetailParams { + configId: number; + userName: string; + pageIndex?: number; + pageSize?: number; +} ⋮---- -// WS API Exception +export interface ProfitTransferDetail { + poolUsername: string; + toPoolUsername: string; + algoName: string; + hashRate: number; + day: number; + amount: number; + coinName: string; +} ⋮---- -// authenticated +export interface GetHashrateResaleDetailResponse { + code: number; + msg: string; + data: { + profitTransferDetails: ProfitTransferDetail[]; + totalNum: number; + pageSize: number; + }; +} +export interface SubmitHashrateResaleParams { + userName: string; + algo: string; + endDate: number; + startDate: number; + toPoolUser: string; + hashRate: number; +} ⋮---- -// Note: Without this check, this will also trigger "onWsAuthenticated()" for session.status requests +export interface CancelHashrateResaleConfigParams { + configId: number; + userName: string; +} ⋮---- -// WS API Success +export interface GetStatisticListParams { + algo: string; + userName: string; +} ⋮---- -// Handle incoming event that listen key expired +export interface Profit { + BTC: string; + BSV: string; + BCH: string; +} ⋮---- -// handle this how? +export interface GetStatisticListResponse { + code: number; + msg: string; + data: { + fifteenMinHashRate: string; + dayHashRate: string; + validNum: number; + invalidNum: number; + profitToday: Profit; + profitYesterday: Profit; + userName: string; + unit: string; + algo: string; + }; +} ⋮---- -// Just closing the connection (with the last parameter as true) will handle cleanup and respawn -// Automatically leads to triggerCustomReconnectionWorkflow() to handle fresh user data respawn +export interface getMiningAccountsListParams { + algo: string; + userName: string; +} ⋮---- -// Suffix all events for the beautifier, if market is options -// Options has some conflicting keys with different intentions, so will be suffixed +export interface MiningHashrateData { + time: number; + hashrate: string; + reject: string; +} ⋮---- -// emit an additional event for user data messages +export interface MiningAccountData { + type: string; + userName: string; + list: MiningHashrateData[]; +} ⋮---- -// Messages for a subscribed topic all include the "topic" property +export interface getMiningAccountsListResponse { + code: number; + msg: string; + data: MiningAccountData[]; +} ⋮---- -// Messages that are a "reply" to a request/command (e.g. subscribe to these topics) typically include the "op" property +export interface GetMiningAccountEarningParams { + algo: string; + startDate?: number; + endDate?: number; + pageIndex?: number; + pageSize?: number; +} ⋮---- -// Failed request +export interface AccountMiningProfit { + time: number; + coinName: string; + type: number; + puid: number; + subName: string; + amount: number; +} ⋮---- -// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) +export interface GetMiningAccountEarningResponse { + code: number; + msg: string; + data: { + accountProfits: AccountMiningProfit[]; + totalNum: number; + pageSize: number; + }; +} ⋮---- -// Request/reply pattern for authentication success +export interface GetFutureTickLevelOrderbookDataLinkParams { + symbol: string; + dataType: 'T_DEPTH' | 'S_DEPTH'; + startTime: number; + endTime: number; +} ⋮---- -// In case of catastrophic failure, fallback to noisy emit update +export interface HistoricalDataLink { + day: string; + url: string; +} ⋮---- -/** - * - * - * - * - * - * User Data Streams - * - * - * - * - * - */ +export interface SubmitVpNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + urgency: 'LOW' | 'MEDIUM' | 'HIGH'; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; +} ⋮---- -/** - * -------------------------- - * User data listen key tracking & persistence - * -------------------------- - **/ +export interface SubmitVpNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} ⋮---- -/** - * Subscribe to a spot user data stream. Use REST client to generate and persist listen key. - * Supports spot, margin & isolated margin listen keys. - */ -public async subscribeSpotUserDataStreamWithListenKey( - wsKey: WsKey, - listenKey: string, - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface SubmitTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + positionSide?: 'BOTH' | 'LONG' | 'SHORT'; + quantity: number; + duration: number; + clientAlgoId?: string; + reduceOnly?: boolean; + limitPrice?: number; +} ⋮---- -/** - * Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeSpotUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface SubmitTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} ⋮---- -public unsubscribeSpotUserDataStream(wsKey: WsKey = 'main'): Promise +export interface CancelAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; +} ⋮---- -public async fetchMarginListenToken(params?: { - symbol?: string; - isIsolated?: boolean; - validity?: number; -}): Promise< +export interface AlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; +} ⋮---- -/** - * Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface GetAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: number; +} ⋮---- -public unsubscribeCrossMarginUserDataStream( - wsKey: WsKey = 'main', -): Promise +export interface HistoricalAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + positionSide: 'BOTH' | 'LONG' | 'SHORT'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; +} ⋮---- -/** - * Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeIsolatedMarginUserDataStream( - symbol: string, - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface GetAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; +} ⋮---- -public unsubscribeIsolatedMarginUserDataStream( - symbol: string, - wsKey: WsKey = 'main', -): Promise +export interface SubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; +} ⋮---- -/** - * Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2)) - */ -public async subscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface GetAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SubOrder[]; +} ⋮---- -public unsubscribeMarginRiskUserDataStream( - wsKey: WsKey = 'main', -): Promise +export interface SubmitSpotTwapNewOrderParams { + symbol: string; + side: 'BUY' | 'SELL'; + quantity: number; + duration: number; + clientAlgoId?: string; + limitPrice?: number; + stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; +} ⋮---- -/** - * -------------------------- - * End of SPOT market websocket streams - * -------------------------- - **/ +export interface SubmitSpotTwapNewOrderResponse { + clientAlgoId: string; + success: boolean; + code: number; + msg: string; +} ⋮---- -/** - * Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribeUsdFuturesUserDataStream( - userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface CancelSpotAlgoOrderResponse { + algoId: number; + success: boolean; + code: number; + msg: string; +} ⋮---- -userWsKey: WsKey = WS_KEY_MAP.usdmPrivate, // usdmPrivate | usdmTestnetPrivate +export interface SpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; + /** Order duration in seconds. Only returned for TWAP orders. */ + duration?: number; +} ⋮---- -// Prevent 'usdm' from being used unintentionally, since this has to be routed via the private endpoints. +/** Order duration in seconds. Only returned for TWAP orders. */ ⋮---- -public unsubscribeUsdFuturesUserDataStream( - wsKey: WsKey = WS_KEY_MAP.usdmPrivate, -): Promise +export interface GetSpotAlgoHistoricalOrdersParams { + symbol?: string; + side?: 'BUY' | 'SELL'; + startTime?: number; + endTime?: number; + page?: number; + pageSize?: number; +} ⋮---- -/** - * Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', // coinm | coinmTestnet - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface HistoricalSpotAlgoOrder { + algoId: number; + symbol: string; + side: 'BUY' | 'SELL'; + totalQty: string; + executedQty: string; + executedAmt: string; + avgPrice: string; + clientAlgoId: string; + bookTime: number; + endTime: number; + algoStatus: string; + algoType: string; + urgency: string; + /** Order duration in seconds. Only returned for TWAP orders. */ + duration?: number; +} ⋮---- -wsKey: WsKey = 'coinm', // coinm | coinmTestnet +/** Order duration in seconds. Only returned for TWAP orders. */ ⋮---- -public unsubscribeCoinFuturesUserDataStream( - wsKey: WsKey = 'coinm', -): Promise +export interface GetSpotAlgoSubOrdersParams { + algoId: number; + page?: number; + pageSize?: number; +} ⋮---- -/** - * Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection. - * - * Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group. - */ -public async subscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', - forceNewConnection?: boolean, - miscState?: MiscUserDataConnectionState, -): Promise +export interface SpotSubOrder { + algoId: number; + orderId: number; + orderStatus: string; + executedQty: string; + executedAmt: string; + feeAmt: string; + feeAsset: string; + bookTime: number; + avgPrice: string; + side: 'BUY' | 'SELL'; + symbol: string; + subId: number; + timeInForce: string; + origQty: string; +} ⋮---- -public unsubscribePortfolioMarginUserDataStream( - wsKey: WsKey = 'portfolioMarginUserData', -): Promise +export interface GetSpotAlgoSubOrdersResponse { + total: number; + executedQty: string; + executedAmt: string; + subOrders: SpotSubOrder[]; +} ⋮---- -/** - * Close an active, dedicated, user data stream connection. - * - * @param wsKey - the connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures. - * @param wsMarket - the product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)). - */ -public async closeUserDataStream( - wsKey: WsKey, - wsMarket: WsMarket, - symbol?: string, -): Promise +export interface GetPortfolioMarginProAccountInfoResponse { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + accountStatus: string; + accountType: string; +} ⋮---- -// built around the assumption in how per-connection listen key wskeys are created -// isolatedMargin_userData_BTCUSDC_6RszN123x213x1233x213x1233x213xx123x1uzkTV_main -// coinm_userData__WRAVTxGaQa1Nhd1243312kjn13kj12n3m5wRFv6JoFQgwUR5AEFofZtlk_coinm +export interface PortfolioDeltaModeStatus { + deltaEnabled: boolean; +} ⋮---- -protected isCustomReconnectionNeeded(wsKey: string): boolean +export interface SwitchPortfolioDeltaModeParams { + deltaEnabled: 'true' | 'false'; +} ⋮---- -protected async triggerCustomReconnectionWorkflow( - legacyWsKey: string, -): Promise +export interface GetPortfolioMarginProCollateralRateResponse { + asset: string; + collateralRate: string; +} ⋮---- -private async respawnUserDataStream( - wsKey: WsKey, - market: WsMarket, - context: { - symbol?: string; - isTestnet?: boolean; - respawnAttempt?: number; - } = {}, -): Promise +export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { + asset: string; + amount: string; +} ⋮---- -// Handle corner case where wsKey is still the derived key for some reason... +export interface GetPortfolioMarginProInterestHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; + size?: number; +} ⋮---- -// If another connection attempt is in progress for this listen key, don't initiate a retry or the risk is multiple connections on the same listen key +export interface GetPortfolioMarginProInterestHistoryResponse { + asset: string; + interest: string; + interestAccruedTime: number; + interestRate: string; + principal: string; +} ⋮---- -// Prevent simultaneous timers in same scope +export interface GetPortfolioMarginAssetIndexPriceResponse { + asset: string; + assetIndexPrice: string; + time: number; +} ⋮---- -// Execute reconnection workflow after short delay +export interface BnbTransferParams { + amount: number; + transferSide: 'TO_UM' | 'FROM_UM'; +} ⋮---- -/** - * Subscribe to the European Options user data stream - listen key is automatically generated. - * - * Not supported at this time. Please get in touch if you need this. - */ -// public async subscribeEuropeanOptionsUserData( -// wsKey: WsKey = 'eoptions', -// forceNewConnection?: boolean, -// isReconnecting?: boolean, -// ): Promise { -// try { -// const { listenKey } = await this.restClientCache -// .getEuropeanOptionsClient( -// this.getRestClientOptions(), -// this.options.requestOptions, -// ) -// .getUserDataListenKey(); +export interface GetPortfolioMarginAssetLeverageResponse { + asset: string; + leverage: number; +} ⋮---- -// const market: WsMarket = 'options'; +export interface SetPortfolioMarginMarginCallLevelParams { + marginCallLevel: number; +} ⋮---- -// return this.subscribeGeneralUserDataStreamWithListenKey( -// wsKey, -// market, -// listenKey, -// forceNewConnection, -// isReconnecting, -// ); -// } catch (e) { -// this.logger.error('Failed to connect to Options user data', { -// ...WS_LOGGER_CATEGORY, -// error: e, -// }); -// this.emit('exception', { -// functionRef: 'subscribePortfolioMarginUserDataStream()', -// wsKey, -// forceNewConnection, -// isReconnecting, -// error: e?.stack || e, -// }); -// } -// } +export interface PortfolioMarginMarginCallLevelResponse { + marginCallLevel: string; +} ⋮---- -/** - * - * - * - * - * Convenient subscribe methods, similar to the legacy WebsocketClient for Binance. - * - * - * - * - */ +export type PortfolioMarginMarginCallLevelGetResponse = + | PortfolioMarginMarginCallLevelResponse + | Record; ⋮---- -/** - * -------------------------- - * Universal market websocket streams (may apply to one or more API markets) - * -------------------------- - **/ +export interface PortfolioMarginMarginCallLevelDeleteResponse { + msg: string; +} ⋮---- -/** - * Advanced: Subscribe to a universal market websocket stream - * - * This is NOT recommended unless you're very confident with what you're doing. - */ -public subscribeEndpoint( - endpoint: string, - market: 'spot' | 'usdm' | 'coinm', -): Promise +export interface SubscribeBlvtParams { + tokenName: string; + cost: number; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in a market category - */ -public subscribeAggregateTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface SubscribeBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + amount: string; + cost: string; + timestamp: number; +} ⋮---- -/** - * Subscribe to trades for a symbol in a market category - * IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning - */ -public subscribeTrades( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface GetBlvtSubscriptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface BlvtSubscriptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + totalCharge: string; + timestamp: number; +} ⋮---- -/** - * Subscribe to coin index for a symbol in COINM Futures markets - * `_updateSpeedMs` is ignored (`@indexPrice@1s` was removed). Drop this arg in the next major. - */ -public subscribeCoinIndexPrice( - symbol: string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): Promise +export interface RedeemBlvtParams { + tokenName: string; + amount: number; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface RedeemBlvtResponse { + id: number; + status: 'S' | 'P' | 'F'; + tokenName: string; + redeemAmount: string; + amount: string; + timestamp: number; +} ⋮---- -/** - * Subscribe to mark price for a symbol in a market category - */ -public subscribeMarkPrice( - symbol: string, - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): Promise +export interface GetBlvtRedemptionRecordParams { + tokenName?: string; + id?: number; + startTime?: number; + endTime?: number; + limit?: number; +} +⋮---- +export interface BlvtRedemptionRecord { + id: number; + tokenName: string; + amount: string; + nav: string; + fee: string; + netProceed: string; + timestamp: number; +} ⋮---- -/** - * Subscribe to mark price for all symbols in a market category - */ -public subscribeAllMarketMarkPrice( - market: 'usdm' | 'coinm', - updateSpeedMs: 1000 | 3000 = 3000, - wsKeyOverride?: WsKey, -): Promise +export interface BlvtUserLimitInfo { + tokenName: string; + userDailyTotalPurchaseLimit: string; + userDailyTotalRedeemLimit: string; +} ⋮---- -/** - * Subscribe to klines(candles) for a symbol in a market category - */ -public subscribeKlines( - symbol: string, - interval: KlineInterval, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface GetFiatOrderHistoryParams { + transactionType: string; + beginTime?: number; + endTime?: number; + page?: number; + rows?: number; +} ⋮---- -/** - * Subscribe to continuous contract klines(candles) for a symbol futures - */ -public subscribeContinuousContractKlines( - symbol: string, - contractType: 'perpetual' | 'current_quarter' | 'next_quarter', - interval: KlineInterval, - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface GetFiatOrderHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + fiatCurrency: string; + indicatedAmount: string; + amount: string; + totalFee: string; + method: string; + status: string; + createTime: number; + updateTime: number; + }[]; + total: number; + success: boolean; +} ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeIndexKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise +export interface GetFiatPaymentsHistoryResponse { + code: string; + message: string; + data: { + orderNo: string; + sourceAmount: string; + fiatCurrency: string; + obtainAmount: string; + cryptoCurrency: string; + totalFee: string; + price: string; + status: string; + paymentMethod?: string; + createTime: number; + updateTime: number; + }[]; + total: number; + success: boolean; +} ⋮---- -/** - * Subscribe to index klines(candles) for a symbol in a coinm futures - */ -public subscribeMarkPriceKlines( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise +export interface WithdrawFiatAccountInfo { + accountNumber: string; + agency: string; + bankCodeForPix: string; + accountType: string; +} ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in market category. - */ -public subscribeSymbolMini24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface WithdrawFiatParams { + currency: string; + apiPaymentMethod: string; + amount: number; + accountInfo?: WithdrawFiatAccountInfo; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in market category. - */ -public subscribeAllMini24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface FiatDepositParams { + currency: string; + apiPaymentMethod: string; + amount: number; + ext?: object; + recvWindow?: number; + timestamp?: number; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in any market. - */ -public subscribeSymbol24hrTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface FiatDepositResponse { + code: string; + message: string; + data: { + orderId: string; + }; +} ⋮---- -/** - * Subscribe to Alpha Trading WebSocket Market Data streams. - * Base URL: wss://nbstream.binance.com/w3w/wsa/stream - */ -public subscribeAlpha(topics: string | string[]): Promise +export interface GetFiatOrderDetailParams { + orderNo: string; + recvWindow?: number; + timestamp?: number; +} ⋮---- -/** - * Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24) - */ -public subscribeAlphaAllTokensTicker24(): Promise +export interface GetFiatOrderDetailResponse { + code: string; + message: string; + data: { + orderId: string; + orderStatus: string; + amount: string; + fee: string; + fiatCurrency: string; + errorCode: string; + errorMessage: string; + ext: object; + }; +} ⋮---- -/** - * Subscribe to Alpha aggregate trades for a symbol - * @param symbol e.g. ALPHA_474USDT - */ -public subscribeAlphaAggTrade(symbol: string): Promise +export interface GetC2CTradeHistoryParams { + tradeType: string; + startTimestamp?: number; + endTimestamp?: number; + page?: number; + rows?: number; +} ⋮---- -/** - * Subscribe to Alpha full depth for a symbol - * @param symbol e.g. ALPHA_474USDT - * @param intervalMs 0, 100, or 500 - */ -public subscribeAlphaFulldepth( - symbol: string, - intervalMs: 0 | 100 | 500 = 500, -): Promise +export interface c2cTradeData { + orderNumber: string; + advNo: string; + tradeType: string; + asset: string; + fiat: string; + fiatSymbol: string; + amount: string; + totalPrice: string; + unitPrice: string; + orderStatus: string; + createTime: number; + commission: string; + counterPartNickName: string; + advertisementRole: string; +} +export interface GetC2CTradeHistoryResponse { + code: string; + message: string; + data: c2cTradeData[]; + total: number; + success: boolean; +} ⋮---- -/** - * Subscribe to Alpha klines for a contract - * @param contractAddress Contract address - * @param chainId Chain ID (e.g. CT_501, 56) - * @param interval 1s, 1m, 5m, 15m, 1h, 4h, 1d - */ -public subscribeAlphaKline( - contractAddress: string, - chainId: string, - interval: '1s' | '1m' | '5m' | '15m' | '1h' | '4h' | '1d', -): Promise +export interface GetVipLoanOngoingOrdersParams { + orderId?: number; + collateralAccountId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} +⋮---- +export interface VipOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + loanRate: string; + residualInterest: string; + collateralAccountId: string; + collateralCoin: string; + totalCollateralValueAfterHaircut: string; + lockedCollateralValue: string; + currentLTV: string; + expirationTime: number; + loanDate: string; + loanTerm: string; + initialLtv: string; + marginCallLtv: string; + liquidationLtv: string; +} +⋮---- +export interface VipLoanRepayParams { + orderId: number; + amount: number; +} ⋮---- -/** - * Subscribe to 24hr ticker in any market. - */ -public subscribeAll24hrTickers( - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanRepayResponse { + loanCoin: string; + repayAmount: string; + remainingPrincipal: string; + remainingInterest: string; + collateralCoin: string; + currentLTV: string; + repayStatus: string; +} ⋮---- -/** - * Subscribe to rolling window ticker statistics for all market symbols, - * computed over multiple windows. Note that only tickers that have - * changed will be present in the array. - * - * Notes: - * - Supported window sizes: 1h,4h,1d. - * - Supported markets: spot - */ -public subscribeAllRollingWindowTickers( - market: 'spot', - windowSize: '1h' | '4h' | '1d', - wsKeyOverride?: WsKey, -): Promise +export interface GetVipLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolBookTicker( - symbol: string, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + repayInterest: string; + repayPrincipal: string; + collateralCoin: string; + repayStatus: string; + loanDate: string; + repayTime: string; + orderId: string; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllBookTickers( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanRenewParams { + orderId: number; + loanTerm?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSymbolLiquidationOrders( - symbol: string, - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanRenewResponse { + loanAccountId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeAllLiquidationOrders( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface CheckVipCollateralAccountParams { + orderId?: number; + collateralAccountId?: number; +} ⋮---- -/** - * Subscribe to partial book depths (snapshots). - * - * Note: - * - spot only supports 1000ms or 100ms for updateMs - * - futures only support 100, 250 or 500ms for updateMs - */ -public subscribePartialBookDepths( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 100 | 250 | 500 | 1000, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipCollateralAccount { + collateralAccountId: string; + collateralCoin: string; +} ⋮---- -/** - * Subscribe to orderbook depth updates to locally manage an order book. - * - * Note that the updatems parameter depends on which market you're trading - * - * - Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream - * - USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams - */ -public subscribeDiffBookDepth( - symbol: string, - updateMs: 100 | 250 | 500 | 1000 = 100, - market: 'spot' | 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanBorrowParams { + loanAccountId: number; + loanCoin: string; + loanAmount: number; + collateralAccountId: string; + collateralCoin: string; + isFlexibleRate: boolean; + loanTerm?: number; +} ⋮---- -/** - * Subscribe to best bid/ask for all symbols in spot markets. - */ -public subscribeContractInfoStream( - market: 'usdm' | 'coinm', - wsKeyOverride?: WsKey, -): Promise +export interface VipLoanBorrowResponse { + loanAccountId: string; + requestId: string; + loanCoin: string; + isFlexibleRate: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm?: string; +} ⋮---- -/** - * -------------------------- - * SPOT market websocket streams - * -------------------------- - **/ +export interface GetLoanableAssetsDataParams { + loanCoin?: string; + vipLevel?: number; +} ⋮---- -/** - * Subscribe to aggregate trades for a symbol in spot markets. - */ -public subscribeSpotAggregateTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface GetApplicationStatusParams { + current?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to trades for a symbol in spot markets. - */ -public subscribeSpotTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface ApplicationStatus { + loanAccountId: string; + orderId: string; + requestId: string; + loanCoin: string; + loanAmount: string; + collateralAccountId: string; + collateralCoin: string; + loanTerm: string; + status: string; + loanDate: string; +} ⋮---- -/** - * Subscribe to block trades for a symbol in spot markets. - */ -public subscribeSpotBlockTrades( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface BorrowInterestRate { + asset: string; + flexibleDailyInterestRate: string; + flexibleYearlyInterestRate: string; + time: number; +} ⋮---- -/** - * Subscribe to candles for a symbol in spot markets. - */ -public subscribeSpotKline( - symbol: string, - interval: KlineInterval, - wsKeyOverride?: WsKey, -): Promise +export interface GetCryptoLoansIncomeHistoryParams { + asset?: string; + type?: string; + startTime?: number; + endTime?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to mini 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbolMini24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface GetCryptoLoansIncomeHistoryResponse { + asset: string; + type: string; + amount: string; + timestamp: number; + tranId: string; +} ⋮---- -/** - * Subscribe to mini 24hr mini ticker in spot markets. - */ -public subscribeSpotAllMini24hrTickers( - wsKeyOverride?: WsKey, -): Promise +export interface BorrowCryptoLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; + loanTerm: number; +} +⋮---- +export interface BorrowCryptoLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + hourlyInterestRate: string; + orderId: string; +} ⋮---- -/** - * Subscribe to 24hr ticker for a symbol in spot markets. - */ -public subscribeSpotSymbol24hrTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface GetLoanBorrowHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to 24hr ticker in spot markets. - */ -public subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise +export interface LoanBorrowHistory { + orderId: number; + loanCoin: string; + initialLoanAmount: string; + hourlyInterestRate: string; + loanTerm: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: string; +} ⋮---- -/** - * Subscribe to best bid/ask for symbol in spot markets. - */ -public subscribeSpotSymbolBookTicker( - symbol: string, - wsKeyOverride?: WsKey, -): Promise +export interface GetLoanOngoingOrdersParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; +} ⋮---- -/** - * Subscribe to top bid/ask levels for symbol in spot markets. - */ -public subscribeSpotPartialBookDepth( - symbol: string, - levels: 5 | 10 | 20, - updateMs: 1000 | 100 = 1000, - wsKeyOverride?: WsKey, -): Promise +export interface LoanOngoingOrder { + orderId: number; + loanCoin: string; + totalDebt: string; + residualInterest: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; + expirationTime: number; +} ⋮---- -/** - * Subscribe to spot orderbook depth updates to locally manage an order book. - */ -public subscribeSpotDiffBookDepth( - symbol: string, - updateMs: 1000 | 100 = 1000, - wsKeyOverride?: WsKey, -): Promise - -================ -File: src/types/spot.ts -================ -import { - ExchangeFilter, - ExchangeSymbol, - GenericCodeMsgError, - numberInString, - OCOOrderStatus, - OCOStatus, - OrderBookRow, - OrderResponseType, - OrderSide, - OrderStatus, - OrderTimeInForce, - OrderType, - RateLimiter, - SelfTradePreventionMode, - SideEffects, - StringBoolean, - SymbolFilter, -} from './shared'; +export interface RepayCryptoLoanParams { + orderId: number; + amount: number; + type?: number; + collateralReturn?: boolean; +} ⋮---- -export interface BasicTimeRangeParam { - startTime?: number; - endTime?: number; +export interface RepayCryptoLoanResponse { + loanCoin: string; + remainingPrincipal?: string; + remainingInterest?: string; + collateralCoin: string; + remainingCollateral?: string; + currentLTV?: string; + repayStatus: string; } ⋮---- -export interface BasicFromPaginatedParams { - fromId?: number; +export interface GetLoanRepaymentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; startTime?: number; endTime?: number; + current?: number; limit?: number; } ⋮---- -export type SymbolStatus = - | 'PRE_TRADING' - | 'TRADING' - | 'POST_TRADING' - | 'END_OF_DAY' - | 'HALT' - | 'AUCTION_MATCH' - | 'BREAK' - | 'CANCEL_ONLY'; +export interface LoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralUsed: string; + collateralReturn: string; + repayType: string; + repayStatus: string; + repayTime: number; + orderId: number; +} ⋮---- -export interface SystemStatusResponse { - status: 0 | 1; - msg: 'normal' | 'system maintenance'; +export interface AdjustCryptoLoanLTVParams { + orderId: number; + amount: number; + direction: 'ADDITIONAL' | 'REDUCED'; } ⋮---- -export interface DailyAccountSnapshotParams { - type: 'SPOT' | 'MARGIN' | 'FUTURES'; +export interface AdjustCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + currentLTV: string; +} +⋮---- +export interface GetLoanLTVAdjustmentHistoryParams { + orderId?: number; + loanCoin?: string; + collateralCoin?: string; startTime?: number; endTime?: number; + current?: number; limit?: number; } ⋮---- -export interface SpotBalance { - asset: string; - free: numberInString; - locked: numberInString; +export interface LoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + amount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; + orderId: number; } ⋮---- -export interface MarginBalance { - asset: string; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; +export interface LoanableAssetData { + loanCoin: string; + _7dHourlyInterestRate: string; + _7dDailyInterestRate: string; + _14dHourlyInterestRate: string; + _14dDailyInterestRate: string; + _30dHourlyInterestRate: string; + _30dDailyInterestRate: string; + _90dHourlyInterestRate: string; + _90dDailyInterestRate: string; + _180dHourlyInterestRate: string; + _180dDailyInterestRate: string; + minLimit: string; + maxLimit: string; + vipLevel: number; } ⋮---- -export interface DailyFuturesBalance { - asset: string; - marginBalance: numberInString; - walletBalance: numberInString; +export interface GetCollateralAssetDataParams { + collateralCoin?: string; + vipLevel?: number; } ⋮---- -export interface DailyFuturesPositionState { - entryPrice: numberInString; - markPrice: numberInString; - positionAmt: numberInString; - symbol: string; - unRealizedProfit: numberInString; +export interface CollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; + vipLevel: number; } ⋮---- -export interface DailySpotAccountSnapshot { - data: { - balances: SpotBalance[]; - totalAssetOfBtc: numberInString; - }; - type: 'spot'; - updateTime: number; +export interface CheckCollateralRepayRateParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; } ⋮---- -export interface DailyMarginAccountSnapshot { - data: { - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - userAssets: MarginBalance[]; - }; - type: 'margin'; - updateTime: number; +export interface CheckCollateralRepayRateResponse { + loanCoin: string; + collateralCoin: string; + repayAmount: string; + rate: string; +} +⋮---- +export interface CustomizeMarginCallParams { + orderId?: number; + collateralCoin?: string; + marginCall: number; +} +⋮---- +export interface CustomizeMarginCall { + orderId: string; + collateralCoin: string; + preMarginCall: string; + afterMarginCall: string; + customizeTime: number; } ⋮---- -export interface DailyFuturesAccountSnapshot { - data: { - assets: DailyFuturesBalance[]; - position: DailyFuturesPositionState[]; - }; - type: 'futures'; - updateTime: number; +export interface BorrowFlexibleLoanParams { + loanCoin: string; + loanAmount?: number; + collateralCoin: string; + collateralAmount?: number; } ⋮---- -export type DailyAccountSnapshotElement = - | DailySpotAccountSnapshot - | DailyMarginAccountSnapshot - | DailyFuturesAccountSnapshot; +export interface BorrowFlexibleLoanResponse { + loanCoin: string; + loanAmount: string; + collateralCoin: string; + collateralAmount: string; + status: 'Succeeds' | 'Failed' | 'Processing'; +} ⋮---- -export interface DailyAccountSnapshot { - code: number; - msg: string; - snapshotVos: DailyAccountSnapshotElement[]; +export interface GetFlexibleLoanOngoingOrdersParams { + loanCoin?: string; + collateralCoin?: string; + current?: number; + limit?: number; } ⋮---- -export interface CoinNetwork { - addressRegex: string; - coin: string; - depositDesc: string; - depositEnable: boolean; - isDefault: boolean; - memoRegex: string; - minConfirm: number; - name: string; - network: string; - resetAddressStatus: boolean; - specialTips?: string; - specialWithdrawTips?: string; - unlockConfirm: number; - withdrawDesc: string; - withdrawEnable: boolean; - withdrawFee: numberInString; - withdrawMin: numberInString; - withdrawMax: numberInString; - withdrawInternalMin: numberInString; - withdrawIntegerMultiple: numberInString; - depositDust?: numberInString; - sameAddress: boolean; - estimatedArrivalTime: number; - busy: boolean; - contractAddressUrl?: string; - contractAddress?: string; +export interface FlexibleLoanOngoingOrder { + loanCoin: string; + totalDebt: string; + collateralCoin: string; + collateralAmount: string; + currentLTV: string; } ⋮---- -export interface AllCoinsInformationResponse { - coin: string; - depositAllEnable: boolean; - free: numberInString; - freeze: numberInString; - ipoable: numberInString; - ipoing: numberInString; - isLegalMoney: boolean; - locked: numberInString; - name: string; - networkList: CoinNetwork[]; - storage: numberInString; - trading: boolean; - withdrawAllEnable: boolean; - withdrawing: numberInString; +export interface GetFlexibleLoanLiquidationHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; // Default: 1, max: 1000 + limit?: number; // Default: 10, max: 100 + recvWindow?: number; } ⋮---- -export interface WithdrawParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; +current?: number; // Default: 1, max: 1000 +limit?: number; // Default: 10, max: 100 +⋮---- +export interface FlexibleLoanLiquidationHistoryRecord { + loanCoin: string; + liquidationDebt: string; + collateralCoin: string; + liquidationCollateralAmount: string; + returnCollateralAmount: string; + liquidationFee: string; + liquidationStartingPrice: string; + liquidationStartingTime: number; + status: 'Liquidated' | 'Liquidating'; } ⋮---- -export interface TransferBrokerSubAccountParams { - fromId?: string; - toId?: string; - clientTranId?: string; - asset: string; - amount: number; +export interface GetFlexibleCryptoLoanBorrowHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -export interface ConvertQuoteRequestParams { - fromAsset: string; - toAsset: string; - fromAmount?: number; - toAmount?: number; - walletType?: string; - validTime?: string; +export interface FlexibleCryptoLoanBorrowHistory { + loanCoin: string; + initialLoanAmount: string; + collateralCoin: string; + initialCollateralAmount: string; + borrowTime: number; + status: 'Succeeds' | 'Failed' | 'Processing'; } ⋮---- -export interface EnableConvertSubAccountParams { - subAccountId: string; - convert: boolean; +export interface RepayCryptoFlexibleLoanParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; + collateralReturn?: boolean; + fullRepayment?: boolean; } ⋮---- -export interface AcceptQuoteRequestParams { - quoteId: string; +export interface RepayCryptoFlexibleLoanResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; } ⋮---- -export interface GetOrderStatusParams { - orderId?: string; - quoteId?: string; +export interface RepayCryptoLoanFlexibleWithCollateralParams { + loanCoin: string; + collateralCoin: string; + repayAmount: number; // Amount of loan to repay + fullRepayment?: boolean; // Default: FALSE } ⋮---- -export interface GetConvertTradeHistoryParams { - startTime: number; +repayAmount: number; // Amount of loan to repay +fullRepayment?: boolean; // Default: FALSE +⋮---- +export interface RepayCryptoLoanFlexibleWithCollateralResponse { + loanCoin: string; + collateralCoin: string; + remainingDebt: string; + remainingCollateral: string; + fullRepayment: boolean; + currentLTV: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; +} +export interface GetFlexibleCryptoLoanRepaymentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; endTime?: number; - limit?: string; + current?: number; + limit?: number; } ⋮---- -export interface TransferBrokerSubAccount { - txnId: numberInString; +export interface FlexibleCryptoLoanRepaymentHistory { + loanCoin: string; + repayAmount: string; + collateralCoin: string; + collateralReturn: string; + repayStatus: 'Repaid' | 'Repaying' | 'Failed'; + repayTime: number; } ⋮---- -export enum EnumDepositStatus { - Pending = 0, - CreditedButCannotWithdraw = 6, - WrongDeposit = 7, - WaitingUserConfirm = 8, - Success = 1, - Rejected = 2, +export interface AdjustFlexibleCryptoLoanLTVParams { + loanCoin: string; + collateralCoin: string; + adjustmentAmount: number; + direction: 'ADDITIONAL' | 'REDUCED'; } ⋮---- -export type DepositStatusCode = `${EnumDepositStatus}`; +export interface AdjustFlexibleCryptoLoanLTVResponse { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + adjustmentAmount: string; + currentLTV: string; +} ⋮---- -export interface DepositHistoryParams { - coin?: string; // Optional: Filter by coin - status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) - offset?: number; // Optional: Pagination offset (Default: 0) - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - txId?: string; // Optional: Filter by transaction ID - includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +export interface GetFlexibleLoanLTVAdjustmentHistoryParams { + loanCoin?: string; + collateralCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -coin?: string; // Optional: Filter by coin -status?: DepositStatusCode; // Optional: Filter by status (0:pending, 6:credited but cannot withdraw, 7:Wrong Deposit, 8:Waiting User confirm, 1:success, 2:rejected) -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) -offset?: number; // Optional: Pagination offset (Default: 0) -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -txId?: string; // Optional: Filter by transaction ID -includeSource?: boolean; // Optional: Return sourceAddress field when set to true (Default: false) +export interface FlexibleLoanLTVAdjustmentHistory { + loanCoin: string; + collateralCoin: string; + direction: 'ADDITIONAL' | 'REDUCED'; + collateralAmount: string; + preLTV: string; + afterLTV: string; + adjustTime: number; +} +⋮---- +export interface FlexibleLoanAssetData { + loanCoin: string; + flexibleInterestRate: string; + flexibleMinLimit: string; + flexibleMaxLimit: string; +} ⋮---- -export interface DepositHistory { - amount: numberInString; - coin: string; - network: string; - status: number; - address: string; - addressTag: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; +export interface FlexibleLoanCollateralAssetData { + collateralCoin: string; + initialLTV: string; + marginCallLTV: string; + liquidationLTV: string; + maxLimit: string; } ⋮---- -export enum EnumWithdrawStatus { - EmailSent = 0, - Cancelled = 1, - AwaitingApproval = 2, - Rejected = 3, - Processing = 4, - Failure = 5, - Completed = 6, +export interface GetFuturesLeadTraderStatusResponse { + code: string; + message: string; + data: { + isLeadTrader: boolean; + time: number; + }; + success: boolean; } ⋮---- -export type WithdrawStatusCode = `${EnumWithdrawStatus}`; +export interface GetFuturesLeadTradingSymbolWhitelistResponse { + code: string; + message: string; + data: { + symbol: string; + baseAsset: string; + quoteAsset: string; + }[]; +} ⋮---- -export interface WithdrawHistoryParams { - coin?: string; // Optional: Filter by coin - withdrawOrderId?: string; // Optional: Filter by withdraw order ID - status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) - offset?: number; // Optional: Pagination offset - limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) - idList?: string; // Optional: Comma-separated list of withdrawal IDs - startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) - endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +export interface GetPayTradeHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; } ⋮---- -coin?: string; // Optional: Filter by coin -withdrawOrderId?: string; // Optional: Filter by withdraw order ID -status?: WithdrawStatusCode; // Optional: Filter by status (0:Email Sent, 2:Awaiting Approval, 3:Rejected, 4:Processing, 6:Completed) -offset?: number; // Optional: Pagination offset -limit?: number; // Optional: Number of records to return (Default: 1000, Max: 1000) -idList?: string; // Optional: Comma-separated list of withdrawal IDs -startTime?: number; // Optional: Start time in milliseconds (Default: 90 days from current timestamp) -endTime?: number; // Optional: End time in milliseconds (Default: present timestamp) +export interface GetAllConvertPairsParams { + fromAsset?: string; + toAsset?: string; +} ⋮---- -export enum EnumWithdrawTransferType { - External = 0, - Interal = 1, +export interface SubmitConvertLimitOrderParams { + baseAsset: string; + quoteAsset: string; + limitPrice: number; + baseAmount?: number; + quoteAmount?: number; + side: 'BUY' | 'SELL'; + walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; + expiredType: '1_D' | '3_D' | '7_D' | '30_D'; } ⋮---- -export type WithdrawTransferType = `${EnumWithdrawTransferType}`; +export interface ConvertLimitOpenOrder { + quoteId: string; + orderId: number; + orderStatus: string; + fromAsset: string; + fromAmount: string; + toAsset: string; + toAmount: string; + ratio: string; + inverseRatio: string; + createTime: number; + expiredTimestamp: number; +} ⋮---- -export interface WithdrawHistory { - address: string; - amount: numberInString; - applyTime: string; - coin: string; - id: string; - withdrawOrderId: string; - network: string; - transferType: WithdrawTransferType; - status: number; - transactionFee: numberInString; - txId: string; +export interface GetSpotRebateHistoryRecordsParams { + startTime?: number; + endTime?: number; + page?: number; } ⋮---- -export interface DepositAddressParams { - coin: string; - network?: string; - amount?: number; +export interface SpotRebateHistoryRecord { + asset: string; + type: number; + amount: string; + updateTime: number; } ⋮---- -export interface DepositAddressResponse { - address: string; - coin: string; - tag: string; - url: string; +export interface GetSpotRebateHistoryRecordsResponse { + status: string; + type: string; + code: string; + data: { + page: number; + totalRecords: number; + totalPageNum: number; + data: SpotRebateHistoryRecord[]; + }; } ⋮---- -export interface ConvertDustParams { - asset: string[]; - accountType?: 'SPOT' | 'MARGIN'; +export interface GetNftTransactionHistoryParams { + orderType: number; + startTime?: number; + endTime?: number; + limit?: number; + page?: number; } ⋮---- -export type DustConvertAccountType = 'SPOT' | 'MARGIN'; +export interface NftToken { + network: string; + tokenId: string; + contractAddress: string; +} ⋮---- -export interface DustConvertParams { - asset: string[]; - accountType?: DustConvertAccountType; - clientId?: string; - targetAsset?: string; - thirdPartyClientId?: string; - dustQuotaAssetToTargetAssetPrice?: numberInString; +export interface NftTransaction { + orderNo: string; + tokens: NftToken[]; + tradeTime: number; + tradeAmount: string; + tradeCurrency: string; } ⋮---- -export interface DustConvertibleAssetsParams { - targetAsset: string; - accountType?: DustConvertAccountType; - dustQuotaAssetToTargetAssetPrice?: numberInString; +export interface GetNftDepositHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; } ⋮---- -export interface DustConvertibleAssetDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - exchange: numberInString; - toQuotaAssetAmount: numberInString; - toTargetAssetAmount: numberInString; - toTargetAssetOffExchange: numberInString; +export interface NftDeposit { + network: string; + txID: string | null; + contractAdrress: string; + tokenId: string; + timestamp: number; } ⋮---- -export interface DustConvertibleAssetsResponse { - dribbletPercentage: numberInString; - totalTransferQuotaAssetAmount: numberInString; - totalTransferTargetAssetAmount: numberInString; - dribbletBase: numberInString; - details: DustConvertibleAssetDetail[]; +export interface GetNftWithdrawHistoryParams { + startTime?: number; + endTime?: number; + limit?: number; + page?: number; } ⋮---- -export interface DustInfoDetail { - asset: string; - assetFullName: string; - amountFree: numberInString; - toBTC: numberInString; - toBNB: numberInString; - toBNBOffExchange: numberInString; - exchange: numberInString; +export interface NftWithdraw { + network: string; + txID: string; + contractAdrress: string; + tokenId: string; + timestamp: number; + fee: number; + feeAsset: string; } ⋮---- -export interface DustInfo { - details: DustInfoDetail[]; - totalTransferBtc: numberInString; - totalTransferBNB: numberInString; - dribbletPercentage: numberInString; +export interface GetNftAssetParams { + limit?: number; + page?: number; } ⋮---- -export interface DustConversionResult { - amount: numberInString; - fromAsset: string; - operateTime: number; - serviceChargeAmount: numberInString; - tranId: number; - transferedAmount: numberInString; +export interface NftAsset { + network: string; + contractAddress: string; + tokenId: string; } ⋮---- -export interface DustConversion { - totalServiceCharge: numberInString; - totalTransfered: numberInString; - transferResult: DustConversionResult[]; +export interface CreateGiftCardParams { + token: string; + amount: number; } ⋮---- -export interface UserAssetDribbletDetail { - transId: number; - serviceChargeAmount: numberInString; - amount: numberInString; - operateTime: number; - transferedAmount: numberInString; - fromAsset: string; +export interface CreateDualTokenGiftCardParams { + baseToken: string; + faceToken: string; + baseTokenAmount: number; + discount?: number; } ⋮---- -export interface UserAssetDribblet { - operateTime: number; - totalTransferedAmount: numberInString; - totalServiceChargeAmount: numberInString; - transId: number; - userAssetDribbletDetails: UserAssetDribbletDetail[]; +export interface RedeemGiftCardParams { + code: string; + externalUid?: string; } ⋮---- -export interface DustLog { - total: number; - userAssetDribblets: UserAssetDribblet[]; +export interface SimpleEarnProductListParams { + asset?: string; + current?: number; + size?: number; } ⋮---- -export enum EnumUniversalTransferType { - SpotToUSDM = 'MAIN_UMFUTURE', - SpotToCOINM = 'MAIN_CMFUTURE', - SpotToMargin = 'MAIN_MARGIN', - SpotToFunding = 'MAIN_FUNDING', - SpotToOptions = 'MAIN_OPTION', - FundingToSpot = 'FUNDING_MAIN', - FundingToUSDM = 'FUNDING_UMFUTURE', - FundingToCOINM = 'FUNDING_CMFUTURE', - FundingToMargin = 'FUNDING_MARGIN', - FundingToOptions = 'FUNDING_OPTION', - USDMToSpot = 'UMFUTURE_MAIN', - USDMToFunding = 'UMFUTURE_FUNDING', - USDMToMargin = 'UMFUTURE_MARGIN', - USDMToOptions = 'UMFUTURE_OPTION', - COINMToSpot = 'CMFUTURE_MAIN', - COINMToFunding = 'CMFUTURE_FUNDING', - COINMToMargin = 'CMFUTURE_MARGIN', - MarginToSpot = 'MARGIN_MAIN', - MarginToUSDM = 'MARGIN_UMFUTURE', - MarginToCOINM = 'MARGIN_CMFUTURE', - MarginToIsolatedMargin = 'MARGIN_ISOLATEDMARGIN ', - MarginToFunding = 'MARGIN_FUNDING', - MarginToOptions = 'MARGIN_OPTION', - IsolatedMarginToMargin = 'ISOLATEDMARGIN_MARGIN', - IsolatedMarginToIsolatedMargin = 'ISOLATEDMARGIN_ISOLATEDMARGIN', - OptionsToSpot = 'OPTION_MAIN', - OptionsToUSDM = 'OPTION_UMFUTURE', - OptionsToFunding = 'OPTION_FUNDING', - OptionsToMargin = 'OPTION_MARGIN', +export interface SimpleEarnFlexibleProduct { + asset: string; + latestAnnualInterestRate: string; + tierAnnualPercentageRate: Record; + airDropPercentageRate: string; + canPurchase: boolean; + canRedeem: boolean; + isSoldOut: boolean; + hot: boolean; + minPurchaseAmount: string; + productId: string; + subscriptionStartTime: number; + status: string; } ⋮---- -export type UniversalTransferType = `${EnumUniversalTransferType}`; +export interface SimpleEarnLockedProduct { + projectId: string; + detail: { + asset: string; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: string; + subscriptionStartTime: number; + extraRewardAsset: string; + extraRewardAPR: string; + boostRewardAsset: string; + boostApr: string; + boostEndTime: string; + }; + quota: { + totalPersonalQuota: string; + minimum: string; + }; +} ⋮---- -export interface UniversalTransferParams { - type: UniversalTransferType; - asset: string; +export interface SimpleEarnSubscribeProductParams { + productId: string; amount: number; - fromSymbol: string; - toSymbol: string; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; } ⋮---- -export interface UniversalTransferHistoryParams { - type: UniversalTransferType; - startTime?: number; - endTime?: number; - current?: number; - size?: number; +export interface SimpleEarnSubscribeFlexibleProductResponse { + purchaseId: string; + success: boolean; } ⋮---- -export interface ExchangeInfoParams { - symbol?: string; - symbols?: string[]; - permissions?: string | string[]; - showPermissionSets?: boolean; - symbolStatus?: string; +export interface SimpleEarnSubscribeLockedProductResponse { + purchaseId: string; + positionId: string; + success: boolean; } ⋮---- -type SpotPegPriceType = 'PRIMARY_PEG' | 'MARKET_PEG'; -type SpotPegOffsetType = 'PRICE_LEVEL'; -⋮---- -export interface NewSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> { - symbol: string; - side: OrderSide; - type: T; - timeInForce?: OrderTimeInForce; - quantity?: number; - quoteOrderQty?: number; - price?: number; - newClientOrderId?: string; - strategyId?: number; - strategyType?: number; - stopPrice?: number; - trailingDelta?: number; - icebergQty?: number; - newOrderRespType?: RT; - selfTradePreventionMode?: SelfTradePreventionMode; - pegPriceType?: SpotPegPriceType; - pegOffsetValue?: number; - pegOffsetType?: SpotPegOffsetType; - isIsolated?: StringBoolean; - sideEffectType?: SideEffects; - autoRepayAtCancel?: StringBoolean; +export interface SimpleEarnRedeemFlexibleProductParams { + productId: string; + redeemAll?: boolean; + amount?: number; + destAccount?: 'SPOT' | 'FUND'; } ⋮---- -export type CancelRestrictions = 'ONLY_NEW' | 'ONLY_PARTIALLY_FILLED'; -export type CancelReplaceMode = 'STOP_ON_FAILURE' | 'ALLOW_FAILURE'; +export interface SimpleEarnRedeemResponse { + success: boolean; + redeemId: string; +} ⋮---- -export interface ReplaceSpotOrderParams< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends NewSpotOrderParams { - cancelReplaceMode: CancelReplaceMode; - cancelNewClientOrderId?: string; - cancelOrigClientOrderId?: string; - cancelOrderId?: number; - cancelRestrictions?: CancelRestrictions; +export interface SimpleEarnFlexibleProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; } ⋮---- -export interface GetOCOParams { - symbol?: string; - orderListId?: number; - origClientOrderId?: string; +export interface SimpleEarnLockedProductPositionParams { + asset?: string; + productId?: string; + current?: number; + size?: number; + positionId?: string; } ⋮---- -export interface NewSpotSOROrderParams { - symbol: string; - side: OrderSide; - type: OrderType; - timeInForce?: OrderTimeInForce; - quantity: number; - price?: number; - newClientOrderId?: string; - strategyId?: number; - strategyType?: number; - icebergQty?: number; - newOrderRespType?: OrderResponseType; - selfTradePreventionMode?: SelfTradePreventionMode; +export interface SimpleEarnLockedProductPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + isRenewable: boolean; + isAutoRenew: boolean; + redeemDate: string; + boostRewardAsset: string; + boostApr: string; + totalBoostRewardAmt: string; } ⋮---- -export type APILockTriggerCondition = 'GCR' | 'IFER' | 'UFR'; +export interface SimpleEarnAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedinBTC: string; + totalLockedinUSDT: string; +} ⋮---- -export interface APITriggerConditionSymbolStatus { - i: APILockTriggerCondition; - c: number; - v: number; - t: number; +export interface GetSubAccountDepositHistoryParams { + subAccountId?: string; + coin?: string; + status?: number; + startTime?: number; + endTime?: number; + limit?: number; + offset?: number; } ⋮---- -export interface APITradingStatus { - data: { - isLocked: boolean; - plannedRecoverTime: number; - triggerCondition: Record; - indicators: Record; - updateTime: number; - }; +export interface SubAccountDeposit { + depositId: number; + subAccountId: string; + address: string; + addressTag: string; + amount: string; + coin: string; + insertTime: number; + transferType: number; + network: string; + status: number; + txId: string; + sourceAddress: string; + confirmTimes: string; + selfReturnStatus: number; } ⋮---- -export interface APIPermissions { - ipRestrict: boolean; - createTime: number; - enableReading: boolean; - enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals - enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly - enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed - enableFutures: boolean; // API Key created before your futures account opened does not support futures API service - permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization - enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading - enableSpotAndMarginTrading: boolean; // Spot and margin trading - tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission - enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading - enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading - enablePortfolioMarginTrading: true; +// Request interface for querying sub account spot asset info +export interface QuerySubAccountSpotMarginAssetInfoParams { + subAccountId?: string; + page?: number; + size?: number; } ⋮---- -enableWithdrawals: boolean; // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals -enableInternalTransfer: boolean; // This option authorizes this key to transfer funds between your master account and your sub account instantly -enableMargin: boolean; // This option can be adjusted after the Cross Margin account transfer is completed -enableFutures: boolean; // API Key created before your futures account opened does not support futures API service -permitsUniversalTransfer: boolean; // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization -enableVanillaOptions: boolean; // Authorizes this key to Vanilla options trading -enableSpotAndMarginTrading: boolean; // Spot and margin trading -tradingAuthorityExpirationTime: number; // Expiration time for spot and margin trading permission -enableFixApiTrade: boolean; // Authorizes this key to use FIX API trading -enableFixReadOnly: boolean; // Authorizes this key to use FIX API reading +export interface SubaccountBrokerSpotAsset { + subAccountId: string; + totalBalanceOfBtc: string; +} ⋮---- -export interface AssetDetail { - minWithdrawAmount: numberInString; - depositStatus: boolean; - withdrawFee: number; - withdrawStatus: boolean; - depositTip?: string; +export interface SubAccountBrokerMarginAsset { + marginEnable: boolean; + subAccountId: string; + totalAssetOfBtc?: string; + totalLiabilityOfBtc?: string; + totalNetAssetOfBtc?: string; + marginLevel?: string; } ⋮---- -export interface SymbolTradeFee { - symbol: string; - makerCommission: numberInString; - takerCommission: numberInString; +// Request interface for querying sub account futures asset info +export interface QuerySubAccountFuturesAssetInfoParams { + subAccountId?: string; + futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures + page?: number; + size?: number; } ⋮---- -export interface SymbolExchangeInfo { - symbol: string; - status: string; - baseAsset: string; - baseAssetPrecision: number; - quoteAsset: string; - quotePrecision: number; - quoteAssetPrecision: number; - baseCommissionPrecision: number; - quoteCommissionPrecision: number; - orderTypes: OrderType[]; - icebergAllowed: boolean; - ocoAllowed: boolean; - opoAllowed: boolean; - quoteOrderQtyMarketAllowed: boolean; - allowTrailingStop: boolean; - cancelReplaceAllowed: boolean; - isSpotTradingAllowed: boolean; - isMarginTradingAllowed: boolean; - filters: SymbolFilter[]; - permissions: ('SPOT' | 'MARGIN')[]; - defaultSelfTradePreventionMode: SelfTradePreventionMode; - allowedSelfTradePreventionModes: SelfTradePreventionMode[]; +futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures +⋮---- +// Response interface for querying sub account futures asset info (USD Margined Futures) +export interface UsdtMarginedFuturesResponse { + subAccountId: string; + totalInitialMargin: string; + totalMaintenanceMargin: string; + totalWalletBalance: string; + totalUnrealizedProfit: string; + totalMarginBalance: string; + totalPositionInitialMargin: string; + totalOpenOrderInitialMargin: string; + futuresEnable: boolean; + asset: string; } ⋮---- -export interface ExchangeInfo { - timezone: string; - serverTime: number; - rateLimits: RateLimiter[]; - exchangeFilters: ExchangeFilter[]; - symbols: SymbolExchangeInfo[]; +// Response interface for querying sub account futures asset info (COIN Margined Futures) +export interface CoinMarginedFuturesResponse { + subAccountId: string; + totalWalletBalanceOfUsdt: string; + totalUnrealizedProfitOfUsdt: string; + totalMarginBalanceOfUsdt: string; + futuresEnable: boolean; } ⋮---- -export interface OrderBookResponse { - lastUpdateId: number; - bids: OrderBookRow[]; - asks: OrderBookRow[]; +// Combined response interface for querying sub account futures asset info +export interface BrokerFuturesSubAccountAssets { + data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; + timestamp: number; } ⋮---- -export interface RawTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; +export interface BrokerUniversalTransfer { + toId: string; + asset: string; + qty: string; time: number; - isBuyerMaker: boolean; - isBestMatch: boolean; + status: string; + txnId: string; + clientTranId: string; + fromAccountType: string; + toAccountType: string; } ⋮---- -export interface BlockTrade { - id: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - time: number; - isBuyerMaker: boolean; +// Request interface for changing sub account commission +export interface ChangeSubAccountCommissionParams { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission?: number; + marginTakerCommission?: number; } ⋮---- -export interface HistoricalBlockTradesParams { +// Response interface for changing sub account commission +export interface ChangeSubAccountCommissionResponse { + subAccountId: string; + makerCommission: number; + takerCommission: number; + marginMakerCommission: number; + marginTakerCommission: number; +} +⋮---- +// Request interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionParams { + subAccountId: string; symbol: string; - fromId: number; - limit?: number; + makerAdjustment: number; + takerAdjustment: number; } ⋮---- -export interface RawAccountTrade { +// Response interface for changing sub account USDT-Ⓜ futures commission adjustment +export interface ChangeSubAccountFuturesCommissionResponse { + subAccountId: string; symbol: string; - id: number; - orderId: number; - orderListId: number; - price: numberInString; - qty: numberInString; - quoteQty: numberInString; - commission: numberInString; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isBestMatch: boolean; + makerAdjustment: number; + takerAdjustment: number; + makerCommission: number; + takerCommission: number; } ⋮---- -export interface AggregateTrade { - a: number; - p: numberInString; - q: numberInString; - f: number; - l: number; - T: number; - m: boolean; - M: boolean; +// Request interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface QuerySubAccountFuturesCommissionParams { + subAccountId: string; + symbol?: string; } ⋮---- -export interface CurrentAvgPrice { - mins: number; - price: numberInString; - closeTime: number; +// Response interface for querying sub account USDT-Ⓜ futures commission adjustment +export interface BrokerSubAccountFuturesCommission { + subAccountId: string; + symbol: string; + makerCommission: number; + takerCommission: number; } ⋮---- -/** Spot PRICE_RANGE execution rule (GET /api/v3/executionRules). */ -export interface SpotPriceRangeExecutionRule { - ruleType: 'PRICE_RANGE'; - bidLimitMultUp: numberInString; - bidLimitMultDown: numberInString; - askLimitMultUp: numberInString; - askLimitMultDown: numberInString; +export interface ChangeSubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair: string; + makerAdjustment: number; + takerAdjustment: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface SpotSymbolExecutionRules { - symbol: string; - rules: SpotPriceRangeExecutionRule[]; +export interface QuerySubAccountCoinFuturesCommissionParams { + subAccountId: string; + pair?: string; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface SpotExecutionRulesResponse { - symbolRules: SpotSymbolExecutionRules[]; +// Response interface for querying sub account COIN-Ⓜ futures commission adjustment +export interface BrokerSubAccountCoinFuturesCommission { + subAccountId: string; + pair: string; + makerCommission: number; + takerCommission: number; } ⋮---- -/** GET /api/v3/executionRules — only one of symbol, symbols, or symbolStatus per request. */ -export interface SpotExecutionRulesParams { - symbol?: string; - symbols?: string[]; - symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +export interface QueryBrokerSpotCommissionRebateParams { + subAccountId?: string; + startTime?: number; + endTime?: number; + page?: number; + size?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -/** Successful GET /api/v3/referencePrice (referencePrice null = not currently set). */ -export interface SpotReferencePriceResponse { +// Response interface for querying spot commission rebate recent record +export interface BrokerCommissionRebate { + subaccountId: string; + income: string; + asset: string; symbol: string; - referencePrice: numberInString | null; - timestamp: number; + tradeId: number; + time: number; + status: number; } ⋮---- -/** GET /api/v3/referencePrice or /referencePrice/calculation when no reference price has ever been set (code -2043). */ -export interface SpotReferencePriceNeverSetError { - code: -2043; - msg: string; +export interface QueryBrokerFuturesCommissionRebateParams { + futuresType: number; // 1: USDT Futures, 2: Coin Futures + startTime: number; + endTime: number; + page?: number; + size?: number; + filterResult?: boolean; + recvWindow?: number; + timestamp: number; } ⋮---- -export type SpotReferencePriceResult = - | SpotReferencePriceResponse - | SpotReferencePriceNeverSetError; +futuresType: number; // 1: USDT Futures, 2: Coin Futures ⋮---- -/** Reference price is computed as an arithmetic mean in the matching engine. */ -export interface SpotReferencePriceCalculationArithmeticMean { +export interface SubmitMarginOTOOrderParams { symbol: string; - calculationType: 'ARITHMETIC_MEAN'; - bucketCount: number; - bucketWidthMs: number; + isIsolated?: 'TRUE' | 'FALSE'; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + sideEffectType?: SideEffects; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + autoRepayAtCancel?: boolean; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: number; + workingQuantity: number; + workingIcebergQty?: number; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingType: OrderType; + pendingSide: 'BUY' | 'SELL'; + pendingClientOrderId?: string; + pendingPrice?: number; + pendingStopPrice?: number; + pendingTrailingDelta?: number; + pendingQuantity: number; + pendingIcebergQty?: number; + pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; } ⋮---- -/** Reference price is computed outside the matching engine. */ -export interface SpotReferencePriceCalculationExternal { +export interface MarginOTOOrder { + orderListId: number; + contingencyType: string; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; symbol: string; - calculationType: 'EXTERNAL'; - externalCalculationId: number; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: string; + timeInForce: string; + type: string; + side: string; + selfTradePreventionMode: string; + }[]; } ⋮---- -export type SpotReferencePriceCalculationResponse = - | SpotReferencePriceCalculationArithmeticMean - | SpotReferencePriceCalculationExternal - | SpotReferencePriceNeverSetError; -⋮---- -export interface DailyChangeStatistic { +export interface SubmitMarginOTOCOOrderParams { symbol: string; - priceChange: numberInString; - priceChangePercent: numberInString; - weightedAvgPrice: numberInString; - prevClosePrice: numberInString; - lastPrice: numberInString; - lastQty: numberInString; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; - openPrice: numberInString; - highPrice: numberInString; - lowPrice: numberInString; - volume: numberInString; - quoteVolume: numberInString; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; + isIsolated?: 'TRUE' | 'FALSE'; + sideEffectType?: SideEffects; + autoRepayAtCancel?: boolean; + listClientOrderId?: string; + newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; + selfTradePreventionMode?: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + workingType: 'LIMIT' | 'LIMIT_MAKER'; + workingSide: 'BUY' | 'SELL'; + workingClientOrderId?: string; + workingPrice: string; + workingQuantity: string; + workingIcebergQty?: string; + workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingSide: 'BUY' | 'SELL'; + pendingQuantity: string; + pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingAboveClientOrderId?: string; + pendingAbovePrice?: string; + pendingAboveStopPrice?: string; + pendingAboveTrailingDelta?: string; + pendingAboveIcebergQty?: string; + pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; + pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; + pendingBelowClientOrderId?: string; + pendingBelowPrice?: string; + pendingBelowStopPrice?: string; + pendingBelowTrailingDelta?: string; + pendingBelowIcebergQty?: string; + pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; } ⋮---- -export interface SymbolOrderBookTicker { - symbol: string; - bidPrice: numberInString; - bidQty: numberInString; - askPrice: numberInString; - askQty: numberInString; +export interface QueryMarginOpenOTOOrderListsParams { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; } ⋮---- -export interface OrderResponseACK { +export interface MarginOpenOTOOrderList { + orderListId: number; + contingencyType: 'OTO' | 'OTOCO'; + listStatusType: string; + listOrderStatus: string; + listClientOrderId: string; + transactionTime: number; symbol: string; - orderId: number; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; +} +⋮---- +export interface MarginOTOCOOrder { orderListId: number; - clientOrderId: string; - transactTime: number; + contingencyType: 'OTO' | 'OTOCO'; + listStatusType: 'EXEC_STARTED'; + listOrderStatus: 'EXECUTING'; + listClientOrderId: string; + transactionTime: number; + symbol: string; + isIsolated: boolean; + orders: { + symbol: string; + orderId: number; + clientOrderId: string; + }[]; + orderReports: { + symbol: string; + orderId: number; + orderListId: number; + clientOrderId: string; + transactTime: number; + price: string; + origQty: string; + executedQty: string; + cummulativeQuoteQty: string; + status: + | 'NEW' + | 'PARTIALLY_FILLED' + | 'FILLED' + | 'CANCELED' + | 'PENDING_CANCEL' + | 'REJECTED' + | 'EXPIRED' + | 'PENDING_NEW'; + timeInForce: 'GTC' | 'IOC' | 'FOK'; + type: + | 'LIMIT' + | 'MARKET' + | 'STOP_LOSS' + | 'STOP_LOSS_LIMIT' + | 'TAKE_PROFIT' + | 'TAKE_PROFIT_LIMIT' + | 'LIMIT_MAKER'; + side: 'BUY' | 'SELL'; + stopPrice?: string; + selfTradePreventionMode: + | 'EXPIRE_TAKER' + | 'EXPIRE_MAKER' + | 'EXPIRE_BOTH' + | 'NONE'; + }[]; } ⋮---- -/** Conditional fields on POST /api/v3/order RESULT/FULL. Only present when the matching condition is met. */ -export interface SpotNewOrderConditionalFields { - icebergQty?: numberInString; - preventedMatchId?: number; - preventedQuantity?: numberInString; - stopPrice?: numberInString; - strategyId?: number; - strategyType?: number; - trailingDelta?: number; - trailingTime?: number; - pegPriceType?: SpotPegPriceType; - pegOffsetType?: SpotPegOffsetType; - pegOffsetValue?: number; - peggedPrice?: numberInString; +export interface CreateSpecialLowLatencyKeyParams { + apiName: string; + symbol?: string; + ip?: string; + publicKey?: string; } ⋮---- -export interface OrderResponseResult extends SpotNewOrderConditionalFields { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; +export interface SpecialLowLatencyKeyResponse { + apiKey: string; + secretKey: string | null; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; } ⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +export interface SpecialLowLatencyKeyInfo { + apiName: string; + apiKey: string; + ip: string; + type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; +} ⋮---- -export interface OrderFill { - price: numberInString; - qty: numberInString; - commission: numberInString | null; - commissionAsset: string | null; - tradeId: number; +export interface MarginLiquidationLoan { + asset: string; + amount: string; + repaidAmount: string; + remainingAmount: string; } ⋮---- -export interface OrderResponseFull extends SpotNewOrderConditionalFields { - symbol: string; - orderId: number; - orderListId?: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - origQuoteOrderQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - marginBuyBorrowAmount?: number; - marginBuyBorrowAsset?: string; - isIsolated?: boolean; - workingTime: number; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ - expiryReason?: string; - fills: OrderFill[]; +export interface RepayMarginLiquidationLoanParams { + asset: string; + amount: string; } ⋮---- -/** Present with newOrderRespType RESULT or FULL when the order has an expiry reason. */ +export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; ⋮---- -export type OrderResponse = - | OrderResponseACK - | OrderResponseResult - | OrderResponseFull; +export interface MarginLiquidationLoanRepayResponse { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; +} ⋮---- -export type OrderResponseTypeFor< - RT extends OrderResponseType | undefined = undefined, - T extends OrderType | undefined = undefined, -> = RT extends 'ACK' - ? OrderResponseACK - : RT extends 'RESULT' - ? OrderResponseResult - : RT extends 'FULL' - ? OrderResponseFull - : T extends 'MARKET' | 'LIMIT' - ? OrderResponseFull - : OrderResponseACK; +export interface GetMarginLiquidationLoanRepayHistoryParams { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +} ⋮---- -export interface OrderListOrder { - symbol: string; - orderId: number; - clientOrderId: string; - /** Present only for expired orders. */ - expiryReason?: string; +export interface MarginLiquidationLoanRepayHistoryRecord { + repayId: number; + asset: string; + amount: string; + status: MarginLiquidationLoanRepayStatus; + createTime: number; } ⋮---- -/** Present only for expired orders. */ +export interface MarginLiquidationLoanRepayHistoryResponse { + total: number; + rows: MarginLiquidationLoanRepayHistoryRecord[]; +} ⋮---- -export interface OrderListResponse { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; - orderReports: [OrderResponseTypeFor, OrderResponseTypeFor]; +export interface SolStakingAccount { + bnsolAmount: string; // Amount in bNSOL + holdingInSOL: string; // Holding in SOL + thirtyDaysProfitInSOL: string; // 30 days profit in SOL } ⋮---- -export interface OrderList { - orderListId: number; - contingencyType: 'OCO'; - listStatusType: OCOStatus; - listOrderStatus: OCOOrderStatus; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: [OrderListOrder, OrderListOrder]; +bnsolAmount: string; // Amount in bNSOL +holdingInSOL: string; // Holding in SOL +thirtyDaysProfitInSOL: string; // 30 days profit in SOL +⋮---- +export interface SolStakingQuota { + leftStakingPersonalQuota: string; // Remaining personal staking quota + leftRedemptionPersonalQuota: string; // Remaining personal redemption quota + minStakeAmount: string; // Minimum stake amount + minRedeemAmount: string; // Minimum redeem amount + redeemPeriod: number; // Redemption period in days + stakeable: boolean; // Whether staking is possible + redeemable: boolean; // Whether redemption is possible + soldOut: boolean; // Whether the staking is sold out + commissionFee: string; // Commission fee + nextEpochTime: number; // Time for the next epoch + calculating: boolean; // Whether calculations are ongoing } -export interface SOROrderFill { - matchType: string; - price: numberInString; - qty: numberInString; - commission: numberInString; - commissionAsset: string; - tradeId: number; - allocId: number; +⋮---- +leftStakingPersonalQuota: string; // Remaining personal staking quota +leftRedemptionPersonalQuota: string; // Remaining personal redemption quota +minStakeAmount: string; // Minimum stake amount +minRedeemAmount: string; // Minimum redeem amount +redeemPeriod: number; // Redemption period in days +stakeable: boolean; // Whether staking is possible +redeemable: boolean; // Whether redemption is possible +soldOut: boolean; // Whether the staking is sold out +commissionFee: string; // Commission fee +nextEpochTime: number; // Time for the next epoch +calculating: boolean; // Whether calculations are ongoing +⋮---- +export interface SubscribeSolStakingResponse { + success: boolean; // Indicates if the subscription was successful + bnsolAmount: string; // Amount in bNSOL received + exchangeRate: string; // SOL amount per 1 BNSOL } ⋮---- -export type SOROrderResponseFull = OrderResponseFull & { - workingTime: number; - fills: SOROrderFill[]; - workingFloor: string; - selfTradePreventionMode: string; - usedSor: true; -}; +success: boolean; // Indicates if the subscription was successful +bnsolAmount: string; // Amount in bNSOL received +exchangeRate: string; // SOL amount per 1 BNSOL ⋮---- -export interface SORTestOrderResponse { - standardCommissionForOrder: { - //Standard commission rates on trades from the order. - maker: numberInString; - taker: numberInString; - }; - taxCommissionForOrder: { - //Tax commission rates for trades from the order. - maker: numberInString; - taker: numberInString; - }; - discount: { - //Discount on standard commissions when paying in BNB. - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ - discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. Staff later confirmed this is a multiplier: 0.75 means pay 75% of standard. The FAQ 0.25 example is fictional. - }; +export interface RedeemSolResponse { + success: boolean; // Indicates if the redemption was successful + solAmount: string; // Amount in SOL received + exchangeRate: string; // SOL amount per 1 BNSOL + arrivalTime: number; // Time of arrival for the redeemed SOL } ⋮---- -//Standard commission rates on trades from the order. +success: boolean; // Indicates if the redemption was successful +solAmount: string; // Amount in SOL received +exchangeRate: string; // SOL amount per 1 BNSOL +arrivalTime: number; // Time of arrival for the redeemed SOL ⋮---- -//Tax commission rates for trades from the order. +export interface GetSolStakingHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory +} ⋮---- -//Discount on standard commissions when paying in BNB. +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset`. - * `0.75` means pay 75% of the standard commission. The FAQ example `0.25` is fictional. - */ -discount: numberInString; //Standard commission is reduced by this rate when paying commission in BNB. Staff later confirmed this is a multiplier: 0.75 means pay 75% of standard. The FAQ 0.25 example is fictional. +export interface SolStakingHistoryRecord { + time: number; // Time of the staking event + asset: string; // Asset involved, e.g., SOL + amount: string; // Amount staked + distributeAsset: string; // Asset distributed, e.g., BNSOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +} ⋮---- -export interface CancelSpotOrderResult { - symbol: string; - origClientOrderId: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - selfTradePreventionMode: SelfTradePreventionMode; +time: number; // Time of the staking event +asset: string; // Asset involved, e.g., SOL +amount: string; // Amount staked +distributeAsset: string; // Asset distributed, e.g., BNSOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +⋮---- +export interface GetSolRedemptionHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -export interface CancelOrderListResult extends OrderList { - orderReports: [CancelSpotOrderResult, CancelSpotOrderResult]; +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface SolRedemptionHistoryRecord { + time: number; // Time of the redemption event + arrivalTime: number; // Time of arrival for the redeemed SOL + asset: string; // Asset redeemed, e.g., BNSOL + amount: string; // Amount redeemed + distributeAsset: string; // Asset distributed, e.g., SOL + distributeAmount: string; // Amount distributed + exchangeRate: string; // Exchange rate at the time + status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event } ⋮---- -export interface GenericReplaceSpotOrderResult { - cancelResult: 'SUCCESS' | 'FAILURE'; - newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'; - cancelResponse: C; - newOrderResponse: N; -} +time: number; // Time of the redemption event +arrivalTime: number; // Time of arrival for the redeemed SOL +asset: string; // Asset redeemed, e.g., BNSOL +amount: string; // Amount redeemed +distributeAsset: string; // Asset distributed, e.g., SOL +distributeAmount: string; // Amount distributed +exchangeRate: string; // Exchange rate at the time +status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event ⋮---- -export interface ReplaceSpotOrderCancelStopFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'NOT_ATTEMPTED'; +export interface GetBnsolRewardsHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -export interface ReplaceSpotOrderNewFailure - extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - GenericCodeMsgError - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'FAILURE'; -} +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory ⋮---- -export interface ReplaceSpotOrderCancelAllowFailure - extends GenericReplaceSpotOrderResult { - cancelResult: 'FAILURE'; - newOrderResult: 'SUCCESS'; +export interface BnsolRewardHistoryRecord { + time: number; // Time of the reward event + amountInSOL: string; // Reward amount in SOL + holding: string; // BNSOL holding balance + holdingInSOL: string; // BNSOL holding balance in SOL + annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) } ⋮---- -export interface ReplaceSpotOrderCancelAllFailure - extends GenericReplaceSpotOrderResult< - GenericCodeMsgError, - GenericCodeMsgError - > { - cancelResult: 'FAILURE'; - newOrderResult: 'FAILURE'; -} +time: number; // Time of the reward event +amountInSOL: string; // Reward amount in SOL +holding: string; // BNSOL holding balance +holdingInSOL: string; // BNSOL holding balance in SOL +annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) ⋮---- -export interface ReplaceSpotOrderResultError { - data: - | ReplaceSpotOrderCancelStopFailure - | ReplaceSpotOrderNewFailure - | ReplaceSpotOrderCancelAllowFailure - | ReplaceSpotOrderCancelAllFailure; +export interface GetBnsolRateHistoryReq { + startTime?: number; // Optional, start time in milliseconds + endTime?: number; // Optional, end time in milliseconds + current?: number; // Optional, current page, default is 1 + size?: number; // Optional, number of records per page, default is 10, max is 100 + recvWindow?: number; // Optional, cannot be greater than 60000 + timestamp: number; // Mandatory } ⋮---- -export interface ReplaceSpotOrderResultSuccess< - T extends OrderType = OrderType, - RT extends OrderResponseType | undefined = OrderResponseType, -> extends GenericReplaceSpotOrderResult< - CancelSpotOrderResult, - OrderResponseTypeFor - > { - cancelResult: 'SUCCESS'; - newOrderResult: 'SUCCESS'; +startTime?: number; // Optional, start time in milliseconds +endTime?: number; // Optional, end time in milliseconds +current?: number; // Optional, current page, default is 1 +size?: number; // Optional, number of records per page, default is 10, max is 100 +recvWindow?: number; // Optional, cannot be greater than 60000 +timestamp: number; // Mandatory +⋮---- +export interface SolBoostRewardsHistoryReq { + type: 'CLAIM' | 'DISTRIBUTE'; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SpotOrder { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - price: numberInString; - origQty: numberInString; - executedQty: numberInString; - cummulativeQuoteQty: numberInString; - status: OrderStatus; - timeInForce: OrderTimeInForce; - type: OrderType; - side: OrderSide; - stopPrice: numberInString; - icebergQty: numberInString; +export interface SolBoostRewardsHistoryRecord { time: number; - updateTime: number; - isWorking: boolean; - origQuoteOrderQty: numberInString; - selfTradePreventionMode: SelfTradePreventionMode; - /** Present only for expired orders. */ - expiryReason?: string; + token: string; + amount: string; + bnsolHolding?: string; // Only present if type is "DISTRIBUTE" + status?: string; // Only present if type is "CLAIM" } ⋮---- -/** Present only for expired orders. */ -⋮---- -export interface SpotAmendKeepPriorityResult { - transactTime: number; - executionId: number; - amendedOrder: { - symbol: string; - orderId: number; - orderListId: number; - origClientOrderId: string; - clientOrderId: string; - price: string; - qty: string; - executedQty: string; - preventedQty: string; - quoteOrderQty: string; - cumulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }; - listStatus?: { - orderListId: number; - contingencyType: string; - listOrderStatus: string; - listClientOrderId: string; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - }; -} +bnsolHolding?: string; // Only present if type is "DISTRIBUTE" +status?: string; // Only present if type is "CLAIM" ⋮---- -export interface SpotAssetBalance { - asset: string; - free: numberInString; - locked: numberInString; +export interface BnsolRateHistoryRecord { + annualPercentageRate: string; // BNSOL APR + exchangeRate: string; // SOL amount per 1 BNSOL + time: number; // Time of the rate record } ⋮---- -export interface AccountInformation { - makerCommission: number; - takerCommission: number; - buyerCommission: number; - sellerCommission: number; - commissionRates: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - canTrade: boolean; - canWithdraw: boolean; - canDeposit: boolean; - brokered: boolean; - requireSelfTradePrevention: boolean; - preventSor: boolean; - updateTime: number; - accoountType: string; - balances: SpotAssetBalance[]; - permissions: string[]; - uid: number; -} +annualPercentageRate: string; // BNSOL APR +exchangeRate: string; // SOL amount per 1 BNSOL +time: number; // Time of the rate record ⋮---- -export interface CrossMarginAccountTransferParams { +export interface RiskUnitMM { asset: string; - amount: number; - type: 1 | 2; + uniMaintainUsd: string; } ⋮---- -export interface MarginTransactionResponse { - tranId: number; +export interface PortfolioMarginProSpanAccountInfo { + uniMMR: string; + accountEquity: string; + actualEquity: string; + accountMaintMargin: string; + riskUnitMMList: RiskUnitMM[]; + marginMM: string; + otherMM: string; + accountStatus: + | 'NORMAL' + | 'MARGIN_CALL' + | 'SUPPLY_MARGIN' + | 'REDUCE_ONLY' + | 'ACTIVE_LIQUIDATION' + | 'FORCE_LIQUIDATION' + | 'BANKRUPTED'; + accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) } ⋮---- -export interface MarginAccountLoanParams { +accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +⋮---- +export interface PortfolioMarginProAccountBalance { asset: string; - isIsolated: StringBoolean; - symbol: string; - amount: number; - type: 'BORROW' | 'REPAY'; + totalWalletBalance: string; + crossMarginAsset: string; + crossMarginBorrowed: string; + crossMarginFree: string; + crossMarginInterest: string; + crossMarginLocked: string; + umWalletBalance: string; + umUnrealizedPNL: string; + cmWalletBalance: string; + cmUnrealizedPNL: string; + updateTime: number; + negativeBalance: string; + optionWalletBalance: string; // only for PM PRO SPAN + optionEquity: string; // only for PM PRO SPAN } ⋮---- -export interface QueryMarginAssetParams { - asset: string; -} +optionWalletBalance: string; // only for PM PRO SPAN +optionEquity: string; // only for PM PRO SPAN ⋮---- -export interface QueryMarginAssetResponse { - assetFullName: string; - assetName: string; - isBorrowable: boolean; - isMortgageable: boolean; - userMinBorrow: numberInString; - userMinRepay: numberInString; - /** - * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. - * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. - */ - delistTime?: number; +export interface PMProMintBFUSDParams { + fromAsset: string; // USDT only + targetAsset: string; // BFUSD only + amount: number; } ⋮---- -/** - * Unix time in milliseconds. Omitted when null, and present only once the asset is `PREPARE_DELIST`. - * Dev-confirmed on dev.binance.vision: the published example that shows seconds is wrong. - */ -⋮---- -export interface QueryCrossMarginPairParams { - symbol: string; -} +fromAsset: string; // USDT only +targetAsset: string; // BFUSD only ⋮---- -/** - * Row from `GET /sapi/v1/margin/allPairs`. - * Dev-confirmed: this response has no `delistTime`. Documentation examples that include it are wrong. - */ -export interface QueryCrossMarginPairResponse { - id: number; - symbol: string; - base: string; - quote: string; - isMarginTrade: boolean; - isBuyAllowed: boolean; - isSellAllowed: boolean; +export interface PMProMintBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; } ⋮---- -export interface QueryMarginPriceIndexResponse { - calcTime: number; - price: numberInString; - symbol: string; +export interface PMProRedeemBFUSDResponse { + fromAsset: string; + targetAsset: string; + fromAssetQty: number; + targetAssetQty: number; + rate: number; } ⋮---- -export interface QueryMarginRecordParams { +export interface PMProBankruptcyLoanRepaymentHistory { asset: string; - isolatedSymbol?: string; - txId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - archived?: boolean; + amount: string; + repayTime: number; } ⋮---- -export interface GetMarginAccountBorrowRepayRecordsParams { - asset?: string; - isolatedSymbol?: string; - txId?: number; +export interface VipLoanInterestRateHistoryParams { + coin: string; startTime?: number; endTime?: number; current?: number; - size?: number; - type: 'BORROW' | 'REPAY'; -} -⋮---- -export type LoanStatus = 'PENDING' | 'CONFIRMED' | 'FAILED'; -⋮---- -export interface MarginAccountRecord { - isolatedSymbol?: string; - asset: string; - principal: numberInString; - status: LoanStatus; - timestamp: number; - txId: number; -} -⋮---- -export interface QueryCrossMarginAccountDetailsParams { - created: boolean; - borrowEnabled: boolean; - marginLevel: numberInString; - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; - totalCollateralValueInUSDT: numberInString; - totalOpenOrderLossInUSDT: numberInString; - tradeEnabled: boolean; - transferInEnabled: boolean; - transferOutEnabled: boolean; - accountType: string; - userAssets: MarginBalance[]; + limit?: number; } ⋮---- -export interface BasicMarginAssetParams { - asset: string; - isolatedSymbol?: string; +export interface VipLoanInterestRateRecord { + coin: string; + annualizedInterestRate: string; + time: number; } ⋮---- -export interface QueryMaxBorrowResponse { - amount: numberInString; - borrowLimit: numberInString; +export interface VipLoanAccruedInterestParams { + orderId?: number; + loanCoin?: string; + startTime?: number; + endTime?: number; + current?: number; + limit?: number; } ⋮---- -export interface QueryMaxTransferOutAmountResponse { - amount: numberInString; +export interface VipLoanAccruedInterestRecord { + loanCoin: string; + principalAmount: string; + interestAmount: string; + annualInterestRate: string; + accrualTime: number; + orderId: number; } ⋮---- -export type IsolatedMarginTransfer = 'SPOT' | 'ISOLATED_MARGIN'; -⋮---- -export interface IsolatedMarginAccountTransferParams { - asset: string; - symbol: string; - transFrom: IsolatedMarginTransfer; - transTo: IsolatedMarginTransfer; +export interface WithdrawTravelRuleParams { + coin: string; + withdrawOrderId?: string; + network?: string; + address: string; + addressTag?: string; amount: number; + transactionFeeFlag?: boolean; + name?: string; + walletType?: number; + questionnaire: string; } ⋮---- -export interface IsolatedMarginAccountAsset { - asset: string; - borrowEnabled: boolean; - borrowed: numberInString; - free: numberInString; - interest: numberInString; - locked: numberInString; - netAsset: numberInString; - netAssetOfBtc: numberInString; - repayEnabled: boolean; - totalAsset: numberInString; +export interface GetTravelRuleWithdrawHistoryParams { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export type IsolatedMarginLevelStatus = - | 'EXCESSIVE' - | 'NORMAL' - | 'MARGIN_CALL' - | 'PRE_LIQUIDATION' - | 'FORCE_LIQUIDATION'; +export interface GetTravelRuleWithdrawHistoryV2Params { + trId?: string; + txId?: string; + withdrawOrderId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + offset?: number; + limit?: number; + startTime?: number; + endTime?: number; +} ⋮---- -export interface IsolatedMarginAccountAssets { - baseAsset: IsolatedMarginAccountAsset; - quoteAsset: IsolatedMarginAccountAsset; - symbol: string; - isolatedCreated: boolean; - enabled: boolean; - marginLevel: numberInString; - marginLevelStatus: IsolatedMarginLevelStatus; - marginRatio: numberInString; - indexPrice: numberInString; - liquidatePrice: numberInString; - liquidateRate: numberInString; - tradeEnabled: boolean; +export interface SubmitTravelRuleDepositQuestionnaireParams { + tranId: number; + questionnaire: string; } ⋮---- -export interface IsolatedMarginAccountInfo { - assets: IsolatedMarginAccountAssets[]; - totalAssetOfBtc?: numberInString; - totalLiabilityOfBtc?: numberInString; - totalNetAssetOfBtc?: numberInString; +export interface GetTravelRuleDepositHistoryParams { + trId?: string; + txId?: string; + tranId?: string; + network?: string; + coin?: string; + travelRuleStatus?: number; + pendingQuestionnaire?: boolean; + startTime?: number; + endTime?: number; + offset?: number; + limit?: number; } ⋮---- -export interface SpotSubUserAssetBtcList { - email: string; - totalAsset: numberInString; +export interface TravelRuleWithdrawHistoryRecord { + id: string; + trId: number; + amount: string; + transactionFee: string; + coin: string; + withdrawalStatus: number; + travelRuleStatus: number; + address: string; + addressTag?: string; + txId: string; + applyTime: string; + network?: string; + transferType: number; + withdrawOrderId?: string; + info: string; + confirmNo: number; + walletType: number; + txKey: string; + questionnaire: string; + completeTime?: string; } ⋮---- -export interface SubAccountList { - email: string; - isFreeze: boolean; - createTime: number; - isManagedSubAccount: boolean; - isAssetManagementSubAccount: boolean; +export interface SubmitTravelRuleDepositQuestionnaireResponse { + trId: number; + accepted: boolean; + info: string; } ⋮---- -export interface SubAccountDepositHistoryList { - depositId: number; - subAccountId: string; +export interface TravelRuleDepositHistoryRecord { + trId: number; + tranId: number; amount: string; coin: string; network: string; - status: number; + depositStatus: number; + travelRuleStatus: number; address: string; - addressTag: string; + addressTag?: string; txId: string; insertTime: number; - sourceAddress: string; + transferType: number; confirmTimes: string; + unlockConfirm: number; + walletType: number; + requireQuestionnaire: boolean; + questionnaire: string | null; } ⋮---- -export interface SubAccountTransferHistoryList { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +export interface VASPInfo { + vaspName: string; + vaspCode?: string; + /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ + identifier?: string; } ⋮---- -export interface SubAccountBasicTransfer { - from: string; - to: string; - asset: string; - qty: numberInString; - tranId: number; - time: number; +/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ +⋮---- +export interface TravelRuleCountryInfo { + countryCode: string; + countryName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; + hasRegionRestrictions: boolean; } ⋮---- -export interface MarginTradeCoeffVo { - forceLiquidationBar: numberInString; - marginCallBar: numberInString; - normalBar: numberInString; +export interface TravelRuleCountryListResponse { + countries: TravelRuleCountryInfo[]; + lastUpdated: number; } ⋮---- -export interface SubAccountStatus { - email: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - insertTime: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - mobile: number; +export interface GetTravelRuleRegionListParams { + countryCode: string; } ⋮---- -export interface BasicBtcTotals { - totalAssetOfBtc: numberInString; - totalLiabilityOfBtc: numberInString; - totalNetAssetOfBtc: numberInString; +export interface TravelRuleRegionInfo { + regionName: string; + blockType: 'supported' | 'limited' | 'blocked'; + depositAllowed: boolean; + withdrawalAllowed: boolean; } ⋮---- -export interface FuturesSubAccountAssets { - asset: string; - initialMargin: numberInString; - maintenanceMargin: numberInString; - marginBalance: numberInString; - maxWithdrawAmount: numberInString; - openOrderInitialMargin: numberInString; - positionInitialMargin: numberInString; - unrealizedProfit: numberInString; - walletBalance: numberInString; +export interface TravelRuleRegionListResponse { + countryCode: string; + regions: TravelRuleRegionInfo[]; + lastUpdated: number; } ⋮---- -export interface FuturesSubAccountList { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - email: string; +export interface GetVipLoanFixedRateMarketParams { + loanCoin: string; + duration?: number; + current?: number; + size?: number; } ⋮---- -export type AccountType = 'SPOT' | 'USDT_FUTURE' | 'COIN_FUTURE'; +export interface VipLoanFixedRateMarketRecord { + requestId: number; + requestNo: number; + coin: string; + interestRate: numberInString; + duration: number; + minimumAmount: numberInString; + availableAmount: numberInString; + estimatedInterest: numberInString; +} ⋮---- -export interface SubAccountTransferHistory { - counterParty: string; - email: string; - type: number; - asset: string; - qty: numberInString; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - tranId: number; - time: number; +export interface VipLoanFixedRateBorrowParams { + supplyRequest: string; + borrowCoin: string; + loanTerm: number; + borrowUid: number; + collateralCoin: string; + collateralAccountId: string; + autoRepay?: boolean; } ⋮---- -export interface SubAccountUniversalTransferHistory { - tranId: number; - fromEmail: string; - toEmail: string; - asset: string; - amount: numberInString; - createTimeStamp: number; - fromAccountType: AccountType; - toAccountType: AccountType; - status: string; - clientTranId?: string; +export interface VipLoanFixedRateBorrowResponse { + borrowCoin: string; + borrowAmount: numberInString; + actualReceivedAmount: numberInString; + collateralCoin: string; + collateralAccountId: string; + borrowInterestRate: numberInString; + duration: string; + autoRepay: boolean; + orderId: number; + status: 'Succeeds' | 'Failed' | 'Processing'; } ⋮---- -export interface BasicSubAccount { - email: string; - subAccountApiKey: string; +// Institutional Loan types +export interface InstitutionalLoanLiability { + assetName: string; + principal: string; + interest: string; } ⋮---- -export interface CreateSubAccountParams { - subAccountString: string; +export interface InstitutionalLoanWallet { + accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; } ⋮---- -export interface EnableOrDisableIPRestrictionForSubAccountParams - extends BasicSubAccount { - ipAddress?: string; +export interface InstitutionalLoanCollateralAccount { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + wallets: InstitutionalLoanWallet[]; } ⋮---- -export interface GetBrokerSubAccountHistoryParams { - fromId?: string; - toId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; +export interface InstitutionalLoanRiskUnitDetails { + groupId: number; + leverageTier: string; + initialLtv: string; + marginCallLtv: string; + liquidationLtv: string; + liquidationExitLtv: string; + maxTransferOutLtv: string; + parentEmail: string; + creditEmail: string; + updateTime: number; + ltv: string; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + // Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. + transferOutLtv: string; + parentAccountFrozenAmount: string; + maxTransferOutAmount: string; + maxAllowedBorrowLimit: string; + liabilities: InstitutionalLoanLiability[]; + collateralAccounts: InstitutionalLoanCollateralAccount[]; } ⋮---- -export interface CreateBrokerSubAccountParams { - tag?: string; +// Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. +⋮---- +export interface GetInstitutionalLoanRiskUnitDetailsParams { + groupId?: number; } ⋮---- -export interface GetBrokerSubAccountParams { - subAccountId?: string; - page?: number; - size?: number; +export interface CloseInstitutionalLoanRiskUnitResponse { + groupId: number; + status: 'CLOSED'; } ⋮---- -export interface GetApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey?: string; - page?: number; - size?: number; +export interface AddInstitutionalLoanCollateralAccountParams { + groupId: number; + subEmail: string; + enableSpot: boolean; + enableMargin: boolean; } ⋮---- -export interface CreateApiKeyBrokerSubAccountParams { - subAccountId: string; - canTrade: boolean; - marginTrade?: boolean; - futuresTrade?: boolean; +export interface InstitutionalLoanRiskUnitMember { + email: string; + type: 'CREDIT' | 'COLLATERAL'; + enableMargin: boolean; + enableSpot: boolean; } -export interface ApiKeyBrokerSubAccount { - subAccountId: string; - apiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +⋮---- +export interface ActiveInstitutionalLoanRiskUnit { + groupId: number; + members: InstitutionalLoanRiskUnitMember[]; + createTime: number; +} +export interface ClosedInstitutionalLoanRiskUnit { + groupId: number; + parentEmail: string; + creditEmail: string; + enabled: boolean; + createTime: number; + closeTime: number; } ⋮---- -export interface UpdateIpRestrictionForSubApiKey { - subAccountId: string; - ipAddress?: string; - subAccountApiKey: string; - status: string; +export interface GetClosedInstitutionalLoanRiskUnitsParams { + current?: number; + size?: number; } ⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canUniversalTransfer: boolean; +export interface GetClosedInstitutionalLoanRiskUnitsResponse { + total: number; + rows: ClosedInstitutionalLoanRiskUnit[]; } ⋮---- -export interface EnableMarginBrokerSubAccountParams { - subAccountId: string; - margin: boolean; +// Institutional Loan Force Liquidation interfaces +export interface InstitutionalLoanLiquidationSnapshot { + subEmail: string; + memberType: 'CREDIT' | 'COLLATERAL'; + walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; + netEquity: string; + maintainMargin: string; } ⋮---- -export interface EnableMarginBrokerSubAccountResponse { - subAccountId: string; - enableMargin: boolean; - updateTime: number; +export interface InstitutionalLoanLiquidationSnapshotData { + snapshots: InstitutionalLoanLiquidationSnapshot[]; + liabilities: InstitutionalLoanLiability[]; } ⋮---- -export interface EnableFuturesBrokerSubAccountParams { - subAccountId: string; - futures: boolean; +export interface InstitutionalLoanForceLiquidationRecord { + groupId: number; + startLtv: number; + endLtv: number; + liquidationStartTime: number; + liquidationEndTime: number; + totalNetEquity: string; + totalMaintenanceMargin: string; + totalLiability: string; + liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; } ⋮---- -export interface EnableFuturesBrokerSubAccountResponse { - subAccountId: string; - enableFutures: boolean; - updateTime: number; +export interface GetInstitutionalLoanForceLiquidationParams { + groupId?: number; + startTime?: number; + endTime?: number; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface EnableMarginApiKeyBrokerSubAccountParams { - subAccountId: string; - margin: boolean; +export interface GetInstitutionalLoanForceLiquidationResponse { + total: number; + rows: InstitutionalLoanForceLiquidationRecord[]; } -export interface UniversalTransferBrokerParams { - fromId?: string; - toId?: string; - fromAccountType: string; - toAccountType: string; - asset: string; - amount: number; +⋮---- +// Risk Unit Transfer interfaces +export interface InstitutionalLoanRiskUnitTransferParams { + subEmail?: string; // Optional: subEmail can be credit account or collateral account + asset: string; // Asset Name + amount: number; // Transfer amount of the asset } ⋮---- -export interface GetUniversalTransferBrokerParams { - fromId?: string; - toId?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; - showAllStatus?: boolean; +subEmail?: string; // Optional: subEmail can be credit account or collateral account +asset: string; // Asset Name +amount: number; // Transfer amount of the asset +⋮---- +// Additional institutional loan types for borrow, repay, and interest history +export interface GetInstitutionalLoanMaxBorrowableParams { + groupId?: number; + assetName: string; } ⋮---- -export interface GetBrokerSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; +export interface InstitutionalLoanMaxBorrowableResponse { + maxBorrowableAmount: numberInString | null; } ⋮---- -export interface DeleteApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; +export interface InstitutionalLoanBorrowParams { + groupId: number; + assetName: string; + amount: number; } ⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountParams { - subAccountId: string; - subAccountApiKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +export interface InstitutionalLoanBorrowResponse { + transactionId: string; + amount: number; + status: string; } ⋮---- -export interface ChangePermissionApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +export interface InstitutionalLoanRepayParams { + groupId: number; + assetName: string; + amount: number; } ⋮---- -export interface VirtualSubAccount { - email: string; +export interface InstitutionalLoanRepayResponse { + transactionId: string; + amount: number; } ⋮---- -export interface BrokerSubAccountHistory { - subAccountsHistory: SubAccountTransferHistoryList[]; +export interface GetInstitutionalLoanInterestHistoryParams { + groupId?: number; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface BrokerSubAccount { - subaccountId: string; - email: string; - makerCommission?: string; - takerCommission?: string; - marginMakerCommission?: string; - marginTakerCommission?: string; - createTime?: number; - tag: string; +export interface InstitutionalLoanInterestHistoryRecord { + groupId: number; + assetName: string; + principal: string; + interestRate: string; + interest: string; + interestTimestamp: number; } ⋮---- -export interface CreateApiKeyBrokerSubAccountResponse { - subaccountId: string; - apiKey: string; - secretKey: string; - canTrade: boolean; - marginTrade: boolean; - futuresTrade: boolean; +export interface InstitutionalLoanInterestHistoryResponse { + total: number; + rows: InstitutionalLoanInterestHistoryRecord[]; } ⋮---- -export interface EnableUniversalTransferApiKeyBrokerSubAccountResponse { - subAccountId: string; - apikey: string; - canUniversalTransfer: boolean; +export interface GetInstitutionalLoanBorrowRepayRecordsParams { + groupId?: number; // Optional: Risk unit unique identifier + type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY + asset?: string; // Optional: Asset name + startTime?: number; // Optional: Start time + endTime?: number; // Optional: End time + current?: number; // Optional: The currently querying page. Start from 1. Default:1 + size?: number; // Optional: Default:10 Max:100 + recvWindow?: number; // Optional: The value cannot be greater than 60000 + timestamp: number; // Required } ⋮---- -export interface GetBrokerInfoResponse { - maxMakerCommission: string; - minMakerCommission: string; - maxTakerCommission: string; - minTakerCommission: string; - subAccountQty: number; - maxSubAccountQty: number; +groupId?: number; // Optional: Risk unit unique identifier +type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY +asset?: string; // Optional: Asset name +startTime?: number; // Optional: Start time +endTime?: number; // Optional: End time +current?: number; // Optional: The currently querying page. Start from 1. Default:1 +size?: number; // Optional: Default:10 Max:100 +recvWindow?: number; // Optional: The value cannot be greater than 60000 +timestamp: number; // Required +⋮---- +export interface InstitutionalLoanBorrowRepayRecord { + tranId: number; // Transaction ID + assetName: string; // Asset name + amount: number; // Amount + status: 'CONFIRM' | 'FAILED'; // Status + type: 'BORROW' | 'REPAY'; // Type + timestamp: number; // Create Time + principal?: number; // Only present for REPAY type + interest?: number; // Only present for REPAY type } -export interface SubAccountListParams { - email?: string; - isFreeze?: StringBoolean; - page?: number; - limit?: number; +⋮---- +tranId: number; // Transaction ID +assetName: string; // Asset name +amount: number; // Amount +status: 'CONFIRM' | 'FAILED'; // Status +type: 'BORROW' | 'REPAY'; // Type +timestamp: number; // Create Time +principal?: number; // Only present for REPAY type +interest?: number; // Only present for REPAY type +⋮---- +export interface GetInstitutionalLoanBorrowRepayRecordsResponse { + total: number; + rows: InstitutionalLoanBorrowRepayRecord[]; } ⋮---- -export interface SubAccountListResponse { - subAccounts: SubAccountList[]; +export interface MarginInterestRebateBalanceResponse { + asset: string; + balance: string; + totalGranted: string; + totalConsumed: string; } ⋮---- -export interface SubAccountSpotAssetTransferHistoryParams { - fromEmail?: string; - toEmail?: string; +export interface GetMarginInterestRebateBalanceRecordsParams { + type?: 0 | 1 | 2; startTime?: number; endTime?: number; - page?: number; - limit?: number; + current?: number; + size?: number; } ⋮---- -export interface SubAccountSpotAssetTransferHistory - extends SubAccountBasicTransfer { - status: string; +export interface MarginInterestRebateBalanceRecord { + type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; + rebateAsset: string; + delta: string; + createTime: number; + groupId?: number; + liabilityAsset?: string; + deductedInterest?: string; + exchangeRate?: string; } ⋮---- -export interface SubAccountFuturesAssetTransferHistoryParams { - email: string; - futuresType: number; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +export interface MarginInterestRebateBalanceRecordsResponse { + total: number; + rows: MarginInterestRebateBalanceRecord[]; } ⋮---- -export interface SubAccountFuturesAssetTransferHistory { - success: boolean; - futuresType: number; - transfers: SubAccountBasicTransfer[]; +// On-chain Yields types +⋮---- +export interface OnchainYieldsLockedProductListParams { + asset?: string; + current?: number; + size?: number; } ⋮---- -export interface SubAccountFuturesAssetTransferParams { - fromEmail: string; - toEmail: string; - futuresType: number; +export interface OnchainYieldsLockedProductDetail { asset: string; - amount: number; + rewardAsset: string; + duration: number; + renewable: boolean; + isSoldOut: boolean; + apr: string; + status: 'PREHEATING' | 'PURCHASING'; + subscriptionStartTime: string; + canRedeemToFlex: boolean; } ⋮---- -export interface SubAccountFuturesAssetTransfer { - success: boolean; - txnId: numberInString; +export interface OnchainYieldsLockedProductQuota { + totalPersonalQuota: string; + minimum: string; } ⋮---- -export interface SubAccountAssetsParams { - email: string; +export interface OnchainYieldsLockedProduct { + projectId: string; + detail: OnchainYieldsLockedProductDetail; + quota: OnchainYieldsLockedProductQuota; } ⋮---- -export interface SubAccountAssets { - balances: SpotBalance[]; +export interface OnchainYieldsLockedProductListResponse { + rows: OnchainYieldsLockedProduct[]; + total: number; } ⋮---- -export interface SubAccountSpotAssetsSummaryParams { - email?: string; - page?: number; - size?: number; +export interface OnchainYieldsLockedPersonalLeftQuotaParams { + projectId: string; } ⋮---- -export interface SubAccountSpotAssetsSummary { - totalCount: number; - masterAccountTotalAsset: numberInString; - spotSubUserAssetBtcVoList: SpotSubUserAssetBtcList[]; +export interface OnchainYieldsLockedPersonalLeftQuotaResponse { + leftPersonalQuota: string; } ⋮---- -export interface SubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; +export interface OnchainYieldsLockedPositionParams { + asset?: string; + positionId?: number; + projectId?: string; + current?: number; + size?: number; } ⋮---- -export interface SubAccountDepositAddress { - address: string; - coin: string; - tag: string; - url: string; +export interface OnchainYieldsLockedPosition { + positionId: string; + projectId: string; + asset: string; + amount: string; + purchaseTime: string; + duration: string; + accrualDays: string; + rewardAsset: string; + APY: string; + rewardAmt: string; + nextPay?: string; + nextPayDate?: string; + payPeriod?: string; + rewardsPayDate?: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; + redeemingAmt?: string; + redeemTo?: 'FLEXIBLE' | 'SPOT'; + canRedeemEarly: boolean; + autoSubscribe: boolean; + type: 'AUTO' | 'NORMAL'; + status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; } ⋮---- -export interface SubAccountDepositHistoryParams extends DepositHistoryParams { - email: string; +export interface OnchainYieldsLockedPositionResponse { + rows: OnchainYieldsLockedPosition[]; + total: number; } ⋮---- -export interface SubAccountEnableMargin { - email: string; - isMarginEnabled: boolean; +export interface OnchainYieldsAccountResponse { + totalAmountInBTC: string; + totalAmountInUSDT: string; + totalFlexibleAmountInBTC: string; + totalFlexibleAmountInUSDT: string; + totalLockedInBTC: string; + totalLockedInUSDT: string; } ⋮---- -export interface SubAccountMarginAccountDetail extends BasicBtcTotals { - email: string; - marginLevel: numberInString; - marginTradeCoeffVo: MarginTradeCoeffVo; - marginUserAssetVoList: MarginBalance[]; -} +// On-chain Yields Earn types ⋮---- -export interface SubAccountListBtc extends BasicBtcTotals { - email: string; +export interface OnchainYieldsLockedSubscriptionPreviewParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; } ⋮---- -export interface SubAccountsMarginAccountSummary extends BasicBtcTotals { - subAccountList: SubAccountListBtc; +export interface OnchainYieldsLockedSubscriptionPreviewResponse { + rewardAsset: string; + totalRewardAmt: string; + nextPay?: string; + nextPayDate?: string; + rewardsPayDate?: string; + valueDate: string; + rewardsEndDate: string; + deliverDate?: string; + nextSubscriptionDate?: string; } ⋮---- -export interface SubAccountEnableFutures { - email: string; - isFuturesEnabled: boolean; +export interface OnchainYieldsLockedSubscribeParams { + projectId: string; + amount: number; + autoSubscribe?: boolean; + sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; + redeemTo?: 'SPOT' | 'FLEXIBLE'; + channelId?: string; + clientId?: string; } ⋮---- -export interface SubAccountFuturesAccountDetail { - email: string; - asset: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; +export interface OnchainYieldsLockedSubscribeResponse { + purchaseId: number; + positionId: string; + amount: string; + success: boolean; } ⋮---- -export interface SubAccountFuturesAccountSummary extends FuturesSubAccountList { - subAccountList: FuturesSubAccountList[]; +export interface OnchainYieldsLockedSetAutoSubscribeParams { + positionId: string; + autoSubscribe: boolean; } ⋮---- -export interface FuturesPositionRisk { - entryPrice: numberInString; - leverage: numberInString; - maxNotional: numberInString; - liquidationPrice: numberInString; - markPrice: numberInString; - positionAmount: numberInString; - symbol: string; - unrealizedProfit: numberInString; +export interface OnchainYieldsLockedSetAutoSubscribeResponse { + success: boolean; } ⋮---- -export interface SubAccountTransferParams { - email: string; - asset: string; - amount: number; - type: number; +export interface OnchainYieldsLockedSetRedeemOptionParams { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; } ⋮---- -export interface SubAccountTransfer { - txnId: numberInString; +export interface OnchainYieldsLockedSetRedeemOptionResponse { + success: boolean; } ⋮---- -export interface SubAccountTransferToSameMasterParams { - toEmail: string; - asset: string; - amount: number; +export interface OnchainYieldsLockedRedeemParams { + positionId: number; + channelId?: string; } ⋮---- -export interface SubAccountTransferToMasterParams { - asset: string; - amount: number; +export interface OnchainYieldsLockedRedeemResponse { + redeemId: number; + success: boolean; } ⋮---- -export interface SubAccountTransferHistoryParams { +// On-chain Yields History types +⋮---- +export interface OnchainYieldsLockedSubscriptionRecordParams { + purchaseId?: string; + clientId?: string; asset?: string; - type?: number; startTime?: number; endTime?: number; - limit?: number; + current?: number; + size?: number; } ⋮---- -export interface SubAccountUniversalTransferParams { - fromEmail?: string; - toEmail?: string; - fromAccountType: AccountType; - toAccountType: AccountType; - clientTranId?: string; +export interface OnchainYieldsLockedSubscriptionRecord { + positionId: string; + purchaseId: string; + projectId: string; + clientId: string; + time: number; asset: string; - amount: number; -} -⋮---- -export interface SubAccountMovePositionParams { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - orderArgs: { - symbol: string; - quantity: number; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - }[]; -} -export interface SubAccountUniversalTransfer extends SubAccountTransfer { - clientTranId?: string; + amount: string; + lockPeriod: string; + type: 'NORMAL' | 'AUTO'; + sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; + amtFromSpot?: string; + amtFromFunding?: string; + status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; } ⋮---- -export interface SubAccountMovePosition { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - symbol: string; - priceType: string; - price: string; - quantity: string; - positionSide: string | null; - side: string; - success: boolean; +export interface OnchainYieldsLockedSubscriptionRecordResponse { + rows: OnchainYieldsLockedSubscriptionRecord[]; + total: number; } ⋮---- -export interface SubAccountMovePositionHistoryParams { - symbol: string; - productType?: 'UM' | 'OPTION'; +export interface OnchainYieldsLockedRewardsHistoryParams { + positionId?: string; + asset?: string; startTime?: number; endTime?: number; - page: number; - row: number; + current?: number; + size?: number; } ⋮---- -export interface SubAccountMovePositionHistory { - fromUserEmail: string; - toUserEmail: string; - productType: 'UM' | 'OPTION'; - symbol: string; - price: string; - quantity: string; - positionSide: string | null; - side: string; - timeStamp: number; +export interface OnchainYieldsLockedRewardsRecord { + positionId: string; + time: number; + asset: string; + lockPeriod: string; + amount: string; } ⋮---- -export interface SubAccountUniversalTransferHistoryParams { - fromEmail?: string; - toEmail?: string; - clientTranId?: string; - startTime?: number; - endTime?: number; - page?: number; - limit?: number; +export interface OnchainYieldsLockedRewardsHistoryResponse { + rows: OnchainYieldsLockedRewardsRecord[]; + total: number; } ⋮---- -export interface SubAccountUniversalTransferHistoryResponse { - result: SubAccountUniversalTransferHistory[]; - totalCount: number; +export interface OnchainYieldsLockedRedemptionRecordParams { + positionId?: number; + redeemId?: string; + asset?: string; + startTime?: number; + endTime?: number; + current?: number; + size?: number; } ⋮---- -export interface SubAccountEnableLeverageToken { - email: string; - enableBlvt: boolean; +export interface OnchainYieldsLockedRedemptionRecord { + positionId: string; + redeemId: number; + time: number; + asset: string; + lockPeriod: string; + amount: string; + originalAmount: string; + type: 'NORMAL' | 'EARLY' | 'CONVERT'; + deliverDate: string; + lossAmount: string; + isComplete: boolean; + rewardAsset: string; + rewardAmt: string; + status: 'CREATED' | 'PAID'; } ⋮---- -export interface AddIpRestriction extends BasicSubAccount { - status: string; - ipAddress: string; +export interface OnchainYieldsLockedRedemptionRecordResponse { + rows: OnchainYieldsLockedRedemptionRecord[]; + total: number; } ⋮---- -export interface SubAccountEnableOrDisableIPRestriction { - ipRestrict: boolean; - ipList: string[]; - updateTime: number; - apiKey: string; -} +/** + * ALPHA TRADING INTERFACES + */ ⋮---- -export interface SubAccountAddOrDeleteIPList extends BasicSubAccount { - ipAddress: string; +export interface AlphaToken { + alphaId: number; + symbol: string; + name: string; + chainId: string; + contractAddress: string; + decimals?: number; } ⋮---- -export interface AddIPListForSubAccountResponseParams { - ip: string; - updateTime: number; - apiKey: string; +export interface AlphaExchangeFilter { + filterType: string; + minPrice?: string; + maxPrice?: string; + tickSize?: string; + stepSize?: string; + maxQty?: string; + minQty?: string; + limit?: number; + minNotional?: string; + maxNotional?: string; + multiplierDown?: string; + multiplierUp?: string; + bidMultiplierUp?: string; + askMultiplierUp?: string; + bidMultiplierDown?: string; + askMultiplierDown?: string; } ⋮---- -export interface SubAccountAssetDetails { - coin: string; - name: string; - totalBalance: numberInString; - availableBalance: numberInString; - inOrder: numberInString; - btcValue: numberInString; +export interface AlphaSymbol { + symbol: string; + status: string; + baseAsset: string; + quoteAsset: string; + pricePrecision: number; + quantityPrecision: number; + baseAssetPrecision: number; + quotePrecision: number; + filters: AlphaExchangeFilter[]; + orderTypes: string[]; } ⋮---- -export interface WithdrawAssetsFromManagedSubAccountParams { - fromEmail: string; +export interface AlphaAsset { asset: string; - amount: number; - transferDate?: number; } ⋮---- -export interface BasicFuturesSubAccountParams { - email: string; - futuresType: 1 | 2; +export interface AlphaExchangeInfo { + timezone: string; + assets: AlphaAsset[]; + symbols: AlphaSymbol[]; } ⋮---- -export interface SubAccountSummaryOnFuturesAccountV2Params { - futuresType: 1 | 2; - page?: number; +export interface AlphaAggTradesParams { + symbol: string; + fromId?: number; + startTime?: number; + endTime?: number; limit?: number; } ⋮---- -export interface SubAccountUSDMDetail { - futureAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - maxWithdrawAmount: numberInString; - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - updateTime: number; - }; +export interface AlphaAggTrade { + a: number; // aggregate trade ID + p: string; // price + q: string; // quantity + f: number; // first trade ID + l: number; // last trade ID + T: number; // timestamp + m: boolean; // is buyer market maker } ⋮---- -export interface COINMSubAccount { - email: string; - totalMarginBalance: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; -} +a: number; // aggregate trade ID +p: string; // price +q: string; // quantity +f: number; // first trade ID +l: number; // last trade ID +T: number; // timestamp +m: boolean; // is buyer market maker ⋮---- -export interface SubAccountCOINMDetail { - deliveryAccountResp: { - email: string; - assets: FuturesSubAccountAssets[]; - canDeposit: boolean; - canWithdraw: boolean; - feeTier: number; - updateTime: number; - }; +export interface AlphaKlinesParams { + symbol: string; + interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M + limit?: number; + startTime?: number; + endTime?: number; } ⋮---- -export interface SubAccountUSDMSummary { - futureAccountSummaryResp: { - totalInitialMargin: numberInString; - totalMaintenanceMargin: numberInString; - totalMarginBalance: numberInString; - totalOpenOrderInitialMargin: numberInString; - totalPositionInitialMargin: numberInString; - totalUnrealizedProfit: numberInString; - totalWalletBalance: numberInString; - asset: string; - subAccountList: FuturesSubAccountList[]; - }; +interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M +⋮---- +export type AlphaKline = [ + string, // Open time + string, // Open price + string, // High price + string, // Low price + string, // Close price + string, // Volume + string, // Close time + string, // Quote asset volume + string, // Number of trades + string, // Taker buy base asset volume + string, // Taker buy quote asset volume + string, // Ignore (always "0") +]; +⋮---- +string, // Open time +string, // Open price +string, // High price +string, // Low price +string, // Close price +string, // Volume +string, // Close time +string, // Quote asset volume +string, // Number of trades +string, // Taker buy base asset volume +string, // Taker buy quote asset volume +string, // Ignore (always "0") +⋮---- +export interface AlphaTickerParams { + symbol: string; } ⋮---- -export interface SubAccountCOINMSummary { - deliveryAccountSummaryResp: { - totalMarginBalanceOfBTC: numberInString; - totalUnrealizedProfitOfBTC: numberInString; - totalWalletBalanceOfBTC: numberInString; - asset: string; - subAccountList: COINMSubAccount[]; - }; +export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; +⋮---- +export interface AlphaFullDepthParams { + symbol: string; + limit?: AlphaFullDepthLimit; } ⋮---- -export interface COINMPositionRisk { - entryPrice: numberInString; - markPrice: numberInString; - leverage: numberInString; - isolated: numberInString; - isolatedWallet: numberInString; - isolatedMargin: numberInString; - isAutoAddMargin: numberInString; - positionSide: string; - positionAmount: numberInString; +export interface AlphaFullDepthData { + lastUpdateId: number; symbol: string; - unrealizedProfit: numberInString; + bids: [string, string][]; + asks: [string, string][]; + E: number; + T: number; } ⋮---- -export interface SubAccountUSDMPositionRisk { - futurePositionRiskVos: FuturesPositionRisk[]; +export interface AlphaFullDepthResponse { + code: string; + message: string | null; + messageDetail: string | null; + success: boolean; + data: AlphaFullDepthData; } ⋮---- -export interface SubAccountCOINMPositionRisk { - deliveryPositionRiskVos: COINMPositionRisk[]; +export interface AlphaTicker { + symbol: string; + priceChange: string; + priceChangePercent: string; + weightedAvgPrice: string; + lastPrice: string; + lastQty: string; + openPrice: string; + highPrice: string; + lowPrice: string; + volume: string; + quoteVolume: string; + openTime: number; + closeTime: number; + firstId: number; + lastId: number; + count: number; } ⋮---- -export interface StakingProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - apy: numberInString; +/** + * Soft Staking interfaces + */ +export interface GetSoftStakingProductListParams { + asset?: string; + current?: number; + size?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface StakingProductQuota { - totalPersonalQuota: numberInString; - minimum: numberInString; +export interface SoftStakingProduct { + asset: string; + minAmount: string; + maxCap: string; + apr: string; + stakedAmount: string; + totalProfit: string; } ⋮---- -export interface StakingProduct { - projectId: string; - detail: StakingProductDetail; - quota: StakingProductQuota; +export interface GetSoftStakingProductListResponse { + status: boolean; + totalRewardsUsdt: string; + rows: SoftStakingProduct[]; + total: number; } ⋮---- -export type StakingTxnType = 'SUBSCRIPTION' | 'REDEMPTION' | 'INTEREST'; -export type StakingStatus = 'HOLDING' | 'REDEEMED'; -export type StakingProductType = 'STAKING' | 'F_DEFI' | 'L_DEFI'; -export type BSwapType = 'SINGLE' | 'COMBINATION'; -export type BSwapOperationType = 'ADD' | 'REMOVE'; +export interface SetSoftStakingParams { + softStaking: boolean; + recvWindow?: number; + timestamp: number; +} ⋮---- -export interface StakingProductPosition { - positionId: numberInString; - projectId: string; - asset: string; - amount: numberInString; - purchaseTime: numberInString; - duration: numberInString; - accrualDays: numberInString; - rewardAsset: string; - APY: numberInString; - rewardAmt: numberInString; - extraRewardAsset: string; - extraRewardAPY: numberInString; - estExtraRewardAmt: numberInString; - nextInterestPay: numberInString; - nextInterestPayDate: numberInString; - payInterestPeriod: numberInString; - redeemAmountEarly: numberInString; - interestEndDate: numberInString; - deliverDate: numberInString; - redeemPeriod: numberInString; - redeemingAmt: numberInString; - partialAmtDeliverDate: numberInString; - canRedeemEarly: boolean; - renewable: boolean; - type: string; - status: StakingStatus; +export interface SetSoftStakingResponse { + success: boolean; } -export interface StakingBasicParams { - product: StakingProductType; +⋮---- +export interface GetSoftStakingRewardsHistoryParams { + asset?: string; + startTime?: number; + endTime?: number; current?: number; size?: number; + recvWindow?: number; + timestamp: number; } ⋮---- -export interface FlexibleSavingBasicParams { - status?: string; - featured?: number; - current?: number; - size?: number; - asset?: string; +export interface SoftStakingRewardsRecord { + asset: string; + rewards: string; + rewardAsset: string; + avgAmount: string; + time: number; } ⋮---- -export interface FlexibleProductPositionParams { - status?: string; - featured?: number; - current?: number; - size?: number; +export interface GetSoftStakingRewardsHistoryResponse { + rows: SoftStakingRewardsRecord[]; + total: number; } + +================ +File: src/main-client.ts +================ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from 'axios'; +⋮---- +import { + AmendKeepPriorityParams, + BasicAssetPaginatedParams, + BasicAssetParam, + BasicSymbolParam, + BinanceBaseUrlKey, + CancelOCOParams, + CancelOrderParams, + CoinStartEndLimit, + ExchangeSymbol, + GetAllOrdersParams, + GetOrderParams, + HistoricalTradesParams, + Kline, + KlinesParams, + NewOCOParams, + NewOrderListParams, + OrderBookParams, + OrderIdProperty, + OrderResponseType, + OrderType, + RecentTradesParams, + RowsWithTotal, + SymbolFromPaginatedRequestFromId, + SymbolPrice, +} from './types/shared'; +import { + AcceptQuoteRequestParams, + AccountInfo, + AccountInformation, + ActiveInstitutionalLoanRiskUnit, + AddBSwapLiquidityParams, + AddInstitutionalLoanCollateralAccountParams, + AddIpRestriction, + AdjustCryptoLoanLTVParams, + AdjustCryptoLoanLTVResponse, + AdjustFlexibleCryptoLoanLTVParams, + AdjustFlexibleCryptoLoanLTVResponse, + AggregateTrade, + AlgoOrder, + AllCoinsInformationResponse, + Allocation, + AllocationsParams, + AlphaAggTrade, + AlphaAggTradesParams, + AlphaExchangeInfo, + AlphaFullDepthParams, + AlphaFullDepthResponse, + AlphaKline, + AlphaKlinesParams, + AlphaTicker, + AlphaToken, + ApiKeyBrokerSubAccount, + APIPermissions, + APITradingStatus, + ApplicationStatus, + AssetDetail, + BasicFromPaginatedParams, + BasicFuturesSubAccountParams, + BasicMarginAssetParams, + BasicSubAccount, + BasicTimeRangeParam, + BethRewardsHistory, + BfusdAccountResponse, + BfusdQuotaResponse, + BfusdRateHistoryRow, + BfusdRedeemParams, + BfusdRedeemResponse, + BfusdRedemptionHistoryRow, + BfusdRewardsHistoryRow, + BfusdSubscribeParams, + BfusdSubscribeResponse, + BfusdSubscriptionHistoryRow, + BlockTrade, + BlvtRedemptionRecord, + BlvtSubscriptionRecord, + BlvtUserLimitInfo, + BNBBurnResponse, + BnbTransferParams, + BnsolRateHistoryRecord, + BnsolRewardHistoryRecord, + BorrowCryptoLoanParams, + BorrowCryptoLoanResponse, + BorrowFlexibleLoanParams, + BorrowFlexibleLoanResponse, + BorrowInterestRate, + BrokerCommissionRebate, + BrokerSubAccount, + BrokerSubAccountCoinFuturesCommission, + BrokerSubAccountFuturesCommission, + BrokerSubAccountHistory, + BrokerUniversalTransfer, + BSwapLiquidity, + BSwapOperations, + BSwapOperationsParams, + BUSDConversionRecord, + CancelAlgoOrderResponse, + CancelHashrateResaleConfigParams, + CancelOrderListResult, + CancelSpotAlgoOrderResponse, + CancelSpotOrderResult, + ChangeAutoCompoundStatusParams, + ChangeAutoCompoundStatusResponse, + ChangePermissionApiKeyBrokerSubAccountParams, + ChangePermissionApiKeyBrokerSubAccountResponse, + ChangePlanStatusParams, + ChangePlanStatusResponse, + ChangeSubAccountCoinFuturesCommissionParams, + ChangeSubAccountCommissionParams, + ChangeSubAccountCommissionResponse, + ChangeSubAccountFuturesCommissionParams, + ChangeSubAccountFuturesCommissionResponse, + CheckCollateralRepayRateParams, + CheckCollateralRepayRateResponse, + CheckDualInvestmentAccountsResponse, + CheckVipCollateralAccountParams, + CloseInstitutionalLoanRiskUnitResponse, + CloudMining, + CloudMiningHistoryParams, + CoinMarginedFuturesResponse, + Collateral, + CollateralAssetData, + CollateralRecord, + CommissionRates, + ConvertDustParams, + ConvertibleCoinsParams, + ConvertibleCoinsResponse, + ConvertLimitOpenOrder, + ConvertQuoteRequestParams, + ConvertTransfer, + ConvertTransferResponse, + CreateApiKeyBrokerSubAccountParams, + CreateApiKeyBrokerSubAccountResponse, + CreateBrokerSubAccountParams, + CreateDualTokenGiftCardParams, + CreateGiftCardParams, + CreateInvestmentPlanParams, + CreateInvestmentPlanResponse, + CreateSpecialLowLatencyKeyParams, + CreateSubAccountParams, + CrossMarginFeeData, + CrossMarginTransferHistory, + CurrentAvgPrice, + CustomizeMarginCall, + CustomizeMarginCallParams, + DailyAccountSnapshot, + DailyAccountSnapshotParams, + DelegationHistory, + DelegationHistoryParams, + DeleteApiKeyBrokerSubAccountParams, + DelistScheduleResponse, + DepositAddress, + DepositAddressListParams, + DepositAddressParams, + DepositAddressResponse, + DepositHistory, + DepositHistoryParams, + DualInvestmentPosition, + DualInvestmentProduct, + DustConversion, + DustConvertibleAssetsParams, + DustConvertibleAssetsResponse, + DustConvertParams, + DustInfo, + DustLog, + EditInvestmentPlanParams, + EditInvestmentPlanResponse, + EnableConvertSubAccountParams, + EnableFuturesBrokerSubAccountParams, + EnableFuturesBrokerSubAccountResponse, + EnableMarginApiKeyBrokerSubAccountParams, + EnableMarginBrokerSubAccountParams, + EnableMarginBrokerSubAccountResponse, + EnableOptionsForSubAccountResponse, + EnableOrDisableIPRestrictionForSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountParams, + EnableUniversalTransferApiKeyBrokerSubAccountResponse, + ETHRateHistory, + EthRedemptionHistory, + EthStakingHistory, + ExchangeInfo, + ExchangeInfoParams, + FiatDepositParams, + FiatDepositResponse, + FixedAndActivityProjectParams, + FixedAndActivityProjectPositionParams, + FlexibleCryptoLoanBorrowHistory, + FlexibleLoanAssetData, + FlexibleLoanCollateralAssetData, + FlexibleLoanLiquidationHistoryRecord, + FlexibleLoanLTVAdjustmentHistory, + FlexibleLoanOngoingOrder, + FlexibleRedemptionRecord, + FlexibleRewardsHistory, + FlexibleSubscriptionPreview, + ForceLiquidationRecord, + FundingAsset, + FutureAccountTransfer, + FuturesPositionRisk, + GetAlgoHistoricalOrdersParams, + GetAlgoSubOrdersParams, + GetAlgoSubOrdersResponse, + GetAllConvertPairsParams, + GetApiKeyBrokerSubAccountParams, + GetApplicationStatusParams, + GetAssetParams, + GetBethRewardsHistoryParams, + GetBfusdRateHistoryParams, + GetBfusdRedemptionHistoryParams, + GetBfusdRewardsHistoryParams, + GetBfusdSubscriptionHistoryParams, + GetBlvtRedemptionRecordParams, + GetBlvtSubscriptionRecordParams, + GetBnsolRateHistoryReq, + GetBnsolRewardsHistoryReq, + GetBrokerInfoResponse, + GetBrokerSubAccountDepositHistoryParams, + GetBrokerSubAccountHistoryParams, + GetBrokerSubAccountParams, + GetC2CTradeHistoryParams, + GetC2CTradeHistoryResponse, + GetClosedInstitutionalLoanRiskUnitsParams, + GetClosedInstitutionalLoanRiskUnitsResponse, + GetCollateralAssetDataParams, + GetCollateralRecordParams, + GetConvertBUSDHistoryParams, + GetConvertTradeHistoryParams, + GetCrossMarginTransferHistoryParams, + GetCryptoLoansIncomeHistoryParams, + GetCryptoLoansIncomeHistoryResponse, + GetDualInvestmentPositionsParams, + GetDualInvestmentProductListParams, + GetEarningsListParams, + GetEarningsListResponse, + GetETHRateHistoryParams, + GetEthRedemptionHistoryParams, + GetEthStakingAccountResponse, + GetEthStakingAccountV2Response, + GetEthStakingHistoryParams, + GetEthStakingQuotaResponse, + GetExtraBonusListParams, + GetExtraBonusListResponse, + GetFiatOrderDetailParams, + GetFiatOrderDetailResponse, + GetFiatOrderHistoryParams, + GetFiatOrderHistoryResponse, + GetFiatPaymentsHistoryResponse, + GetFlexibleCryptoLoanBorrowHistoryParams, + GetFlexibleLoanLiquidationHistoryParams, + GetFlexibleLoanLTVAdjustmentHistoryParams, + GetFlexibleLoanOngoingOrdersParams, + GetFlexibleRedemptionRecordParams, + GetFlexibleRewardsHistoryParams, + GetFlexibleSubscriptionPreviewParams, + GetFlexibleSubscriptionRecordParams, + GetFlexibleSubscriptionRecordResponse, + GetForceLiquidationRecordParams, + GetFutureAccountTransferHistoryParams, + GetFuturesLeadTraderStatusResponse, + GetFuturesLeadTradingSymbolWhitelistResponse, + GetFutureTickLevelOrderbookDataLinkParams, + GetHashrateResaleDetailParams, + GetHashrateResaleDetailResponse, + GetHashrateResaleListParams, + GetHashrateResaleListResponse, + GetIndexDetailsResponse, + GetIndexLinkedPlanPositionDetailsResponse, + GetIndexLinkedPlanRebalanceHistoryParams, + GetIndexLinkedPlanRedemptionHistoryParams, + GetInstitutionalLoanBorrowRepayRecordsParams, + GetInstitutionalLoanBorrowRepayRecordsResponse, + GetInstitutionalLoanForceLiquidationParams, + GetInstitutionalLoanForceLiquidationResponse, + GetInstitutionalLoanInterestHistoryParams, + GetInstitutionalLoanMaxBorrowableParams, + GetInstitutionalLoanRiskUnitDetailsParams, + GetLoanableAssetsDataParams, + GetLoanBorrowHistoryParams, + GetLoanCoinPaginatedHistoryParams, + GetLoanLTVAdjustmentHistoryParams, + GetLoanOngoingOrdersParams, + GetLoanRepaymentHistoryParams, + GetLockedRedemptionRecordParams, + GetLockedRewardsHistory, + GetLockedRewardsHistoryParams, + GetLockedSubscriptionPreviewParams, + GetLockedSubscriptionRecordParams, + GetMarginAccountBorrowRepayRecordsParams, + GetMarginCapitalFlowParams, + GetMarginInterestHistoryParams, + GetMarginInterestRebateBalanceRecordsParams, + GetMarginLiquidationLoanRepayHistoryParams, + GetMarginOrderCountUsageParams, + GetMinerDetailsParams, + GetMinerDetailsResponse, + GetMinerListParams, + GetMinerListResponse, + GetMiningAccountEarningParams, + GetMiningAccountEarningResponse, + getMiningAccountsListParams, + getMiningAccountsListResponse, + GetMiningAlgoListResponse, + GetMiningCoinListResponse, + GetNextHourlyInterestRateParams, + GetNftAssetParams, + GetNftDepositHistoryParams, + GetNftTransactionHistoryParams, + GetNftWithdrawHistoryParams, + GetOCOParams, + GetOneTimeTransactionStatusParams, + GetOneTimeTransactionStatusResponse, + GetOrderStatusParams, + GetPayTradeHistoryParams, + GetPlanDetailsParams, + GetPortfolioMarginAssetIndexPriceResponse, + GetPortfolioMarginAssetLeverageResponse, + GetPortfolioMarginProAccountInfoResponse, + GetPortfolioMarginProBankruptcyLoanAmountResponse, + GetPortfolioMarginProCollateralRateResponse, + GetPortfolioMarginProInterestHistoryParams, + GetPortfolioMarginProInterestHistoryResponse, + GetRateHistory, + GetRateHistoryParams, + GetRwusdRateHistoryParams, + GetRwusdRedemptionHistoryParams, + GetRwusdRewardsHistoryParams, + GetRwusdSubscriptionHistoryParams, + GetSmallLiabilityExchangeHistoryParams, + GetSoftStakingProductListParams, + GetSoftStakingProductListResponse, + GetSoftStakingRewardsHistoryParams, + GetSoftStakingRewardsHistoryResponse, + GetSolStakingHistoryReq, + GetSourceAssetListParams, + GetSourceAssetListResponse, + GetSpotAlgoHistoricalOrdersParams, + GetSpotAlgoSubOrdersParams, + GetSpotAlgoSubOrdersResponse, + GetSpotRebateHistoryRecordsParams, + GetSpotRebateHistoryRecordsResponse, + GetStatisticListParams, + GetStatisticListResponse, + GetSubAccountDepositHistoryParams, + GetSubscriptionTransactionHistoryParams, + GetTargetAssetListParams, + GetTargetAssetListResponse, + GetTargetAssetROIParams, + GetTravelRuleDepositHistoryParams, + GetTravelRuleRegionListParams, + GetTravelRuleWithdrawHistoryParams, + GetTravelRuleWithdrawHistoryV2Params, + GetUniversalTransferBrokerParams, + GetVipLoanFixedRateMarketParams, + GetVipLoanOngoingOrdersParams, + GetVipLoanRepaymentHistoryParams, + GetWbethRewardsHistoryResponse, + GetWrapHistoryParams, + HistoricalAlgoOrder, + HistoricalBlockTradesParams, + HistoricalDataLink, + HistoricalSpotAlgoOrder, + IndexLinkedPlanRedemptionRecord, + InstitutionalLoanBorrowParams, + InstitutionalLoanBorrowResponse, + InstitutionalLoanInterestHistoryResponse, + InstitutionalLoanMaxBorrowableResponse, + InstitutionalLoanRepayParams, + InstitutionalLoanRepayResponse, + InstitutionalLoanRiskUnitDetails, + InstitutionalLoanRiskUnitTransferParams, + IsolatedMarginAccountInfo, + IsolatedMarginAccountTransferParams, + IsolatedMarginFeeData, + IsolatedMarginSymbol, + IsolatedMarginTierData, + LeftDailyPurchaseQuotaFlexibleProductResponse, + LiabilityCoinLeverageBracket, + LoanableAssetData, + LoanBorrowHistory, + LoanLTVAdjustmentHistory, + LoanOngoingOrder, + LoanRepaymentHistory, + LockedRedemptionRecord, + LockedSubscriptionPreview, + LockedSubscriptionRecord, + ManagedSubAccountDepositAddress, + ManagedSubAccountDepositAddressParams, + ManagedSubAccountFuturesAssetsResponse, + ManagedSubAccountListParams, + ManagedSubAccountMarginAssetsResponse, + ManagedSubAccountSnapshot, + ManagedSubAccountSnapshotParams, + ManagedSubAccountTransferLogParams, + ManagedSubAccountTransferTTLogParams, + ManagerSubTransferHistoryVos, + ManagerSubUserInfoVo, + ManualLiquidationParams, + ManualLiquidationResponse, + MarginAccountLoanParams, + MarginAccountRecord, + MarginAvailableInventoryResponse, + MarginCapitalFlow, + MarginDelistSchedule, + MarginInterestHistory, + MarginInterestRateHistory, + MarginInterestRebateBalanceRecordsResponse, + MarginInterestRebateBalanceResponse, + MarginLiquidationLoan, + MarginLiquidationLoanRepayHistoryResponse, + MarginLiquidationLoanRepayResponse, + MarginOpenOTOOrderList, + MarginOrderCountUsageResponse, + MarginOTOCOOrder, + MarginOTOOrder, + MarginTransactionResponse, + NewFutureAccountTransferParams, + NewOrderListOPOCOParams, + NewOrderListOPOCOResponse, + NewOrderListOPOParams, + NewOrderListOPOResponse, + NewOrderListOTOCOParams, + NewOrderListOTOCOResponse, + NewOrderListOTOParams, + NewOrderListOTOResponse, + NewSpotOrderParams, + NewSpotSOROrderParams, + NextHourlyInterestRate, + NftAsset, + NftDeposit, + NftTransaction, + NftWithdraw, + OnchainYieldsAccountResponse, + OnchainYieldsLockedPersonalLeftQuotaParams, + OnchainYieldsLockedPersonalLeftQuotaResponse, + OnchainYieldsLockedPositionParams, + OnchainYieldsLockedPositionResponse, + OnchainYieldsLockedProductListParams, + OnchainYieldsLockedProductListResponse, + OnchainYieldsLockedRedeemParams, + OnchainYieldsLockedRedeemResponse, + OnchainYieldsLockedRedemptionRecordParams, + OnchainYieldsLockedRedemptionRecordResponse, + OnchainYieldsLockedRewardsHistoryParams, + OnchainYieldsLockedRewardsHistoryResponse, + OnchainYieldsLockedSetAutoSubscribeParams, + OnchainYieldsLockedSetAutoSubscribeResponse, + OnchainYieldsLockedSetRedeemOptionParams, + OnchainYieldsLockedSetRedeemOptionResponse, + OnchainYieldsLockedSubscribeParams, + OnchainYieldsLockedSubscribeResponse, + OnchainYieldsLockedSubscriptionPreviewParams, + OnchainYieldsLockedSubscriptionPreviewResponse, + OnchainYieldsLockedSubscriptionRecordParams, + OnchainYieldsLockedSubscriptionRecordResponse, + OrderBookResponse, + OrderList, + OrderListResponse, + OrderRateLimitUsage, + OrderResponseTypeFor, + PMProBankruptcyLoanRepaymentHistory, + PMProMintBFUSDParams, + PMProMintBFUSDResponse, + PMProRedeemBFUSDResponse, + PortfolioDeltaModeStatus, + PortfolioMarginMarginCallLevelDeleteResponse, + PortfolioMarginMarginCallLevelGetResponse, + PortfolioMarginMarginCallLevelResponse, + PortfolioMarginProAccountBalance, + PortfolioMarginProSpanAccountInfo, + PreventedMatch, + PreventedMatchesParams, + PurchaseFlexibleProductResponse, + PurchaseRecordParams, + QueryBrokerFuturesCommissionRebateParams, + QueryBrokerSpotCommissionRebateParams, + QueryCrossMarginAccountDetailsParams, + QueryCrossMarginFeeDataParams, + QueryCrossMarginPairResponse, + QueryIsolatedMarginTierDataParams, + QueryMarginAccountAllOCOParams, + QueryMarginAccountTradeListParams, + QueryMarginAssetResponse, + QueryMarginInterestRateHistoryParams, + QueryMarginOpenOTOOrderListsParams, + QueryMarginPriceIndexResponse, + QueryMarginRecordParams, + QueryMaxBorrowResponse, + QueryMaxTransferOutAmountResponse, + QuerySubAccountCoinFuturesCommissionParams, + QuerySubAccountFuturesAssetInfoParams, + QuerySubAccountFuturesCommissionParams, + QuerySubAccountSpotMarginAssetInfoParams, + RawAccountTrade, + RawTrade, + RedeemBlvtParams, + RedeemBlvtResponse, + RedeemEthParams, + RedeemEthResponse, + RedeemGiftCardParams, + RedeemSolResponse, + RemoveBSwapLiquidityParams, + RepayCryptoFlexibleLoanParams, + RepayCryptoFlexibleLoanResponse, + RepayCryptoLoanFlexibleWithCollateralParams, + RepayCryptoLoanFlexibleWithCollateralResponse, + RepayCryptoLoanParams, + RepayCryptoLoanResponse, + RepayMarginLiquidationLoanParams, + ReplaceSpotOrderParams, + ReplaceSpotOrderResultSuccess, + RollingWindowTickerParams, + RwusdAccountResponse, + RwusdQuotaResponse, + RwusdRateHistoryRow, + RwusdRedeemParams, + RwusdRedeemResponse, + RwusdRedemptionHistoryRow, + RwusdRewardsHistoryRow, + RwusdSubscribeParams, + RwusdSubscribeResponse, + RwusdSubscriptionHistoryRow, + SetAutoSubscribeParams, + SetPortfolioMarginMarginCallLevelParams, + SetSoftStakingParams, + SetSoftStakingResponse, + SimpleEarnAccountResponse, + SimpleEarnFlexibleProduct, + SimpleEarnFlexibleProductPositionParams, + SimpleEarnLockedProduct, + SimpleEarnLockedProductPosition, + SimpleEarnLockedProductPositionParams, + SimpleEarnProductListParams, + SimpleEarnRedeemFlexibleProductParams, + SimpleEarnRedeemResponse, + SimpleEarnSubscribeFlexibleProductResponse, + SimpleEarnSubscribeLockedProductResponse, + SimpleEarnSubscribeProductParams, + SmallLiabilityExchangeCoin, + SmallLiabilityExchangeHistory, + SolBoostRewardsHistoryRecord, + SolBoostRewardsHistoryReq, + SolRedemptionHistoryRecord, + SolStakingAccount, + SolStakingHistoryRecord, + SolStakingQuota, + SOROrderResponseFull, + SORTestOrderResponse, + SpecialLowLatencyKeyInfo, + SpecialLowLatencyKeyResponse, + SpotAlgoOrder, + SpotAmendKeepPriorityResult, + SpotAssetTag, + SpotAssetTagsParams, + SpotExecutionRulesParams, + SpotExecutionRulesResponse, + SpotOrder, + SpotReferencePriceCalculationResponse, + SpotReferencePriceResult, + StakingBasicParams, + StakingHistory, + StakingHistoryParams, + StakingPersonalLeftQuota, + StakingProduct, + StakingProductPosition, + StakingProductType, + SubAccountAddOrDeleteIPList, + SubAccountAssetDetails, + SubAccountAssets, + SubAccountAssetsParams, + SubaccountBalances, + SubAccountBrokerMarginAsset, + SubaccountBrokerSpotAsset, + SubAccountCOINMDetail, + SubAccountCOINMPositionRisk, + SubAccountCOINMSummary, + SubAccountDeposit, + SubAccountDepositAddress, + SubAccountDepositAddressParams, + SubAccountDepositHistoryList, + SubAccountDepositHistoryParams, + SubAccountEnableFutures, + SubAccountEnableLeverageToken, + SubAccountEnableMargin, + SubAccountEnableOrDisableIPRestriction, + SubAccountFuturesAccountDetail, + SubAccountFuturesAccountSummary, + SubAccountFuturesAssetTransfer, + SubAccountFuturesAssetTransferHistory, + SubAccountFuturesAssetTransferHistoryParams, + SubAccountFuturesAssetTransferParams, + SubAccountListParams, + SubAccountListResponse, + SubAccountMarginAccountDetail, + SubAccountMovePosition, + SubAccountMovePositionHistory, + SubAccountMovePositionHistoryParams, + SubAccountMovePositionParams, + SubAccountsMarginAccountSummary, + SubAccountSpotAssetsSummary, + SubAccountSpotAssetsSummaryParams, + SubAccountSpotAssetTransferHistory, + SubAccountSpotAssetTransferHistoryParams, + SubAccountStatus, + SubAccountSummaryOnFuturesAccountV2Params, + SubAccountTransactionStatistics, + SubAccountTransfer, + SubAccountTransferHistory, + SubAccountTransferHistoryParams, + SubAccountTransferParams, + SubAccountTransferToMasterParams, + SubAccountTransferToSameMasterParams, + SubAccountUniversalTransfer, + SubAccountUniversalTransferHistoryParams, + SubAccountUniversalTransferHistoryResponse, + SubAccountUniversalTransferParams, + SubAccountUSDMDetail, + SubAccountUSDMPositionRisk, + SubAccountUSDMSummary, + SubmitConvertLimitOrderParams, + SubmitDepositCreditParams, + SubmitDepositCreditResponse, + SubmitHashrateResaleParams, + SubmitIndexLinkedPlanRedemptionParams, + SubmitMarginOTOCOOrderParams, + SubmitMarginOTOOrderParams, + SubmitOneTimeTransactionParams, + SubmitOneTimeTransactionResponse, + SubmitSpotTwapNewOrderParams, + SubmitSpotTwapNewOrderResponse, + SubmitTravelRuleDepositQuestionnaireParams, + SubmitTravelRuleDepositQuestionnaireResponse, + SubmitTwapNewOrderParams, + SubmitTwapNewOrderResponse, + SubmitVpNewOrderParams, + SubmitVpNewOrderResponse, + SubscribeBlvtParams, + SubscribeBlvtResponse, + SubscribeDualInvestmentProductParams, + SubscribeDualInvestmentProductResponse, + SubscribeEthStakingV2Response, + SubscribeSolStakingResponse, + SwitchPortfolioDeltaModeParams, + SymbolOrderBookTicker, + SymbolTradeFee, + SystemStatusResponse, + TargetAssetROI, + Ticker24hrResponse, + ToggleBNBBurnParams, + TradingDayTickerArray, + TradingDayTickerFull, + TradingDayTickerMini, + TradingDayTickerParams, + TradingDayTickerSingle, + TransferBrokerSubAccount, + TransferBrokerSubAccountParams, + TravelRuleCountryListResponse, + TravelRuleDepositHistoryRecord, + TravelRuleRegionListResponse, + TravelRuleWithdrawHistoryRecord, + UniversalTransferBrokerParams, + UniversalTransferHistoryParams, + UniversalTransferParams, + UpdateIpRestrictionForSubApiKey, + UsdtMarginedFuturesResponse, + UserAsset, + VASPInfo, + VipCollateralAccount, + VipLoanAccruedInterestParams, + VipLoanAccruedInterestRecord, + VipLoanBorrowParams, + VipLoanBorrowResponse, + VipLoanFixedRateBorrowParams, + VipLoanFixedRateBorrowResponse, + VipLoanFixedRateMarketRecord, + VipLoanInterestRateHistoryParams, + VipLoanInterestRateRecord, + VipLoanRenewParams, + VipLoanRenewResponse, + VipLoanRepaymentHistory, + VipLoanRepayParams, + VipLoanRepayResponse, + VipOngoingOrder, + VirtualSubAccount, + WalletBalance, + WithdrawAddress, + WithdrawAssetsFromManagedSubAccountParams, + WithdrawFiatParams, + WithdrawHistory, + WithdrawHistoryParams, + WithdrawParams, + WithdrawTravelRuleParams, + WrapBethResponse, + WrapHistory, +} from './types/spot'; +import BaseRestClient from './util/BaseRestClient'; +import { + generateNewOrderId, + getOrderIdPrefix, + getServerTimeEndpoint, + logInvalidOrderId, + RestClientOptions, + serialiseParams, +} from './util/requestUtils'; ⋮---- -export interface PurchaseFlexibleProductParams { - productId: string; - amount: number; - autoSubscribe: boolean; -} +export class MainClient extends BaseRestClient ⋮---- -export interface PurchaseFlexibleProductResponse { - purchaseId: number; -} +constructor( + restClientOptions: RestClientOptions = {}, + requestOptions: AxiosRequestConfig = {}, +) ⋮---- -export interface RedeemFlexibleProductParams { - productId: string; - amount: number; - type: 'FAST' | 'NORMAL'; -} +/** + * 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 ⋮---- -export interface LeftDailyPurchaseQuotaFlexibleProductResponse { - asset: string; - leftQuota: string; -} +// Adjust server time by adding estimated one-way latency ⋮---- -export type ProjectStatus = 'ALL' | 'SUBSCRIBABLE' | 'UNSUBSCRIBABLE'; -export type ProjectType = 'ACTIVITY' | 'CUSTOMIZED_FIXED'; -export type ProjectSortBy = - | 'START_TIME' - | 'LOT_SIZE' - | 'INTEREST_RATE' - | 'DURATION'; +// Calculate time difference between adjusted server time and local time ⋮---- -export interface FixedAndActivityProjectParams { - asset?: string; - type: ProjectType; - status?: ProjectStatus; - isSortAsc?: boolean; - sortBy?: ProjectSortBy; - current?: number; - size?: number; -} -export interface FixedAndActivityProjectPositionParams { - asset?: string; - projectId?: string; - status?: StakingStatus; -} +/** + * Abstraction required by each client to aid with time sync / drift handling + */ +async getServerTime(baseUrlKeyOverride?: BinanceBaseUrlKey): Promise ⋮---- -export type LendingType = 'DAILY' | 'ACTIVITY' | 'CUSTOMIZED_FIXED'; +/** + * + * SPOT TRADING Endpoints - General endpoints + * + **/ ⋮---- -export interface PurchaseRecordParams { - lendingType: LendingType; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +testConnectivity(): Promise ⋮---- -export interface NewFutureAccountTransferParams { - asset: string; - amount: number; - type: 1 | 2 | 3 | 4; -} +getExchangeInfo(params?: ExchangeInfoParams): Promise ⋮---- -export interface GetFutureAccountTransferHistoryParams { - asset: string; - startTime: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * + * SPOT TRADING Endpoints - Market endpoints + * + **/ ⋮---- -export interface FutureAccountTransfer { - asset: string; - tranId: number; - amount: string; - type: string; - timestamp: number; - status: 'PENDING' | 'CONFIRMED' | 'FAILED'; -} +getOrderBook(params: OrderBookParams): Promise ⋮---- -export interface GetLoanCoinPaginatedHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getRecentTrades(params: RecentTradesParams): Promise ⋮---- -/** - * - * STAKING - * - */ +getHistoricalTrades(params: HistoricalTradesParams): Promise ⋮---- -export interface StakingHistory { - positionId: numberInString; - time: number; - asset: string; - project?: string; - amount: numberInString; - lockPeriod?: numberInString; - deliverDate?: numberInString; - type?: string; - status: string; -} +getHistoricalBlockTrades( + params: HistoricalBlockTradesParams, +): Promise ⋮---- -export interface StakingPersonalLeftQuota { - leftPersonalQuota: numberInString; -} +getAggregateTrades( + params: SymbolFromPaginatedRequestFromId, +): Promise ⋮---- -export interface StakingHistoryParams extends StakingBasicParams { - txnType: StakingTxnType; - asset?: string; - startTime?: number; - endTime?: number; -} -export interface BSwapOperationsParams { - operationId?: number; - poolId?: number; - operation: BSwapOperationType; - startTime?: number; - endTime?: number; - limit: number; -} +getKlines(params: KlinesParams): Promise ⋮---- -export interface BSwapOperations { - operationId: number; - poolId: number; - poolName: string; - operation: BSwapOperationType; - status: number; - updateTime: number; - shareAmount: numberInString; -} -export interface RemoveBSwapLiquidityParams { - poolId: number; - type: BSwapType; - asset?: string; - shareAmount: number; -} +getUIKlines(params: KlinesParams): Promise ⋮---- -export interface AddBSwapLiquidityParams { - poolId: number; - type?: BSwapType; - asset: string; - quantity: number; -} +getAvgPrice(params: ⋮---- -export interface BSwapShare { - shareAmount: number; - sharePercentage: number; - asset: { [k: string]: number }; -} +getExecutionRules( + params?: SpotExecutionRulesParams, +): Promise ⋮---- -export interface BSwapLiquidity { - poolId: number; - poolNmae: string; - updateTime: number; - liquidity: { [k: string]: number }; - share: BSwapShare; -} +getReferencePrice(params: { + symbol: string; +}): Promise ⋮---- -export interface FundingAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - btcValuation: string; -} +getReferencePriceCalculation(params: { + symbol: string; + symbolStatus?: 'TRADING' | 'HALT' | 'BREAK'; +}): Promise ⋮---- -export interface GetAssetParams { - asset?: string; - needBtcValuation?: boolean; -} +get24hrChangeStatistics(params?: { + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; ⋮---- -export interface UserAsset { - asset: string; - free: string; - locked: string; - freeze: string; - withdrawing: string; - ipoable: string; - btcValuation: string; -} +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -export interface SpotAssetTagsParams { - tag?: string; -} +get24hrChangeStatistics(params: { + symbol: string; // use for single symbol + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; + }): Promise; ⋮---- -export interface SpotAssetTag { - assetCode: string; - assetName: string; - trading: boolean; - tags: string[]; -} +symbol: string; // use for single symbol +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -export interface ConvertTransfer { - clientTranId: string; - asset: string; - amount: number; - targetAsset: string; - accountType?: string; -} +get24hrChangeStatistics(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + type?: 'FULL' | 'MINI'; // default is FULL + symbolStatus?: string; +}): Promise ⋮---- -export interface ConvertTransferResponse { - tranId: number; - status: string; -} +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols +type?: 'FULL' | 'MINI'; // default is FULL ⋮---- -export interface GetConvertBUSDHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - accountType?: string; - current?: number; - size?: number; -} +getTradingDayTicker( + params: TradingDayTickerParams, +): Promise ⋮---- -export interface BUSDConversionRecord { - tranId: number; - type: number; - time: number; - deductedAsset: string; - deductedAmount: string; - targetAsset: string; - targetAmount: string; - status: string; - accountType: string; -} +getSymbolPriceTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise ⋮---- -export interface CloudMiningHistoryParams { - tranId?: number; - clientTranId?: string; - asset?: string; - startTime: number; - endTime: number; - current?: number; - size?: number; -} +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols ⋮---- -export interface CloudMining { - createTime: number; - tranId: number; - type: number; - asset: string; - amount: string; - status: string; -} +getSymbolOrderBookTicker(params?: { + symbol?: string; // use for single symbol + symbols?: string[]; // use for multiple symbols + symbolStatus?: string; +}): Promise ⋮---- -export interface ConvertibleCoinsResponse { - convertEnabled: boolean; - coins: string[]; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exchangeRates: any; -} +symbol?: string; // use for single symbol +symbols?: string[]; // use for multiple symbols ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +getRollingWindowTicker( + params: RollingWindowTickerParams, +): Promise ⋮---- -export interface ConvertibleCoinsParams { - coin: string; - enable: boolean; -} +/** + * + * SPOT TRADING Endpoints - Trading endpoints + * + **/ ⋮---- -export interface SubmitDepositCreditParams { - depositId?: number; - txId?: string; - subAccountId?: number; - subUserId?: number; -} +submitNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> ⋮---- -export interface SubmitDepositCreditResponse { - code: string; - message: string; - data: boolean; - success: boolean; -} +testNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise ⋮---- -export interface DepositAddressListParams { - coin: string; - network?: string; -} +getOrder(params: GetOrderParams): Promise ⋮---- -export interface DepositAddress { - coin: string; - address: string; - tag: string; - isDefault: number; -} +cancelOrder(params: CancelOrderParams): Promise ⋮---- -export interface WalletBalance { - activate: boolean; - balance: string; - walletName: string; -} +cancelAllSymbolOrders(params: { + symbol: string; +}): Promise ⋮---- -export interface DelegationHistoryParams { - email: string; - startTime: number; - endTime: number; - type?: 'Delegate' | 'Undelegate'; - asset?: string; - current?: number; - size?: number; -} +replaceOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, + >( + params: ReplaceSpotOrderParams, +): Promise> +⋮---- +/** + * Reduce the quantity of an existing open order while keeping its priority in the order book. + * The new quantity must be less than the current quantity. + * https://binance-docs.github.io/apidocs/futures/en/#order-amend-keep-priority-trade + */ +amendOrderKeepPriority( + params: AmendKeepPriorityParams, +): Promise +⋮---- +getOpenOrders(params?: +⋮---- +getAllOrders(params: GetAllOrdersParams): Promise +⋮---- +/** + * @deprecated + */ +submitNewOCO(params: NewOCOParams): Promise ⋮---- -export interface DelegationHistory { - clientTranId: string; - transferType: 'Delegate' | 'Undelegate'; - asset: string; - amount: string; - time: number; -} +submitNewOrderList( + params: NewOrderListParams, +): Promise> ⋮---- -export interface DelistScheduleResponse { - delistTime: number; - symbols: string[]; -} +submitNewOrderListOTO( + params: NewOrderListOTOParams, +): Promise ⋮---- -export interface WithdrawAddress { - address: string; - addressTag: string; - coin: string; - name: string; - network: string; - origin: string; - originType: string; - whiteStatus: boolean; -} +submitNewOrderListOTOCO( + params: NewOrderListOTOCOParams, +): Promise ⋮---- -export interface AccountInfo { - vipLevel: number; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isOptionsEnabled: boolean; - isPortfolioMarginRetailEnabled: boolean; -} +submitNewOrderListOPO( + params: NewOrderListOPOParams, +): Promise ⋮---- -export interface ManagedSubAccountSnapshotParams { - email: string; - type: 'SPOT' | 'MARGIN' | 'FUTURES'; - startTime?: number; - endTime?: number; - limit?: number; -} +submitNewOrderListOPOCO( + params: NewOrderListOPOCOParams, +): Promise ⋮---- -export interface SubaccountBalances { - asset: string; - free: string; - locked: string; -} +cancelOCO(params: CancelOCOParams): Promise ⋮---- -export interface SubaccountUserAssets { - asset: string; - borrowed: string; - free: string; - interest: string; - locked: string; - netAsset: string; -} +getOCO(params?: GetOCOParams): Promise ⋮---- -export interface SubaccountAssets { - asset: string; - marginBalance: string; - walletBalance: string; -} +getAllOCO(params?: BasicFromPaginatedParams): Promise ⋮---- -export interface SubaccountPosition { - entryPrice: string; - markPrice: string; - positionAmt: string; - symbol: string; - unRealizedProfit: string; -} +/** + * Query open OCO + */ +getAllOpenOCO(): Promise ⋮---- -export interface ManagedSubAccountSnapshot { - code: number; - msg: string; - snapshotVos: { - data: { - balances?: SubaccountBalances[]; - totalAssetOfBtc?: string; - marginLevel?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - userAssets?: SubaccountUserAssets[]; - assets?: SubaccountAssets[]; - position?: SubaccountPosition[]; - }; - type: string; - updateTime: number; - }[]; -} +/** + * Places an order using smart order routing (SOR). + */ +submitNewSOROrder( + params: NewSpotSOROrderParams, +): Promise ⋮---- -export interface ManagedSubAccountTransferLogParams { - email: string; - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: 'from' | 'to'; - transferFunctionAccountType?: - | 'SPOT' - | 'MARGIN' - | 'ISOLATED_MARGIN' - | 'USDT_FUTURE' - | 'COIN_FUTURE'; -} +/** + * Test new order creation and signature/recvWindow using smart order routing (SOR). + * Creates and validates a new order but does not send it into the matching engine. + */ +testNewSOROrder( + params: NewSpotSOROrderParams & { computeCommissionRates?: boolean }, +): Promise ⋮---- -export interface ManagerSubTransferHistoryVos { - fromEmail: string; - fromAccountType: string; - toEmail: string; - toAccountType: string; - asset: string; - amount: string; - scheduledData: number; - createTime: number; - status: string; - tranId: number; -} +/** + * + * SPOT TRADING Endpoints - Account endpoints + * + **/ ⋮---- -export interface ManagedSubAccountFuturesAssetsResponse { - code: string; - message: string; - snapshotVos: { - type: string; - updateTime: number; - data: { - assets: SubaccountAssets[]; - position: SubaccountPosition[]; - }; - }[]; -} +/** + * Get current account information + */ +getAccountInformation(params?: { + omitZeroBalances?: boolean; +}): Promise ⋮---- -export interface ManagedSubAccountMarginAssetsResponse { - marginLevel: string; - totalAssetOfBtc: string; - totalLiabilityOfBtc: string; - totalNetAssetOfBtc: string; - userAssets: SubaccountUserAssets[]; -} +getAccountTradeList( + params: SymbolFromPaginatedRequestFromId & { orderId?: number }, +): Promise ⋮---- -export interface ManagedSubAccountListParams { - email?: string; - page?: number; - limit?: number; -} +getOrderRateLimit(): Promise ⋮---- -export interface ManagerSubUserInfoVo { - rootUserId: number; - managersubUserId: number; - bindParentUserId: number; - email: string; - insertTimeStamp: number; - bindParentEmail: string; - isSubUserEnabled: boolean; - isUserActive: boolean; - isMarginEnabled: boolean; - isFutureEnabled: boolean; - isSignedLVTRiskAgreement: boolean; -} +getPreventedMatches( + params: PreventedMatchesParams, +): Promise ⋮---- -export interface SubaccountTradeInfoVos { - userId: number; - btc: number; - btcFutures: number; - btcMargin: number; - busd: number; - busdFutures: number; - busdMargin: number; - date: number; -} -export interface SubAccountTransactionStatistics { - recent30BtcTotal: string; - recent30BtcFuturesTotal: string; - recent30BtcMarginTotal: string; - recent30BusdTotal: string; - recent30BusdFuturesTotal: string; - recent30BusdMarginTotal: string; - tradeInfoVos: SubaccountTradeInfoVos[]; -} +getAllocations(params: AllocationsParams): Promise ⋮---- -export interface ManagedSubAccountDepositAddressParams { - email: string; - coin: string; - network?: string; -} +getCommissionRates(params: ⋮---- -export interface ManagedSubAccountDepositAddress { - coin: string; - address: string; - tag: string; - url: string; -} +/** + * + * MARGIN TRADING Endpoints - Market Data endpoints + * + **/ ⋮---- -export interface EnableOptionsForSubAccountResponse { - email: string; - isEOptionsEnabled: boolean; -} +getCrossMarginCollateralRatio(): Promise< + { + collaterals: Collateral[]; + assetNames: string[]; + }[] + > { + return this.getPrivate('sapi/v1/margin/crossMarginCollateralRatio'); ⋮---- -export interface ManagedSubAccountTransferTTLogParams { - startTime: number; - endTime: number; - page: number; - limit: number; - transfers?: string; - transferFunctionAccountType?: string; -} +getAllCrossMarginPairs(): Promise +⋮---- +getIsolatedMarginAllSymbols(params?: { + symbol?: string; +}): Promise ⋮---- -export interface UIKlinesParams { - symbol: string; - interval: string; - startTime?: number; - endTime?: number; - timeZone?: string; - limit?: number; -} +getAllMarginAssets(): Promise ⋮---- -export interface Ticker24hrFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - prevClosePrice: string; - lastPrice: string; - lastQty: string; - bidPrice: string; - bidQty: string; - askPrice: string; - askQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} +getMarginDelistSchedule(): Promise ⋮---- -export interface Ticker24hrMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} +getIsolatedMarginTierData( + params: QueryIsolatedMarginTierDataParams, +): Promise ⋮---- -export type Ticker24hrResponse = Ticker24hrFull | Ticker24hrMini; +queryMarginPriceIndex( + params: BasicSymbolParam, +): Promise ⋮---- -export interface TradingDayTickerParams { - symbol?: string; - symbols?: string[]; - timeZone?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +getMarginAvailableInventory(params: { + type: string; +}): Promise ⋮---- -export interface TradingDayTickerFull { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} +getLeverageBracket(): Promise ⋮---- -export interface TradingDayTickerMini { - symbol: string; - openPrice: string; - highPrice: string; - lowPrice: string; - lastPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} +/** + * + * MARGIN TRADING Endpoints - Borrow and Repay endpoints + * + **/ ⋮---- -export type TradingDayTickerSingle = - | TradingDayTickerFull - | TradingDayTickerMini; +getNextHourlyInterestRate( + params: GetNextHourlyInterestRateParams, +): Promise ⋮---- -export type TradingDayTickerArray = - | TradingDayTickerFull[] - | TradingDayTickerMini[]; +getMarginInterestHistory(params: GetMarginInterestHistoryParams): Promise< ⋮---- -export interface RollingWindowTickerParams { - symbol?: string; - symbols?: string[]; - windowSize?: string; - type?: 'FULL' | 'MINI'; - symbolStatus?: string; -} +submitMarginAccountBorrowRepay( + params: MarginAccountLoanParams, +): Promise ⋮---- -export interface NewOrderListOTOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingQuantity: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; -} +getMarginAccountBorrowRepayRecords( + params: GetMarginAccountBorrowRepayRecordsParams, +): Promise< ⋮---- -export interface NewOrderListOTOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} +getMarginInterestRateHistory( + params: QueryMarginInterestRateHistoryParams, +): Promise ⋮---- -export interface NewOrderListOTOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESPONSE'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; -} +queryMaxBorrow( + params: BasicMarginAssetParams, +): Promise ⋮---- -export interface NewOrderListOTOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} +/** + * + * MARGIN TRADING Endpoints - Trade endpoints + * + **/ ⋮---- -export interface NewOrderListOPOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'FOK' | 'IOC' | 'GTC'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingType: string; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: string; - pendingStopPrice?: string; - pendingTrailingDelta?: string; - pendingIcebergQty?: string; - pendingTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingStrategyId?: number; - pendingStrategyType?: number; - pendingPegPriceType?: string; - pendingPegOffsetType?: string; - pendingPegOffsetValue?: number; -} +getMarginForceLiquidationRecord( + params: GetForceLiquidationRecordParams, +): Promise< ⋮---- -export interface NewOrderListOPOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} +getSmallLiabilityExchangeCoins(): Promise ⋮---- -export interface NewOrderListOPOCOParams { - symbol: string; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'FULL' | 'RESULT'; - selfTradePreventionMode?: string; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - workingStrategyId?: number; - workingStrategyType?: number; - workingPegPriceType?: string; - workingPegOffsetType?: string; - workingPegOffsetValue?: number; - pendingSide: 'BUY' | 'SELL'; - pendingAboveType: - | 'STOP_LOSS_LIMIT' - | 'STOP_LOSS' - | 'LIMIT_MAKER' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingAboveStrategyId?: number; - pendingAboveStrategyType?: number; - pendingAbovePegPriceType?: string; - pendingAbovePegOffsetType?: string; - pendingAbovePegOffsetValue?: number; - pendingBelowType?: - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'FOK' | 'IOC'; - pendingBelowStrategyId?: number; - pendingBelowStrategyType?: number; - pendingBelowPegPriceType?: string; - pendingBelowPegOffsetType?: string; - pendingBelowPegOffsetValue?: number; -} +getSmallLiabilityExchangeHistory( + params: GetSmallLiabilityExchangeHistoryParams, +): Promise< ⋮---- -export interface NewOrderListOPOCOResponse { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty?: string; - executedQty: string; - origQuoteOrderQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - stopPrice?: string; - workingTime: number; - selfTradePreventionMode: string; - }[]; -} +marginAccountCancelOpenOrders( + params: BasicSymbolParam, +): Promise ⋮---- -export interface OrderRateLimitUsage { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} +marginAccountCancelOCO(params: CancelOCOParams): Promise ⋮---- -export interface PreventedMatchesParams { - symbol: string; - preventedMatchId?: number; - orderId?: number; - fromPreventedMatchId?: number; - limit?: number; -} +marginAccountCancelOrder( + params: CancelOrderParams, +): Promise ⋮---- -export interface PreventedMatch { - symbol: string; - preventedMatchId: number; - takerOrderId: number; - makerSymbol: string; - makerOrderId: number; - tradeGroupId: number; - selfTradePreventionMode: SelfTradePreventionMode; - price: string; - makerPreventedQuantity: string; - transactTime: number; -} +marginAccountNewOCO(params: NewOCOParams): Promise ⋮---- -export interface AllocationsParams { - symbol: string; - startTime?: number; - endTime?: number; - fromAllocationId?: number; - limit?: number; - orderId?: number; -} +marginAccountNewOrder< + T extends OrderType, + RT extends OrderResponseType | undefined = undefined, +>(params: NewSpotOrderParams): Promise> ⋮---- -export interface Allocation { - symbol: string; - allocationId: number; - allocationType: string; - orderId: number; - orderListId: number; - price: string; - qty: string; - quoteQty: string; - commission: string; - commissionAsset: string; - time: number; - isBuyer: boolean; - isMaker: boolean; - isAllocator: boolean; -} +getMarginOrderCountUsage( + params: GetMarginOrderCountUsageParams, +): Promise ⋮---- -export interface CommissionRates { - symbol: string; - standardCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - taxCommission: { - maker: string; - taker: string; - buyer: string; - seller: string; - }; - discount: { - enabledForAccount: boolean; - enabledForSymbol: boolean; - discountAsset: string; - /** - * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). - * `0.75` means pay 75% of the standard commission. It is not a reduction rate. - * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. - * Does not apply to tax or special commission. - */ - discount: string; - }; -} +queryMarginAccountAllOCO( + params: QueryMarginAccountAllOCOParams, +): Promise +⋮---- +queryMarginAccountAllOrders( + params: GetAllOrdersParams, +): Promise ⋮---- -/** - * Multiplier on standard commission when paying in `discountAsset` (`GET /api/v3/account/commission`). - * `0.75` means pay 75% of the standard commission. It is not a reduction rate. - * Staff confirmed this on binance.vision. The FAQ example `0.25` is fictional. - * Does not apply to tax or special commission. - */ +queryMarginAccountOCO(params: GetOCOParams): Promise ⋮---- -export interface GetCrossMarginTransferHistoryParams { - asset?: string; - type?: 'ROLL_IN' | 'ROLL_OUT'; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - isolatedSymbol?: string; -} +queryMarginAccountOpenOCO(params: { + isIsolated?: 'TRUE' | 'FALSE'; + symbol?: string; +}): Promise ⋮---- -export interface CrossMarginTransferHistory { - amount: string; - asset: string; - status: string; - timestamp: number; - txId: number; - type: 'ROLL_IN' | 'ROLL_OUT'; - transFrom?: string; - transTo?: string; - fromSymbol?: string; - toSymbol?: string; -} +queryMarginAccountOpenOTOOrderLists( + params: QueryMarginOpenOTOOrderListsParams, +): Promise ⋮---- -export interface GetMarginInterestHistoryParams { - asset?: string; - isolatedSymbol?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +queryMarginAccountOpenOrders(params: BasicSymbolParam): Promise ⋮---- -export interface MarginInterestHistory { - txId: number; - interestAccuredTime: number; - asset: string; - rawAsset?: string; - principal: string; - interest: string; - interestRate: string; - type: - | 'PERIODIC' - | 'ON_BORROW' - | 'PERIODIC_CONVERTED' - | 'ON_BORROW_CONVERTED' - | 'PORTFOLIO'; - isolatedSymbol?: string; -} +queryMarginAccountOrder(params: GetOrderParams): Promise ⋮---- -export interface GetForceLiquidationRecordParams { - startTime?: number; - endTime?: number; - isolatedSymbol?: string; - current?: number; - size?: number; -} +queryMarginAccountTradeList( + params: QueryMarginAccountTradeListParams, +): Promise ⋮---- -export interface ForceLiquidationRecord { - avgPrice: string; - executedQty: string; - orderId: number; - price: string; - qty: string; - side: 'BUY' | 'SELL'; - symbol: string; - timeInForce: string; - isIsolated: boolean; - updatedTime: number; -} +submitSmallLiabilityExchange(params: ⋮---- -export interface QueryMarginAccountAllOCOParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +submitManualLiquidation( + params: ManualLiquidationParams, +): Promise ⋮---- -export interface QueryMarginAccountTradeListParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - orderId?: number; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} +/** + * Post a new OTO order for margin account + */ +submitMarginOTOOrder( + params: SubmitMarginOTOOrderParams, +): Promise ⋮---- -export interface IsolatedMarginSymbol { - base: string; - isBuyAllowed: boolean; - isMarginTrade: boolean; - isSellAllowed: boolean; - quote: string; - symbol: string; - delistTime?: number; -} +/** + * Submit a new OTOCO order for margin account + */ +submitMarginOTOCOOrder( + params: SubmitMarginOTOCOOrderParams, +): Promise ⋮---- -export interface ToggleBNBBurnParams { - spotBNBBurn?: 'true' | 'false'; - interestBNBBurn?: 'true' | 'false'; -} +/** + * Create a special key for low-latency trading (VIP 4+ only) + */ +createMarginSpecialLowLatencyKey( + params: CreateSpecialLowLatencyKeyParams, +): Promise ⋮---- -export interface BNBBurnResponse { - spotBNBBurn: boolean; - interestBNBBurn: boolean; -} +deleteMarginSpecialLowLatencyKey(params?: { + apiKey?: string; + apiName?: string; + symbol?: string; +}): Promise ⋮---- -export interface QueryMarginInterestRateHistoryParams { - asset: string; - vipLevel?: number; - startTime?: number; - endTime?: number; -} +updateMarginIPForSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; + ip: string; +}): Promise ⋮---- -export interface MarginInterestRateHistory { - asset: string; - dailyInterestRate: string; - timestamp: number; - vipLevel: number; -} +/** + * Query the list of special keys for low-latency trading + */ +getMarginSpecialLowLatencyKeys(params: { + symbol?: string; +}): Promise ⋮---- -export interface QueryCrossMarginFeeDataParams { - vipLevel?: number; - coin?: string; -} +/** + * Query information for a specific special key used in low-latency trading + */ +getMarginSpecialLowLatencyKey(params: { + apiKey: string; + symbol?: string; +}): Promise ⋮---- -export interface CrossMarginFeeData { - vipLevel: number; - coin: string; - transferIn: boolean; - borrowable: boolean; - dailyInterest: string; - yearlyInterest: string; - borrowLimit: string; - marginablePairs: string[]; -} +/** + * Query the current cross-margin liquidation loan status (bankruptcy deficit). + */ +getMarginLiquidationLoan(): Promise ⋮---- -export interface IsolatedMarginFeeData { - vipLevel: number; - symbol: string; - leverage: string; - data: { - coin: string; - dailyInterest: string; - borrowLimit: string; - }[]; -} +/** + * Repay an outstanding cross-margin liquidation loan from the spot wallet. + */ +repayMarginLiquidationLoan( + params: RepayMarginLiquidationLoanParams, +): Promise ⋮---- -export interface QueryIsolatedMarginTierDataParams { - symbol: string; - tier?: number; -} +/** + * Query cross-margin liquidation loan repayment history. + */ +getMarginLiquidationLoanRepayHistory( + params?: GetMarginLiquidationLoanRepayHistoryParams, +): Promise ⋮---- -export interface IsolatedMarginTierData { - symbol: string; - tier: number; - effectiveMultiple: string; - initialRiskRatio: string; - liquidationRiskRatio: string; - baseAssetMaxBorrowable: string; - quoteAssetMaxBorrowable: string; -} +/** + * Exit Margin Special Key mode for Cross Margin Classic accounts. + */ +exitMarginSpecialKeyMode(): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Transfer endpoints + * + **/ +⋮---- +getCrossMarginTransferHistory( + params: GetCrossMarginTransferHistoryParams, +): Promise> +⋮---- +queryMaxTransferOutAmount( + params: BasicMarginAssetParams, +): Promise +⋮---- +/** + * + * MARGIN TRADING Endpoints - Account endpoints + * + **/ +⋮---- +updateCrossMarginMaxLeverage(params: +⋮---- +disableIsolatedMarginAccount(params: ⋮---- -export interface GetMarginOrderCountUsageParams { - isIsolated?: string; - symbol?: string; -} +enableIsolatedMarginAccount(params: ⋮---- -export interface MarginOrderCountUsageResponse { - rateLimitType: string; - interval: string; - intervalNum: number; - limit: number; - count: number; -} +getBNBBurn(): Promise ⋮---- -export interface Collateral { - minUsdValue: string; - maxUsdValue?: string; - discountRate: string; -} +getMarginSummary(): Promise ⋮---- -export interface SmallLiabilityExchangeCoin { - asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; -} -export interface GetSmallLiabilityExchangeHistoryParams { - current: number; - size: number; - startTime?: number; - endTime?: number; -} +queryCrossMarginAccountDetails(): Promise ⋮---- -export interface SmallLiabilityExchangeHistory { - asset: string; - amount: string; - targetAsset: string; - targetAmount: string; - bizType: string; - timestamp: number; -} +getCrossMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise ⋮---- -export interface GetNextHourlyInterestRateParams { - assets: string; - isIsolated: boolean; -} +getIsolatedMarginAccountLimit(): Promise< ⋮---- -export interface NextHourlyInterestRate { - asset: string; - nextHourlyInterestRate: string; -} +getIsolatedMarginAccountInfo(params?: { + symbols?: string; +}): Promise ⋮---- -export interface GetMarginCapitalFlowParams { - asset?: string; - symbol?: string; - type?: string; - startTime?: number; - endTime?: number; - fromId?: number; - limit?: number; -} +getIsolatedMarginFeeData( + params: QueryCrossMarginFeeDataParams, +): Promise ⋮---- -export interface MarginCapitalFlow { - id: number; - tranId: number; - timestamp: number; - asset: string; - symbol: string; - type: string; - amount: string; -} +toggleBNBBurn(params: ToggleBNBBurnParams): Promise ⋮---- -export interface MarginDelistSchedule { - delistTime: number; - crossMarginAssets: string[]; - isolatedMarginSymbols: string[]; - updateTime: number; -} +/** + * Possibly @deprecated + * Only existing in old documentation, not in new documentation + */ +getMarginCapitalFlow( + params: GetMarginCapitalFlowParams, +): Promise ⋮---- -export interface MarginAvailableInventoryResponse { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - assets: any; - updateTime: number; -} +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryLoanRecord( + params: QueryMarginRecordParams, +): Promise< ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +/** + * @deprecated on 2024-01-09, use getMarginAccountBorrowRepayRecords() instead + */ +queryRepayRecord( + params: QueryMarginRecordParams, +): Promise< ⋮---- -export interface ManualLiquidationParams { - type: string; - symbol?: string; -} +/** + * @deprecated on 2024-01-09, use submitUniversalTransfer() instead + */ +isolatedMarginAccountTransfer( + params: IsolatedMarginAccountTransferParams, +): Promise ⋮---- -export interface ManualLiquidationResponse { - asset: string; - interest: string; - principal: string; - liabilityAsset: string; - liabilityQty: number; -} +/** + * + * WALLET Endpoints - Capital endpoints + * + **/ ⋮---- -export interface LeverageBracket { - leverage: number; - maxDebt: number; - maintenanceMarginRate: number; - initialMarginRate: number; - fastNum: number; -} +getBalances(): Promise ⋮---- -export interface LiabilityCoinLeverageBracket { - assetNames: string[]; - rank: number; - brackets: LeverageBracket[]; -} -export interface GetFlexibleSubscriptionRecordParams { - productId?: string; - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +withdraw(params: WithdrawParams): Promise< ⋮---- -export interface GetFlexibleSubscriptionRecordResponse { - amount: string; - asset: string; - time: number; - purchaseId: number; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; - status: string; -} +getWithdrawHistory( + params?: WithdrawHistoryParams, +): Promise ⋮---- -export interface GetLockedSubscriptionRecordParams { - purchaseId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getWithdrawAddresses(): Promise ⋮---- -export interface LockedSubscriptionRecord { - positionId: string; - purchaseId: number; - time: number; - asset: string; - amount: string; - lockPeriod: string; - type: string; - sourceAccount: string; - amtFromSpot?: string; - amtFromFunding?: string; - status: string; -} +getWithdrawQuota(): Promise< ⋮---- -export interface GetFlexibleRedemptionRecordParams { - productId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getDepositHistory(params?: DepositHistoryParams): Promise ⋮---- -export interface FlexibleRedemptionRecord { - amount: string; - asset: string; - time: number; - productId: string; - redeemId: number; - destAccount: string; - status: string; -} +getDepositAddress( + params: DepositAddressParams, +): Promise ⋮---- -export interface GetLockedRedemptionRecordParams { - positionId?: string; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getDepositAddresses( + params: DepositAddressListParams, +): Promise ⋮---- -export interface LockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; - deliverDate: string; - status: string; -} +submitDepositCredit( + params: SubmitDepositCreditParams, +): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +getAutoConvertStablecoins(): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + */ +setConvertibleCoins(params: ConvertibleCoinsParams): Promise +⋮---- +/** + * + * WALLET Endpoints - Asset endpoints + * + **/ +⋮---- +getAssetDetail( + params?: Partial, +): Promise> ⋮---- -export interface GetFlexibleRewardsHistoryParams { - productId?: string; - asset?: string; - startTime?: number; - endTime?: number; - type: 'BONUS' | 'REALTIME' | 'REWARDS' | 'ALL'; - current?: number; - size?: number; -} +getWalletBalances(params?: { + quoteAsset?: string; +}): Promise ⋮---- -export interface FlexibleRewardsHistory { - asset: string; - rewards: string; - projectId: string; - type: string; - time: number; -} +getUserAsset(params: GetAssetParams): Promise ⋮---- -export interface GetLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getSpotAssetTags(params?: SpotAssetTagsParams): Promise ⋮---- -export interface GetLockedRewardsHistory { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; - type: string; -} +submitUniversalTransfer( + params: UniversalTransferParams, +): Promise< ⋮---- -export interface SetAutoSubscribeParams { - productId: string; - autoSubscribe: boolean; -} +getUniversalTransferHistory( + params: UniversalTransferHistoryParams, +): Promise ⋮---- -export interface GetFlexibleSubscriptionPreviewParams { - productId: string; - amount: number; -} +getDust(params: ⋮---- -export interface FlexibleSubscriptionPreview { - totalAmount: string; - rewardAsset: string; - airDropAsset: string; - estDailyBonusRewards: string; - estDailyRealTimeRewards: string; - estDailyAirdropRewards: string; -} +convertDustToBnb(params: ConvertDustParams): Promise ⋮---- -export interface GetLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} +/** + * Convert dust assets to a target asset (e.g. BNB, USDT). + */ +convertDustAssets(params: DustConvertParams): Promise ⋮---- -export interface LockedSubscriptionPreview { - rewardAsset: string; - totalRewardAmt: string; - extraRewardAsset: string; - estTotalExtraRewardAmt: string; - nextPay: string; - nextPayDate: string; - valueDate: string; - rewardsEndDate: string; - deliverDate: string; - nextSubscriptionDate: string; - boostRewardAsset: string; - estDailyRewardAmt: string; -} +/** + * Query assets eligible for dust conversion. + */ +queryDustConvertibleAssets( + params: DustConvertibleAssetsParams, +): Promise ⋮---- -export interface GetRateHistoryParams { - productId: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getDustLog(params?: BasicTimeRangeParam): Promise ⋮---- -export interface GetRateHistory { - productId: string; - asset: string; - annualPercentageRate: string; - time: number; -} +getAssetDividendRecord(params?: BasicAssetPaginatedParams): Promise ⋮---- -export interface GetCollateralRecordParams { - productId?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getTradeFee(params?: ⋮---- -export interface CollateralRecord { - amount: string; - productId: string; - asset: string; - createTime: number; - type: string; - productName: string; - orderId: number; -} +getFundingAsset(params: GetAssetParams): Promise ⋮---- -export interface GetDualInvestmentProductListParams { - optionType: string; - exercisedCoin: string; - investCoin: string; - pageSize?: number; - pageIndex?: number; -} +getCloudMiningHistory(params: CloudMiningHistoryParams): Promise< ⋮---- -export interface DualInvestmentProduct { - id: string; - investCoin: string; - exercisedCoin: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseDecimal: number; - purchaseEndTime: number; - canPurchase: boolean; - apr: string; - orderId: number; - minAmount: string; - maxAmount: string; - createTimestamp: number; - optionType: string; - isAutoCompoundEnable: boolean; - autoCompoundPlanList: string[]; -} +getDelegationHistory( + params: DelegationHistoryParams, +): Promise> ⋮---- -export interface SubscribeDualInvestmentProductParams { - id: string; - orderId: string; - depositAmount: number; - /** - * @deprecated Binance removed the `autoCompoundPlan` request parameter from - * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. - * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says - * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec - * still lists the parameter, so this field stays deprecated. - */ - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} +/** + * + * Futures Management Endpoints: + * https://binance-docs.github.io/apidocs/spot/en/#futures + * + * Note: to trade futures use the usdm-client or coinm-client. + * MainClient only has the futures endpoints listed in the "spot" docs category, primarily used for transfers. + * + **/ ⋮---- /** - * @deprecated Binance removed the `autoCompoundPlan` request parameter from - * `POST /sapi/v1/dci/product/subscribe`. Configure auto-compound in the Binance web UI. - * connector-js dual-investment v6.0.0 drops this parameter. Its OpenAPI description says - * auto-compound is toggled in the Binance web UI. The published binance-api-swagger spec - * still lists the parameter, so this field stays deprecated. + * Execute transfer between spot account and futures account. + * + * Type: + * - 1: transfer from spot account to USDT-Ⓜ futures account. + * - 2: transfer from USDT-Ⓜ futures account to spot account. + * - 3: transfer from spot account to COIN-Ⓜ futures account. + * - 4: transfer from COIN-Ⓜ futures account to spot account. */ ⋮---- -export interface SubscribeDualInvestmentProductResponse { - positionId: number; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - duration: number; - autoCompoundPlan?: 'STANDARD' | 'ADVANCED'; - strikePrice: string; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseTime: number; - optionType: string; -} -⋮---- -export interface GetDualInvestmentPositionsParams { - status?: - | 'PENDING' - | 'PURCHASE_SUCCESS' - | 'SETTLED' - | 'PURCHASE_FAIL' - | 'REFUNDING' - | 'REFUND_SUCCESS' - | 'SETTLING'; - pageSize?: number; - pageIndex?: number; -} +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +submitNewFutureAccountTransfer( + params: NewFutureAccountTransferParams, +): Promise< ⋮---- -export interface DualInvestmentPosition { - id: string; - investCoin: string; - exercisedCoin: string; - subscriptionAmount: string; - strikePrice: string; - duration: number; - settleDate: number; - purchaseStatus: string; - apr: string; - orderId: number; - purchaseEndTime: number; - optionType: string; - autoCompoundPlan: 'STANDARD' | 'ADVANCED' | 'NONE'; - settlePrice?: string; - isExercised?: boolean; - settleAsset?: string; - settleAmount?: string; - subscriptionTime?: number; -} +/** + * Possibly @deprecated, found only in old docs only + * Use sapi/v1/asset/transfer instead + */ +getFutureAccountTransferHistory( + params: GetFutureAccountTransferHistoryParams, +): Promise> ⋮---- -export interface CheckDualInvestmentAccountsResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; -} +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralBorrowHistory(params?: CoinStartEndLimit): Promise ⋮---- /** - * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. - * Configure auto-compound for Dual Investment positions in the Binance web UI. - * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published - * binance-api-swagger spec still lists the endpoint, so this type stays deprecated. - */ -export interface ChangeAutoCompoundStatusParams { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} + * @deprecated as of 2023-09-25 + */ +getCrossCollateralRepaymentHistory(params?: CoinStartEndLimit): Promise ⋮---- -export interface ChangeAutoCompoundStatusResponse { - positionId: string; - autoCompoundPlan: 'NONE' | 'STANDARD' | 'ADVANCED'; -} +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralWalletV2(): Promise ⋮---- -export interface GetTargetAssetListParams { - targetAsset?: string; - size?: number; - current?: number; -} +/** + * @deprecated as of 2023-09-25 + */ +getAdjustCrossCollateralLTVHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -export interface RoiAndDimensionType { - simulateRoi: string; - dimensionValue: string; - dimensionUnit: string; -} +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralLiquidationHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -export interface AutoInvestAsset { - targetAsset: string; - roiAndDimensionTypeList: RoiAndDimensionType[]; -} +/** + * @deprecated as of 2023-09-25 + */ +getCrossCollateralInterestHistory( + params?: GetLoanCoinPaginatedHistoryParams, +): Promise ⋮---- -export interface GetTargetAssetListResponse { - targetAssets: string[]; - autoInvestAssetList: AutoInvestAsset[]; -} +/** + * + * WALLET Endpoints - Account endpoints + * + **/ ⋮---- -export interface GetTargetAssetROIParams { - targetAsset: string; - hisRoiType: - | 'FIVE_YEAR' - | 'THREE_YEAR' - | 'ONE_YEAR' - | 'SIX_MONTH' - | 'THREE_MONTH' - | 'SEVEN_DAY'; -} +getAccountInfo(): Promise ⋮---- -export interface TargetAssetROI { - date: string; - simulateRoi: string; -} +getDailyAccountSnapshot( + params: DailyAccountSnapshotParams, +): Promise ⋮---- -export interface GetSourceAssetListParams { - targetAsset?: string[]; - indexId?: number; - usageType: 'RECURRING' | 'ONE_TIME'; - flexibleAllowedToUse?: boolean; - sourceType?: 'MAIN_SITE' | 'TR'; -} +disableFastWithdrawSwitch(): Promise ⋮---- -export interface SourceAsset { - sourceAsset: string; - assetMinAmount: string; - assetMaxAmount: string; - scale: string; - flexibleAmount: string; -} +enableFastWithdrawSwitch(): Promise ⋮---- -export interface GetSourceAssetListResponse { - feeRate: string; - taxRate: string; - sourceAssets: SourceAsset[]; -} +getAccountStatus(): Promise< ⋮---- -export interface AutoInvestPortfolioDetail { - targetAsset: string; - percentage: number; -} +getApiTradingStatus(): Promise ⋮---- -export interface CreateInvestmentPlanParams { - UID: string; - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; - indexId?: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse: boolean; - details: AutoInvestPortfolioDetail[]; -} +getApiKeyPermissions(): Promise ⋮---- -export interface CreateInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} +/** + * + * WALLET Endpoints - Travel Rule endpoints + * + **/ ⋮---- -export interface EditInvestmentPlanParams { - planId: number; - subscriptionAmount: number; - subscriptionCycle: - | 'H1' - | 'H4' - | 'H8' - | 'H12' - | 'WEEKLY' - | 'DAILY' - | 'MONTHLY' - | 'BI_WEEKLY'; - subscriptionStartDay?: number; - subscriptionStartWeekday?: - | 'MON' - | 'TUE' - | 'WED' - | 'THU' - | 'FRI' - | 'SAT' - | 'SUN'; - subscriptionStartTime: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - details: AutoInvestPortfolioDetail[]; -} +/** + * Submit a withdrawal request for local entities that require travel rule + * + * For questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/withdraw-questionnaire + */ +withdrawTravelRule(params: WithdrawTravelRuleParams): Promise< ⋮---- -export interface EditInvestmentPlanResponse { - planId: number; - nextExecutionDateTime: number; -} +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistory( + params?: GetTravelRuleWithdrawHistoryParams, +): Promise ⋮---- -export interface ChangePlanStatusParams { - planId: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} +/** + * Fetch withdraw history for local entities that require travel rule + */ +getTravelRuleWithdrawHistoryV2( + params?: GetTravelRuleWithdrawHistoryV2Params, +): Promise ⋮---- -export interface ChangePlanStatusResponse { - planId: number; - nextExecutionDateTime: number; - status: 'ONGOING' | 'PAUSED' | 'REMOVED'; -} +/** + * Submit questionnaire for local entities that require travel rule + * + * for questionaire format, please refer to the docs: + * https://developers.binance.com/docs/wallet/travel-rule/deposit-questionnaire + */ +submitTravelRuleDepositQuestionnaire( + params: SubmitTravelRuleDepositQuestionnaireParams, +): Promise ⋮---- -export interface GetPlanDetailsParams { - planId?: number; - requestId?: string; -} +/** + * Fetch deposit history for local entities that require travel rule + */ +getTravelRuleDepositHistory( + params?: GetTravelRuleDepositHistoryParams, +): Promise ⋮---- -export interface GetSubscriptionTransactionHistoryParams { - planId?: number; - startTime?: number; - endTime?: number; - targetAsset?: string; - planType?: 'SINGLE' | 'PORTFOLIO' | 'INDEX' | 'ALL'; - size?: number; - current?: number; -} +/** + * Fetch the onboarded VASP list for local entities that require travel rule. + * Use the `identifier` field (not vaspCode) for the `vasp` param in deposit/withdrawal questionnaires. + * Both vaspCode and identifier accepted until 28 May 2026. + */ +getOnboardedVASPList(): Promise ⋮---- -export interface AssetAllocation { - targetAsset: string; - allocation: string; -} +getTravelRuleCountryList(): Promise ⋮---- -export interface GetIndexDetailsResponse { - indexId: number; - indexName: string; - status: 'RUNNING' | 'REBALANCING' | 'PAUSED'; - assetAllocation: AssetAllocation[]; -} +getTravelRuleRegionList( + params: GetTravelRuleRegionListParams, +): Promise ⋮---- -export interface IndexLinkedPlanDetail { - targetAsset: string; - averagePriceInUSD: string; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - purchasedAmount: string; - pnlInUSD: string; - roi: string; - percentage: string; - availableAmount: string; - redeemedAmount: string; - assetValueInUSD: string; -} +/** + * + * WALLET Endpoints - Other endpoints + * + **/ ⋮---- -export interface GetIndexLinkedPlanPositionDetailsResponse { - indexId: number; - totalInvestedInUSD: string; - currentInvestedInUSD: string; - pnlInUSD: string; - roi: string; - assetAllocation: { targetAsset: string; allocation: string }[]; - details: IndexLinkedPlanDetail[]; -} +getSystemStatus(): Promise ⋮---- -export interface SubmitOneTimeTransactionParams { - sourceType: 'MAIN_SITE' | 'TR'; - requestId?: string; - subscriptionAmount: number; - sourceAsset: string; - flexibleAllowedToUse?: boolean; - planId?: number; - indexId?: number; - details: AutoInvestPortfolioDetail[]; -} +getDelistSchedule(): Promise ⋮---- -export interface SubmitOneTimeTransactionResponse { - transactionId: number; - waitSecond: number; -} +/** + * + * SUB ACCOUNT Endpoints - Account management + * + **/ ⋮---- -export interface GetOneTimeTransactionStatusParams { - transactionId: number; - requestId?: string; -} +createVirtualSubAccount( + params: CreateSubAccountParams, +): Promise ⋮---- -export interface GetOneTimeTransactionStatusResponse { - transactionId: number; - status: 'SUCCESS' | 'CONVERTING'; -} +getSubAccountList( + params?: SubAccountListParams, +): Promise ⋮---- -export interface SubmitIndexLinkedPlanRedemptionParams { - indexId: number; - requestId?: string; - redemptionPercentage: number; -} +subAccountEnableFutures(email: string): Promise ⋮---- -export interface GetIndexLinkedPlanRedemptionHistoryParams { - requestId: number; - startTime?: number; - endTime?: number; - current?: number; - asset?: string; - size?: number; -} +/** + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. + */ +subAccountEnableMargin(email: string): Promise ⋮---- -export interface IndexLinkedPlanRedemptionRecord { - indexId: number; - indexName: string; - redemptionId: number; - status: 'SUCCESS' | 'FAILED'; - asset: string; - amount: string; - redemptionDateTime: number; - transactionFee: string; - transactionFeeUnit: string; -} +enableOptionsForSubAccount(params: { + email: string; +}): Promise ⋮---- -export interface GetIndexLinkedPlanRebalanceHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * @deprecated as of 2025-06-03 + * User now should make the initial transfer in the Margin account to enable it. + */ +subAccountEnableLeverageToken( + params: SubAccountEnableLeverageToken, +): Promise ⋮---- -export interface RebalanceTransactionDetail { - asset: string; - transactionDateTime: number; - rebalanceDirection: 'BUY' | 'SELL'; - rebalanceAmount: string; -} +getSubAccountStatusOnMarginOrFutures(params?: { + email?: string; +}): Promise ⋮---- -export interface IndexLinkedPlanRebalanceRecord { - indexId: number; - indexName: string; - rebalanceId: number; - status: 'SUCCESS' | 'INIT'; - rebalanceFee: string; - rebalanceFeeUnit: string; - transactionDetails: RebalanceTransactionDetail[]; -} +getSubAccountFuturesPositionRisk( + email: string, +): Promise ⋮---- -export interface SubscribeEthStakingV2Response { - success: boolean; - wbethAmount: string; - conversionRatio: string; -} +getSubAccountFuturesPositionRiskV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -export interface RedeemEthParams { - asset?: string; - amount: number; -} +getSubAccountTransactionStatistics(params: { + email: string; +}): Promise ⋮---- -export interface RedeemEthResponse { - success: boolean; - arrivalTime: number; - ethAmount: string; - conversionRatio: string; -} +/** + * + * SUB ACCOUNT Endpoints - API management + * + **/ ⋮---- -export interface GetEthStakingHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getSubAccountIPRestriction( + params: BasicSubAccount, +): Promise ⋮---- -export interface EthStakingHistory { - time: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAmount: string; - conversionRatio: string; -} +subAccountDeleteIPList( + params: SubAccountAddOrDeleteIPList, +): Promise ⋮---- -export interface GetEthRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +subAccountAddIPRestriction( + params: AddIpRestriction, +): Promise ⋮---- -export interface EthRedemptionHistory { - time: number; - arrivalTime: number; - asset: string; - amount: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; - distributeAsset: string; - distributeAmount: string; - conversionRatio: string; -} +/** + * @deprecated + * Use subAccountAddIPRestriction instead + **/ +subAccountAddIPList( + params: SubAccountEnableOrDisableIPRestriction, +): Promise ⋮---- -export interface GetBethRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * @deprecated + * Use subAccountAddIPRestriction instead, or subAccountDeleteIPList + **/ +subAccountEnableOrDisableIPRestriction( + params: EnableOrDisableIPRestrictionForSubAccountParams, +): Promise ⋮---- -export interface BethRewardsHistory { - time: number; - asset: string; - holding: string; - amount: string; - annualPercentageRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} +/** + * + * SUB ACCOUNT Endpoints - Asset management + * + **/ ⋮---- -export interface GetEthStakingQuotaResponse { - leftStakingPersonalQuota: string; - leftRedemptionPersonalQuota: string; -} +subAccountFuturesTransfer( + params: SubAccountTransferParams, +): Promise ⋮---- -export interface GetETHRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getSubAccountFuturesAccountDetail( + email: string, +): Promise ⋮---- -export interface ETHRateHistory { - annualPercentageRate: string; - exchangeRate: string; - time: number; -} +getSubAccountDetailOnFuturesAccountV2( + params: BasicFuturesSubAccountParams, +): Promise ⋮---- -export interface GetEthStakingAccountResponse { - cumulativeProfitInBETH: string; - lastDayProfitInBETH: string; -} +getSubAccountDetailOnMarginAccount( + email: string, +): Promise ⋮---- -export interface GetEthStakingAccountV2Response { - holdingInETH: string; - holdings: { - wbethAmount: string; - bethAmount: string; - }; - thirtyDaysProfitInETH: string; - profit: { - amountFromWBETH: string; - amountFromBETH: string; - }; -} +getSubAccountDepositAddress( + params: SubAccountDepositAddressParams, +): Promise ⋮---- -export interface WrapBethResponse { - success: boolean; - wbethAmount: string; - exchangeRate: string; -} +getSubAccountDepositHistory( + params: SubAccountDepositHistoryParams, +): Promise ⋮---- -export interface GetWrapHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getSubAccountFuturesAccountSummary(): Promise ⋮---- -export interface WrapHistory { - time: number; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - exchangeRate: string; - status: 'PENDING' | 'SUCCESS' | 'FAILED'; -} +getSubAccountSummaryOnFuturesAccountV2( + params: SubAccountSummaryOnFuturesAccountV2Params, +): Promise ⋮---- -export interface WbethRewardsHistory { - time: number; - amountInETH: string; - holding: string; - holdingInETH: string; - annualPercentageRate: string; -} +getSubAccountsSummaryOfMarginAccount(): Promise ⋮---- -export interface GetWbethRewardsHistoryResponse { - estRewardsInETH: string; - rows: WbethRewardsHistory[]; - total: number; -} +subAccountMarginTransfer( + params: SubAccountTransferParams, +): Promise ⋮---- -/** - * BFUSD (sapi/v1/bfusd/*) - */ +getSubAccountAssets( + params: SubAccountAssetsParams, +): Promise ⋮---- -export interface BfusdAccountResponse { - bfusdAmount: string; - usdtProfit: string; - bfusdProfit: string; -} +getSubAccountAssetsMaster(params: ⋮---- -export interface BfusdSubscriptionQuota { - leftQuota: string; -} +getSubAccountFuturesAssetTransferHistory( + params: SubAccountFuturesAssetTransferHistoryParams, +): Promise ⋮---- -export interface BfusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} +getSubAccountSpotAssetTransferHistory( + params?: SubAccountSpotAssetTransferHistoryParams, +): Promise ⋮---- -export interface BfusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} +getSubAccountSpotAssetsSummary( + params?: SubAccountSpotAssetsSummaryParams, +): Promise ⋮---- -export interface BfusdQuotaResponse { - subscriptionQuota: BfusdSubscriptionQuota; - fastRedemptionQuota: BfusdFastRedemptionQuota; - standardRedemptionQuota: BfusdStandardRedemptionQuota; -} +getSubAccountUniversalTransferHistory( + params?: SubAccountUniversalTransferHistoryParams, +): Promise ⋮---- -export interface BfusdSubscribeParams { - asset: string; - amount: number; -} +subAccountFuturesAssetTransfer( + params: SubAccountFuturesAssetTransferParams, +): Promise ⋮---- -export interface BfusdSubscribeResponse { - success: boolean; - bfusdAmount: string; -} +subAccountTransferHistory( + params?: SubAccountTransferHistoryParams, +): Promise ⋮---- -export interface BfusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} +subAccountTransferToMaster( + params: SubAccountTransferToMasterParams, +): Promise ⋮---- -export interface BfusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; -} +subAccountTransferToSameMaster( + params: SubAccountTransferToSameMasterParams, +): Promise ⋮---- -export interface GetBfusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +subAccountUniversalTransfer( + params: SubAccountUniversalTransferParams, +): Promise ⋮---- -export interface BfusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} +subAccountMovePosition( + params: SubAccountMovePositionParams, +): Promise< ⋮---- -export interface GetBfusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getSubAccountFuturesPositionMoveHistory( + params: SubAccountMovePositionHistoryParams, +): Promise< ⋮---- -export interface BfusdRedemptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} +/** + * + * SUB ACCOUNT Endpoints - Managed Sub Account + * + **/ ⋮---- -export interface GetBfusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +depositAssetsIntoManagedSubAccount( + params: SubAccountTransferToSameMasterParams, +): Promise ⋮---- -export interface BfusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - annualPercentageRate: string; - rewardAsset?: string; - /** API may return this casing per Binance docs. */ - BFUSDPosition?: string; -} +getManagedSubAccountDepositAddress( + params: ManagedSubAccountDepositAddressParams, +): Promise ⋮---- -/** API may return this casing per Binance docs. */ +withdrawAssetsFromManagedSubAccount( + params: WithdrawAssetsFromManagedSubAccountParams, +): Promise ⋮---- -export interface GetBfusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getManagedSubAccountTransfersParent( + params: ManagedSubAccountTransferLogParams, +): Promise< ⋮---- -export interface BfusdRateHistoryRow { - annualPercentageRate: string; - time: number; -} +getManagedSubAccountTransferLog( + params: ManagedSubAccountTransferTTLogParams, +): Promise< ⋮---- -/** - * RWUSD (sapi/v1/rwusd/*) - */ +getManagedSubAccountTransfersInvestor( + params: ManagedSubAccountTransferLogParams, +): Promise< ⋮---- -export interface RwusdAccountResponse { - rwusdAmount: string; - totalProfit: string; -} +getManagedSubAccounts(params: ManagedSubAccountListParams): Promise< ⋮---- -export interface RwusdSubscriptionQuota { - assets: string[]; - leftQuota: string; - minimum: string; -} +getManagedSubAccountSnapshot( + params: ManagedSubAccountSnapshotParams, +): Promise ⋮---- -export interface RwusdFastRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - freeQuota: string; -} +getManagedSubAccountAssetDetails( + email: string, +): Promise ⋮---- -export interface RwusdStandardRedemptionQuota { - leftQuota: string; - minimum: string; - fee: string; - redeemPeriod: number; -} +getManagedSubAccountMarginAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- -export interface RwusdQuotaResponse { - subscriptionQuota: RwusdSubscriptionQuota; - fastRedemptionQuota: RwusdFastRedemptionQuota; - standardRedemptionQuota: RwusdStandardRedemptionQuota; - subscribeEnable: boolean; - redeemEnable: boolean; -} +getManagedSubAccountFuturesAssets(params: { + email: string; + accountType?: string; +}): Promise ⋮---- -export interface RwusdSubscribeParams { - asset: string; - amount: number; -} +/** + * + * AUTO INVEST Endpoints - Market data + * + **/ ⋮---- -export interface RwusdSubscribeResponse { - success: boolean; - rwusdAmount: string; -} +getAutoInvestAssets(): Promise< ⋮---- -export interface RwusdRedeemParams { - amount: number; - type?: 'FAST' | 'STANDARD'; -} +getAutoInvestSourceAssets( + params: GetSourceAssetListParams, +): Promise ⋮---- -export interface RwusdRedeemResponse { - success: boolean; - receiveAmount: string; - fee: string; - arrivalTime: number; -} +getAutoInvestTargetAssets( + params: GetTargetAssetListParams, +): Promise ⋮---- -export interface GetRwusdSubscriptionHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getAutoInvestTargetAssetsROI( + params: GetTargetAssetROIParams, +): Promise ⋮---- -export interface RwusdSubscriptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - status: 'PENDING' | 'SUCCESS'; -} +getAutoInvestIndex(params: { + indexId: number; +}): Promise ⋮---- -export interface GetRwusdRedemptionHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getAutoInvestPlans(params: { + planType: 'SINGLE' | 'PORTFOLIO' | 'INDEX'; +}): Promise ⋮---- -export interface RwusdRedemptionHistoryRow { - time: number; - asset: string; - amount: string; - receiveAsset: string; - receiveAmount: string; - fee: string; - arrivalTime: number; - status: 'PENDING' | 'SUCCESS'; -} +/** + * + * AUTO INVEST Endpoints - Trade + * + **/ ⋮---- -export interface GetRwusdRewardsHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * https://developers.binance.com/docs/auto_invest/trade/One-Time-Transaction + * + * @param params + * @returns + */ +submitAutoInvestOneTimeTransaction( + params: SubmitOneTimeTransactionParams, +): Promise ⋮---- -export interface RwusdRewardsHistoryRow { - time: number; - rewardsAmount: string; - rwusdPosition: string; - annualPercentageRate: string; -} +updateAutoInvestPlanStatus( + params: ChangePlanStatusParams, +): Promise ⋮---- -export interface GetRwusdRateHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +updateAutoInvestmentPlan( + params: EditInvestmentPlanParams, +): Promise ⋮---- -export interface RwusdRateHistoryRow { - annualPercentageRate: string; - time: number; -} +submitAutoInvestRedemption( + params: SubmitIndexLinkedPlanRedemptionParams, +): Promise< ⋮---- -export interface GetMiningAlgoListResponse { - algoName: string; // Algorithm name - algoId: number; // Algorithm ID - poolIndex: number; // Sequence - unit: string; // Unit -} +getAutoInvestSubscriptionTransactions( + params: GetSubscriptionTransactionHistoryParams, +): Promise ⋮---- -algoName: string; // Algorithm name -algoId: number; // Algorithm ID -poolIndex: number; // Sequence -unit: string; // Unit +getOneTimeTransactionStatus( + params: GetOneTimeTransactionStatusParams, +): Promise ⋮---- -export interface GetMiningCoinListResponse { - coinName: string; // Coin name - coinId: number; // Coin ID - poolIndex: number; // Sequence - unit: string; // Unit -} +submitAutoInvestmentPlan( + params: CreateInvestmentPlanParams, +): Promise ⋮---- -coinName: string; // Coin name -coinId: number; // Coin ID -poolIndex: number; // Sequence -unit: string; // Unit +getAutoInvestRedemptionHistory( + params: GetIndexLinkedPlanRedemptionHistoryParams, +): Promise ⋮---- -export interface GetMinerDetailsParams { - algo: string; - userName: string; - workerName: string; -} +getAutoInvestPlan(params: GetPlanDetailsParams): Promise ⋮---- -export interface HashrateData { - time: number; - hashrate: string; - reject: number; -} +getAutoInvestUserIndex(params: { + indexId: number; +}): Promise ⋮---- -export interface MinerDetail { - workerName: string; - type: string; - hashrateDatas: HashrateData[]; -} +getAutoInvestRebalanceHistory( + params: GetIndexLinkedPlanRebalanceHistoryParams, +): Promise ⋮---- -export interface GetMinerDetailsResponse { - code: number; - msg: string; - data: MinerDetail[]; -} +/** + * + * CONVERT Endpoints - Market Data + * + **/ ⋮---- -export interface GetMinerListParams { - algo: string; - userName: string; - pageIndex?: number; - sort?: number; - sortColumn?: number; - workerStatus?: number; -} +getConvertPairs(params: GetAllConvertPairsParams): Promise ⋮---- -export interface WorkerData { - workerId: string; - workerName: string; - status: number; - hashRate: number; - dayHashRate: number; - rejectRate: number; - lastShareTime: number; -} +getConvertAssetInfo(): Promise ⋮---- -export interface GetMinerListResponse { - code: number; - msg: string; - data: { - workerDatas: WorkerData[]; - totalNum: number; - pageSize: number; - }; -} +/** + * + * CONVERT Endpoints - Trade + * + **/ ⋮---- -export interface GetEarningsListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} +convertQuoteRequest(params: ConvertQuoteRequestParams): Promise ⋮---- -export interface AccountEarningsProfit { - time: number; - type: number; - hashTransfer: number | null; - transferAmount: number | null; - dayHashRate: number; - profitAmount: number; - coinName: string; - status: number; -} +acceptQuoteRequest(params: AcceptQuoteRequestParams): Promise ⋮---- -export interface GetEarningsListResponse { - code: number; - msg: string; - data: { - accountProfits: AccountEarningsProfit[]; - totalNum: number; - pageSize: number; - }; -} +getConvertTradeHistory(params: GetConvertTradeHistoryParams): Promise +⋮---- +getOrderStatus(params: GetOrderStatusParams): Promise ⋮---- -export interface GetExtraBonusListParams { - algo: string; - userName: string; - coin?: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} +submitConvertLimitOrder(params: SubmitConvertLimitOrderParams): Promise ⋮---- -export interface OtherProfit { - time: number; - coinName: string; - type: number; - profitAmount: number; - status: number; -} +cancelConvertLimitOrder(params: ⋮---- -export interface GetExtraBonusListResponse { - code: number; - msg: string; - data: { - otherProfits: OtherProfit[]; - totalNum: number; - pageSize: number; - }; -} +getConvertLimitOpenOrders(): Promise< ⋮---- -export interface GetHashrateResaleListParams { - pageIndex?: number; - pageSize?: number; -} +/** + * + * STAKING Endpoints - ETH Staking - Account + * + **/ ⋮---- -export interface ConfigDetail { - configId: number; - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - startDay: number; - endDay: number; - status: number; -} +/** + * @deprecated use getEthStakingAccountV2 instead + **/ +getEthStakingAccount(): Promise ⋮---- -export interface GetHashrateResaleListResponse { - code: number; - msg: string; - data: { - configDetails: ConfigDetail[]; - totalNum: number; - pageSize: number; - }; -} +getEthStakingAccountV2(): Promise ⋮---- -export interface GetHashrateResaleDetailParams { - configId: number; - userName: string; - pageIndex?: number; - pageSize?: number; -} +getEthStakingQuota(): Promise ⋮---- -export interface ProfitTransferDetail { - poolUsername: string; - toPoolUsername: string; - algoName: string; - hashRate: number; - day: number; - amount: number; - coinName: string; -} +/** + * + * STAKING Endpoints - ETH Staking- Staking + * + **/ ⋮---- -export interface GetHashrateResaleDetailResponse { - code: number; - msg: string; - data: { - profitTransferDetails: ProfitTransferDetail[]; - totalNum: number; - pageSize: number; - }; -} -export interface SubmitHashrateResaleParams { - userName: string; - algo: string; - endDate: number; - startDate: number; - toPoolUser: string; - hashRate: number; -} +/** + * @deprecated use subscribeEthStakingV2 instead + **/ +subscribeEthStakingV1(params: ⋮---- -export interface CancelHashrateResaleConfigParams { - configId: number; - userName: string; -} +subscribeEthStakingV2(params: { + amount: number; +}): Promise ⋮---- -export interface GetStatisticListParams { - algo: string; - userName: string; -} +redeemEth(params: RedeemEthParams): Promise ⋮---- -export interface Profit { - BTC: string; - BSV: string; - BCH: string; -} +wrapBeth(params: ⋮---- -export interface GetStatisticListResponse { - code: number; - msg: string; - data: { - fifteenMinHashRate: string; - dayHashRate: string; - validNum: number; - invalidNum: number; - profitToday: Profit; - profitYesterday: Profit; - userName: string; - unit: string; - algo: string; - }; -} +/** + * + * STAKING Endpoints - ETH Staking - History + * + **/ ⋮---- -export interface getMiningAccountsListParams { - algo: string; - userName: string; -} +getEthStakingHistory(params: GetEthStakingHistoryParams): Promise< ⋮---- -export interface MiningHashrateData { - time: number; - hashrate: string; - reject: string; -} +getEthRedemptionHistory(params: GetEthRedemptionHistoryParams): Promise< ⋮---- -export interface MiningAccountData { - type: string; - userName: string; - list: MiningHashrateData[]; -} +getBethRewardsHistory(params: GetBethRewardsHistoryParams): Promise< ⋮---- -export interface getMiningAccountsListResponse { - code: number; - msg: string; - data: MiningAccountData[]; -} +getWbethRewardsHistory( + params: GetWrapHistoryParams, +): Promise ⋮---- -export interface GetMiningAccountEarningParams { - algo: string; - startDate?: number; - endDate?: number; - pageIndex?: number; - pageSize?: number; -} +getEthRateHistory(params: GetETHRateHistoryParams): Promise< ⋮---- -export interface AccountMiningProfit { - time: number; - coinName: string; - type: number; - puid: number; - subName: string; - amount: number; -} +getBethWrapHistory(params: GetWrapHistoryParams): Promise< ⋮---- -export interface GetMiningAccountEarningResponse { - code: number; - msg: string; - data: { - accountProfits: AccountMiningProfit[]; - totalNum: number; - pageSize: number; - }; -} +getBethUnwrapHistory(params: GetWrapHistoryParams): Promise< ⋮---- -export interface GetFutureTickLevelOrderbookDataLinkParams { - symbol: string; - dataType: 'T_DEPTH' | 'S_DEPTH'; - startTime: number; - endTime: number; -} +/** + * + * BFUSD (sapi/v1/bfusd) + * + **/ ⋮---- -export interface HistoricalDataLink { - day: string; - url: string; -} +getBfusdAccount(): Promise ⋮---- -export interface SubmitVpNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - urgency: 'LOW' | 'MEDIUM' | 'HIGH'; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; -} +getBfusdQuota(): Promise ⋮---- -export interface SubmitVpNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} +subscribeBfusd( + params: BfusdSubscribeParams, +): Promise ⋮---- -export interface SubmitTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - positionSide?: 'BOTH' | 'LONG' | 'SHORT'; - quantity: number; - duration: number; - clientAlgoId?: string; - reduceOnly?: boolean; - limitPrice?: number; -} +redeemBfusd(params: BfusdRedeemParams): Promise +⋮---- +getBfusdSubscriptionHistory( + params: GetBfusdSubscriptionHistoryParams, +): Promise< +⋮---- +getBfusdRedemptionHistory( + params: GetBfusdRedemptionHistoryParams, +): Promise< +⋮---- +getBfusdRewardsHistory( + params: GetBfusdRewardsHistoryParams, +): Promise< +⋮---- +getBfusdRateHistory( + params: GetBfusdRateHistoryParams, +): Promise< ⋮---- -export interface SubmitTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} +/** + * + * RWUSD (sapi/v1/rwusd) + * + **/ ⋮---- -export interface CancelAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: string; -} +getRwusdAccount(): Promise ⋮---- -export interface AlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; -} +getRwusdQuota(): Promise ⋮---- -export interface GetAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: number; -} +subscribeRwusd( + params: RwusdSubscribeParams, +): Promise ⋮---- -export interface HistoricalAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - positionSide: 'BOTH' | 'LONG' | 'SHORT'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; -} +redeemRwusd(params: RwusdRedeemParams): Promise ⋮---- -export interface GetAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; -} +getRwusdSubscriptionHistory( + params: GetRwusdSubscriptionHistoryParams, +): Promise< ⋮---- -export interface SubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; -} +getRwusdRedemptionHistory( + params: GetRwusdRedemptionHistoryParams, +): Promise< ⋮---- -export interface GetAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SubOrder[]; -} +getRwusdRewardsHistory( + params: GetRwusdRewardsHistoryParams, +): Promise< ⋮---- -export interface SubmitSpotTwapNewOrderParams { - symbol: string; - side: 'BUY' | 'SELL'; - quantity: number; - duration: number; - clientAlgoId?: string; - limitPrice?: number; - stpMode?: 'EXPIRE_TAKER' | 'EXPIRE_MAKER' | 'EXPIRE_BOTH' | 'NONE'; -} +getRwusdRateHistory( + params: GetRwusdRateHistoryParams, +): Promise< ⋮---- -export interface SubmitSpotTwapNewOrderResponse { - clientAlgoId: string; - success: boolean; - code: number; - msg: string; -} +/** + * @deprecated as of 2024-01-19 + */ +getStakingProducts( + params: StakingBasicParams & { + asset?: string; + }, +): Promise ⋮---- -export interface CancelSpotAlgoOrderResponse { - algoId: number; - success: boolean; - code: number; - msg: string; -} +/** + * @deprecated as of 2024-01-19 + */ +getStakingProductPosition( + params: StakingBasicParams & { + productId?: string; + asset?: string; + }, +): Promise ⋮---- -export interface SpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; - /** Order duration in seconds. Only returned for TWAP orders. */ - duration?: number; -} +/** + * @deprecated as of 2024-01-19 + */ +getStakingHistory(params: StakingHistoryParams): Promise ⋮---- -/** Order duration in seconds. Only returned for TWAP orders. */ +/** + * @deprecated as of 2024-01-19 + */ +getPersonalLeftQuotaOfStakingProduct(params: { + product: StakingProductType; + productId: string; +}): Promise ⋮---- -export interface GetSpotAlgoHistoricalOrdersParams { - symbol?: string; - side?: 'BUY' | 'SELL'; - startTime?: number; - endTime?: number; - page?: number; - pageSize?: number; -} +/** + * + * STAKING Endpoints - SOL Staking- Account + * + **/ ⋮---- -export interface HistoricalSpotAlgoOrder { - algoId: number; - symbol: string; - side: 'BUY' | 'SELL'; - totalQty: string; - executedQty: string; - executedAmt: string; - avgPrice: string; - clientAlgoId: string; - bookTime: number; - endTime: number; - algoStatus: string; - algoType: string; - urgency: string; - /** Order duration in seconds. Only returned for TWAP orders. */ - duration?: number; -} +getSolStakingAccount(): Promise ⋮---- -/** Order duration in seconds. Only returned for TWAP orders. */ +getSolStakingQuota(): Promise ⋮---- -export interface GetSpotAlgoSubOrdersParams { - algoId: number; - page?: number; - pageSize?: number; -} +/** + * + * STAKING Endpoints - SOL Staking - Staking + * + **/ ⋮---- -export interface SpotSubOrder { - algoId: number; - orderId: number; - orderStatus: string; - executedQty: string; - executedAmt: string; - feeAmt: string; - feeAsset: string; - bookTime: number; - avgPrice: string; - side: 'BUY' | 'SELL'; - symbol: string; - subId: number; - timeInForce: string; - origQty: string; -} +subscribeSolStaking(params: { + amount: number; +}): Promise ⋮---- -export interface GetSpotAlgoSubOrdersResponse { - total: number; - executedQty: string; - executedAmt: string; - subOrders: SpotSubOrder[]; -} +redeemSol(params: ⋮---- -export interface GetPortfolioMarginProAccountInfoResponse { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - accountStatus: string; - accountType: string; -} +claimSolBoostRewards(): Promise< ⋮---- -export interface PortfolioDeltaModeStatus { - deltaEnabled: boolean; -} +/** + * + * STAKING Endpoints - SOL Staking- History + * + **/ ⋮---- -export interface SwitchPortfolioDeltaModeParams { - deltaEnabled: 'true' | 'false'; -} +getSolStakingHistory(params?: GetSolStakingHistoryReq): Promise< ⋮---- -export interface GetPortfolioMarginProCollateralRateResponse { - asset: string; - collateralRate: string; -} +getSolRedemptionHistory(params?: { + rows: SolRedemptionHistoryRecord[]; + total: number; +}): Promise ⋮---- -export interface GetPortfolioMarginProBankruptcyLoanAmountResponse { - asset: string; - amount: string; -} +getBnsolRewardsHistory(params?: GetBnsolRewardsHistoryReq): Promise< ⋮---- -export interface GetPortfolioMarginProInterestHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - size?: number; -} +getBnsolRateHistory(params?: GetBnsolRateHistoryReq): Promise< ⋮---- -export interface GetPortfolioMarginProInterestHistoryResponse { - asset: string; - interest: string; - interestAccruedTime: number; - interestRate: string; - principal: string; -} +getSolBoostRewardsHistory(params?: SolBoostRewardsHistoryReq): Promise< ⋮---- -export interface GetPortfolioMarginAssetIndexPriceResponse { - asset: string; - assetIndexPrice: string; - time: number; -} +getSolUnclaimedRewards(): Promise< + { + amount: string; + rewardsAsset: string; + }[] + > { + return this.getPrivate('sapi/v1/sol-staking/sol/history/unclaimedRewards'); ⋮---- -export interface BnbTransferParams { - amount: number; - transferSide: 'TO_UM' | 'FROM_UM'; -} +/** + * + * STAKING - Onchain Yields - Account + * + **/ ⋮---- -export interface GetPortfolioMarginAssetLeverageResponse { - asset: string; - leverage: number; -} +getOnchainYieldsLockedProducts( + params?: OnchainYieldsLockedProductListParams, +): Promise ⋮---- -export interface SetPortfolioMarginMarginCallLevelParams { - marginCallLevel: number; -} +getOnchainYieldsLockedPersonalLeftQuota( + params: OnchainYieldsLockedPersonalLeftQuotaParams, +): Promise ⋮---- -export interface PortfolioMarginMarginCallLevelResponse { - marginCallLevel: string; -} +getOnchainYieldsLockedPosition( + params?: OnchainYieldsLockedPositionParams, +): Promise ⋮---- -export type PortfolioMarginMarginCallLevelGetResponse = - | PortfolioMarginMarginCallLevelResponse - | Record; +getOnchainYieldsAccount(): Promise ⋮---- -export interface PortfolioMarginMarginCallLevelDeleteResponse { - msg: string; -} +/** + * + * STAKING - Onchain Yields - Earn + * + **/ ⋮---- -export interface SubscribeBlvtParams { - tokenName: string; - cost: number; -} +getOnchainYieldsLockedSubscriptionPreview( + params: OnchainYieldsLockedSubscriptionPreviewParams, +): Promise ⋮---- -export interface SubscribeBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - amount: string; - cost: string; - timestamp: number; -} +subscribeOnchainYieldsLockedProduct( + params: OnchainYieldsLockedSubscribeParams, +): Promise ⋮---- -export interface GetBlvtSubscriptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +setOnchainYieldsLockedAutoSubscribe( + params: OnchainYieldsLockedSetAutoSubscribeParams, +): Promise ⋮---- -export interface BlvtSubscriptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - totalCharge: string; - timestamp: number; -} +setOnchainYieldsLockedRedeemOption( + params: OnchainYieldsLockedSetRedeemOptionParams, +): Promise ⋮---- -export interface RedeemBlvtParams { - tokenName: string; - amount: number; -} +redeemOnchainYieldsLockedProduct( + params: OnchainYieldsLockedRedeemParams, +): Promise ⋮---- -export interface RedeemBlvtResponse { - id: number; - status: 'S' | 'P' | 'F'; - tokenName: string; - redeemAmount: string; - amount: string; - timestamp: number; -} +/** + * + * STAKING - Onchain Yields - History + * + **/ ⋮---- -export interface GetBlvtRedemptionRecordParams { - tokenName?: string; - id?: number; - startTime?: number; - endTime?: number; - limit?: number; -} +getOnchainYieldsLockedSubscriptionRecord( + params?: OnchainYieldsLockedSubscriptionRecordParams, +): Promise ⋮---- -export interface BlvtRedemptionRecord { - id: number; - tokenName: string; - amount: string; - nav: string; - fee: string; - netProceed: string; - timestamp: number; -} +getOnchainYieldsLockedRewardsHistory( + params?: OnchainYieldsLockedRewardsHistoryParams, +): Promise ⋮---- -export interface BlvtUserLimitInfo { - tokenName: string; - userDailyTotalPurchaseLimit: string; - userDailyTotalRedeemLimit: string; -} +getOnchainYieldsLockedRedemptionRecord( + params?: OnchainYieldsLockedRedemptionRecordParams, +): Promise ⋮---- -export interface GetFiatOrderHistoryParams { - transactionType: string; - beginTime?: number; - endTime?: number; - page?: number; - rows?: number; -} +/** + * + * STAKING - Soft staking + * + **/ ⋮---- -export interface GetFiatOrderHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - fiatCurrency: string; - indicatedAmount: string; - amount: string; - totalFee: string; - method: string; - status: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; -} +getSoftStakingProductList( + params?: GetSoftStakingProductListParams, +): Promise ⋮---- -export interface GetFiatPaymentsHistoryResponse { - code: string; - message: string; - data: { - orderNo: string; - sourceAmount: string; - fiatCurrency: string; - obtainAmount: string; - cryptoCurrency: string; - totalFee: string; - price: string; - status: string; - paymentMethod?: string; - createTime: number; - updateTime: number; - }[]; - total: number; - success: boolean; -} +setSoftStaking( + params: SetSoftStakingParams, +): Promise ⋮---- -export interface WithdrawFiatAccountInfo { - accountNumber: string; - agency: string; - bankCodeForPix: string; - accountType: string; -} +getSoftStakingRewardsHistory( + params?: GetSoftStakingRewardsHistoryParams, +): Promise ⋮---- -export interface WithdrawFiatParams { - currency: string; - apiPaymentMethod: string; - amount: number; - accountInfo?: WithdrawFiatAccountInfo; -} +/** + * + * COPY TRADING Endpoints - Future copy trading + * + **/ ⋮---- -export interface FiatDepositParams { - currency: string; - apiPaymentMethod: string; - amount: number; - ext?: object; - recvWindow?: number; - timestamp?: number; -} +getFuturesLeadTraderStatus(): Promise ⋮---- -export interface FiatDepositResponse { - code: string; - message: string; - data: { - orderId: string; - }; -} +getFuturesLeadTradingSymbolWhitelist(): Promise< + GetFuturesLeadTradingSymbolWhitelistResponse[] + > { + return this.getPrivate('sapi/v1/copyTrading/futures/leadSymbol'); ⋮---- -export interface GetFiatOrderDetailParams { - orderNo: string; - recvWindow?: number; - timestamp?: number; -} +/** + * + * MINING Endpoints - rest api + * + **/ ⋮---- -export interface GetFiatOrderDetailResponse { - code: string; - message: string; - data: { - orderId: string; - orderStatus: string; - amount: string; - fee: string; - fiatCurrency: string; - errorCode: string; - errorMessage: string; - ext: object; - }; -} +getMiningAlgos(): Promise ⋮---- -export interface GetC2CTradeHistoryParams { - tradeType: string; - startTimestamp?: number; - endTimestamp?: number; - page?: number; - rows?: number; -} +getMiningCoins(): Promise ⋮---- -export interface c2cTradeData { - orderNumber: string; - advNo: string; - tradeType: string; - asset: string; - fiat: string; - fiatSymbol: string; - amount: string; - totalPrice: string; - unitPrice: string; - orderStatus: string; - createTime: number; - commission: string; - counterPartNickName: string; - advertisementRole: string; -} -export interface GetC2CTradeHistoryResponse { - code: string; - message: string; - data: c2cTradeData[]; - total: number; - success: boolean; -} +getHashrateResales( + params: GetHashrateResaleListParams, +): Promise ⋮---- -export interface GetVipLoanOngoingOrdersParams { - orderId?: number; - collateralAccountId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} +getMiners(params: GetMinerListParams): Promise ⋮---- -export interface VipOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - loanRate: string; - residualInterest: string; - collateralAccountId: string; - collateralCoin: string; - totalCollateralValueAfterHaircut: string; - lockedCollateralValue: string; - currentLTV: string; - expirationTime: number; - loanDate: string; - loanTerm: string; - initialLtv: string; - marginCallLtv: string; - liquidationLtv: string; -} +getMinerDetails( + params: GetMinerDetailsParams, +): Promise ⋮---- -export interface VipLoanRepayParams { - orderId: number; - amount: number; -} +getExtraBonuses( + params: GetExtraBonusListParams, +): Promise ⋮---- -export interface VipLoanRepayResponse { - loanCoin: string; - repayAmount: string; - remainingPrincipal: string; - remainingInterest: string; - collateralCoin: string; - currentLTV: string; - repayStatus: string; -} +getMiningEarnings( + params: GetEarningsListParams, +): Promise ⋮---- -export interface GetVipLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +cancelHashrateResaleConfig( + params: CancelHashrateResaleConfigParams, +): Promise ⋮---- -export interface VipLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - repayInterest: string; - repayPrincipal: string; - collateralCoin: string; - repayStatus: string; - loanDate: string; - repayTime: string; - orderId: string; -} +getHashrateResale( + params: GetHashrateResaleDetailParams, +): Promise ⋮---- -export interface VipLoanRenewParams { - orderId: number; - loanTerm?: number; -} +getMiningAccountEarnings( + params: GetMiningAccountEarningParams, +): Promise ⋮---- -export interface VipLoanRenewResponse { - loanAccountId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; -} +getMiningStatistics( + params: GetStatisticListParams, +): Promise ⋮---- -export interface CheckVipCollateralAccountParams { - orderId?: number; - collateralAccountId?: number; -} +submitHashrateResale(params: SubmitHashrateResaleParams): Promise ⋮---- -export interface VipCollateralAccount { - collateralAccountId: string; - collateralCoin: string; -} +getMiningAccounts( + params: getMiningAccountsListParams, +): Promise ⋮---- -export interface VipLoanBorrowParams { - loanAccountId: number; - loanCoin: string; - loanAmount: number; - collateralAccountId: string; - collateralCoin: string; - isFlexibleRate: boolean; - loanTerm?: number; -} +/** + * + * ALGO TRADING Endpoints - Future algo + * + **/ ⋮---- -export interface VipLoanBorrowResponse { - loanAccountId: string; - requestId: string; - loanCoin: string; - isFlexibleRate: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm?: string; -} +submitVpNewOrder( + params: SubmitVpNewOrderParams, +): Promise ⋮---- -export interface GetLoanableAssetsDataParams { - loanCoin?: string; - vipLevel?: number; -} +submitTwapNewOrder( + params: SubmitTwapNewOrderParams, +): Promise ⋮---- -export interface GetApplicationStatusParams { - current?: number; - limit?: number; -} +cancelAlgoOrder( + params: + | { algoId: number; clientAlgoId?: string } + | { clientAlgoId: string; algoId?: number }, +): Promise ⋮---- -export interface ApplicationStatus { - loanAccountId: string; - orderId: string; - requestId: string; - loanCoin: string; - loanAmount: string; - collateralAccountId: string; - collateralCoin: string; - loanTerm: string; - status: string; - loanDate: string; -} +getAlgoSubOrders( + params: GetAlgoSubOrdersParams, +): Promise ⋮---- -export interface BorrowInterestRate { - asset: string; - flexibleDailyInterestRate: string; - flexibleYearlyInterestRate: string; - time: number; -} +getAlgoOpenOrders(): Promise< ⋮---- -export interface GetCryptoLoansIncomeHistoryParams { - asset?: string; - type?: string; - startTime?: number; - endTime?: number; - limit?: number; -} +getAlgoHistoricalOrders(params: GetAlgoHistoricalOrdersParams): Promise< ⋮---- -export interface GetCryptoLoansIncomeHistoryResponse { - asset: string; - type: string; - amount: string; - timestamp: number; - tranId: string; -} +/** + * + * ALGO TRADING Endpoints - Spot algo + * + **/ ⋮---- -export interface BorrowCryptoLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; - loanTerm: number; -} +submitSpotAlgoTwapOrder( + params: SubmitSpotTwapNewOrderParams, +): Promise ⋮---- -export interface BorrowCryptoLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - hourlyInterestRate: string; - orderId: string; -} +cancelSpotAlgoOrder( + params: + | { algoId: number; clientAlgoId?: string } + | { clientAlgoId: string; algoId?: number }, +): Promise ⋮---- -export interface GetLoanBorrowHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +getSpotAlgoSubOrders( + params: GetSpotAlgoSubOrdersParams, +): Promise ⋮---- -export interface LoanBorrowHistory { - orderId: number; - loanCoin: string; - initialLoanAmount: string; - hourlyInterestRate: string; - loanTerm: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: string; -} +getSpotAlgoOpenOrders(): Promise< ⋮---- -export interface GetLoanOngoingOrdersParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} +getSpotAlgoHistoricalOrders( + params: GetSpotAlgoHistoricalOrdersParams, +): Promise< ⋮---- -export interface LoanOngoingOrder { - orderId: number; - loanCoin: string; - totalDebt: string; - residualInterest: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; - expirationTime: number; -} +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Market data + * + **/ ⋮---- -export interface RepayCryptoLoanParams { - orderId: number; - amount: number; - type?: number; - collateralReturn?: boolean; -} +getCryptoLoanFlexibleCollateralAssets(params: { + collateralCoin?: string; +}): Promise< ⋮---- -export interface RepayCryptoLoanResponse { - loanCoin: string; - remainingPrincipal?: string; - remainingInterest?: string; - collateralCoin: string; - remainingCollateral?: string; - currentLTV?: string; - repayStatus: string; -} +getCryptoLoanFlexibleAssets(params: ⋮---- -export interface GetLoanRepaymentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - Trade + * + **/ ⋮---- -export interface LoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralUsed: string; - collateralReturn: string; - repayType: string; - repayStatus: string; - repayTime: number; - orderId: number; -} +borrowCryptoLoanFlexible( + params: BorrowFlexibleLoanParams, +): Promise ⋮---- -export interface AdjustCryptoLoanLTVParams { - orderId: number; - amount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} +repayCryptoLoanFlexible( + params: RepayCryptoFlexibleLoanParams, +): Promise ⋮---- -export interface AdjustCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - currentLTV: string; -} +repayCryptoLoanFlexibleWithCollateral( + params: RepayCryptoLoanFlexibleWithCollateralParams, +): Promise ⋮---- -export interface GetLoanLTVAdjustmentHistoryParams { - orderId?: number; - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +adjustCryptoLoanFlexibleLTV( + params: AdjustFlexibleCryptoLoanLTVParams, +): Promise ⋮---- -export interface LoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - amount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; - orderId: number; -} +/** + * + * CRYPTO LOAN Endpoints - Flexible rate - User info + * + **/ ⋮---- -export interface LoanableAssetData { - loanCoin: string; - _7dHourlyInterestRate: string; - _7dDailyInterestRate: string; - _14dHourlyInterestRate: string; - _14dDailyInterestRate: string; - _30dHourlyInterestRate: string; - _30dDailyInterestRate: string; - _90dHourlyInterestRate: string; - _90dDailyInterestRate: string; - _180dHourlyInterestRate: string; - _180dDailyInterestRate: string; - minLimit: string; - maxLimit: string; - vipLevel: number; -} +getCryptoLoanFlexibleLTVAdjustmentHistory( + params: GetFlexibleLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -export interface GetCollateralAssetDataParams { - collateralCoin?: string; - vipLevel?: number; -} +getFlexibleLoanCollateralRepayRate(params: { + loanCoin: string; + collateralCoin: string; +}): Promise< ⋮---- -export interface CollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; - vipLevel: number; -} +getLoanFlexibleBorrowHistory( + params: GetFlexibleCryptoLoanBorrowHistoryParams, +): Promise< ⋮---- -export interface CheckCollateralRepayRateParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; -} +getCryptoLoanFlexibleOngoingOrders( + params: GetFlexibleLoanOngoingOrdersParams, +): Promise< ⋮---- -export interface CheckCollateralRepayRateResponse { - loanCoin: string; - collateralCoin: string; - repayAmount: string; - rate: string; -} +getFlexibleLoanLiquidationHistory( + params?: GetFlexibleLoanLiquidationHistoryParams, +): Promise< ⋮---- -export interface CustomizeMarginCallParams { - orderId?: number; - collateralCoin?: string; - marginCall: number; -} +getLoanFlexibleRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise< ⋮---- -export interface CustomizeMarginCall { - orderId: string; - collateralCoin: string; - preMarginCall: string; - afterMarginCall: string; - customizeTime: number; -} +/** + * + * CRYPTO LOAN Endpoints - Stable rate - Market data + * + **/ ⋮---- -export interface BorrowFlexibleLoanParams { - loanCoin: string; - loanAmount?: number; - collateralCoin: string; - collateralAmount?: number; -} +/** + * @deprecated + */ +getCryptoLoanLoanableAssets(params: GetLoanableAssetsDataParams): Promise< +⋮---- +getCryptoLoanCollateralRepayRate( + params: CheckCollateralRepayRateParams, +): Promise ⋮---- -export interface BorrowFlexibleLoanResponse { - loanCoin: string; - loanAmount: string; - collateralCoin: string; - collateralAmount: string; - status: 'Succeeds' | 'Failed' | 'Processing'; -} +/** + * @deprecated + */ +getCryptoLoanCollateralAssetsData( + params: GetCollateralAssetDataParams, +): Promise< ⋮---- -export interface GetFlexibleLoanOngoingOrdersParams { - loanCoin?: string; - collateralCoin?: string; - current?: number; - limit?: number; -} +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/income` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoansIncomeHistory( + params: GetCryptoLoansIncomeHistoryParams, +): Promise ⋮---- -export interface FlexibleLoanOngoingOrder { - loanCoin: string; - totalDebt: string; - collateralCoin: string; - collateralAmount: string; - currentLTV: string; -} +/** + * + * CRYPTO LOAN Endpoints - Stable rate - Trade + * + **/ ⋮---- -export interface GetFlexibleLoanLiquidationHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; // Default: 1, max: 1000 - limit?: number; // Default: 10, max: 100 - recvWindow?: number; -} +/** + * @deprecated + */ +borrowCryptoLoan( + params: BorrowCryptoLoanParams, +): Promise ⋮---- -current?: number; // Default: 1, max: 1000 -limit?: number; // Default: 10, max: 100 +/** + * @deprecated + */ +repayCryptoLoan( + params: RepayCryptoLoanParams, +): Promise ⋮---- -export interface FlexibleLoanLiquidationHistoryRecord { - loanCoin: string; - liquidationDebt: string; - collateralCoin: string; - liquidationCollateralAmount: string; - returnCollateralAmount: string; - liquidationFee: string; - liquidationStartingPrice: string; - liquidationStartingTime: number; - status: 'Liquidated' | 'Liquidating'; -} +/** + * @deprecated + */ +adjustCryptoLoanLTV( + params: AdjustCryptoLoanLTVParams, +): Promise ⋮---- -export interface GetFlexibleCryptoLoanBorrowHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +/** + * @deprecated + */ +customizeCryptoLoanMarginCall(params: CustomizeMarginCallParams): Promise< ⋮---- -export interface FlexibleCryptoLoanBorrowHistory { - loanCoin: string; - initialLoanAmount: string; - collateralCoin: string; - initialCollateralAmount: string; - borrowTime: number; - status: 'Succeeds' | 'Failed' | 'Processing'; -} +/** + * + * CRYPTO LOAN Endpoints - Stable rate - User info + * + **/ ⋮---- -export interface RepayCryptoFlexibleLoanParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; - collateralReturn?: boolean; - fullRepayment?: boolean; -} +/** + * @deprecated + */ +getCryptoLoanOngoingOrders(params: GetLoanOngoingOrdersParams): Promise< ⋮---- -export interface RepayCryptoFlexibleLoanResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/borrow/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanBorrowHistory(params: GetLoanBorrowHistoryParams): Promise< ⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralParams { - loanCoin: string; - collateralCoin: string; - repayAmount: number; // Amount of loan to repay - fullRepayment?: boolean; // Default: FALSE -} +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/ltv/adjustment/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanLTVAdjustmentHistory( + params: GetLoanLTVAdjustmentHistoryParams, +): Promise< ⋮---- -repayAmount: number; // Amount of loan to repay -fullRepayment?: boolean; // Default: FALSE +/** + * @deprecated Stable Rate history was retired on 2026-10-16. + * `GET /sapi/v1/loan/repay/history` returns HTTP 404. Flexible Rate v2 is unaffected. + */ +getCryptoLoanRepaymentHistory( + params: GetLoanRepaymentHistoryParams, +): Promise ⋮---- -export interface RepayCryptoLoanFlexibleWithCollateralResponse { - loanCoin: string; - collateralCoin: string; - remainingDebt: string; - remainingCollateral: string; - fullRepayment: boolean; - currentLTV: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; -} -export interface GetFlexibleCryptoLoanRepaymentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +/** + * + * SIMPLE EARN Endpoints - Account + * + **/ ⋮---- -export interface FlexibleCryptoLoanRepaymentHistory { - loanCoin: string; - repayAmount: string; - collateralCoin: string; - collateralReturn: string; - repayStatus: 'Repaid' | 'Repaying' | 'Failed'; - repayTime: number; -} +getSimpleEarnAccount(): Promise ⋮---- -export interface AdjustFlexibleCryptoLoanLTVParams { - loanCoin: string; - collateralCoin: string; - adjustmentAmount: number; - direction: 'ADDITIONAL' | 'REDUCED'; -} +getFlexibleSavingProducts(params?: SimpleEarnProductListParams): Promise< ⋮---- -export interface AdjustFlexibleCryptoLoanLTVResponse { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - adjustmentAmount: string; - currentLTV: string; -} +getSimpleEarnLockedProductList( + params?: SimpleEarnProductListParams, +): Promise< ⋮---- -export interface GetFlexibleLoanLTVAdjustmentHistoryParams { - loanCoin?: string; - collateralCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +getFlexibleProductPosition( + params?: SimpleEarnFlexibleProductPositionParams, +): Promise< ⋮---- -export interface FlexibleLoanLTVAdjustmentHistory { - loanCoin: string; - collateralCoin: string; - direction: 'ADDITIONAL' | 'REDUCED'; - collateralAmount: string; - preLTV: string; - afterLTV: string; - adjustTime: number; -} +getLockedProductPosition( + params?: SimpleEarnLockedProductPositionParams, +): Promise< ⋮---- -export interface FlexibleLoanAssetData { - loanCoin: string; - flexibleInterestRate: string; - flexibleMinLimit: string; - flexibleMaxLimit: string; -} +getFlexiblePersonalLeftQuota(params: ⋮---- -export interface FlexibleLoanCollateralAssetData { - collateralCoin: string; - initialLTV: string; - marginCallLTV: string; - liquidationLTV: string; - maxLimit: string; -} +getLockedPersonalLeftQuota(params: ⋮---- -export interface GetFuturesLeadTraderStatusResponse { - code: string; - message: string; - data: { - isLeadTrader: boolean; - time: number; - }; - success: boolean; -} +/** + * + * SIMPLE EARN Endpoints - Earn + * + **/ ⋮---- -export interface GetFuturesLeadTradingSymbolWhitelistResponse { - code: string; - message: string; - data: { - symbol: string; - baseAsset: string; - quoteAsset: string; - }[]; -} +purchaseFlexibleProduct( + params: SimpleEarnSubscribeProductParams, +): Promise +⋮---- +subscribeSimpleEarnLockedProduct( + params: SimpleEarnSubscribeProductParams, +): Promise ⋮---- -export interface GetPayTradeHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; -} +redeemFlexibleProduct( + params: SimpleEarnRedeemFlexibleProductParams, +): Promise ⋮---- -export interface GetAllConvertPairsParams { - fromAsset?: string; - toAsset?: string; -} +redeemLockedProduct(params: { + positionId: string; +}): Promise ⋮---- -export interface SubmitConvertLimitOrderParams { - baseAsset: string; - quoteAsset: string; - limitPrice: number; - baseAmount?: number; - quoteAmount?: number; - side: 'BUY' | 'SELL'; - walletType?: 'SPOT' | 'FUNDING' | 'SPOT_FUNDING'; - expiredType: '1_D' | '3_D' | '7_D' | '30_D'; -} +setFlexibleAutoSubscribe(params: SetAutoSubscribeParams): Promise< ⋮---- -export interface ConvertLimitOpenOrder { - quoteId: string; - orderId: number; - orderStatus: string; - fromAsset: string; - fromAmount: string; - toAsset: string; - toAmount: string; - ratio: string; - inverseRatio: string; - createTime: number; - expiredTimestamp: number; -} +setLockedAutoSubscribe(params: SetAutoSubscribeParams): Promise< ⋮---- -export interface GetSpotRebateHistoryRecordsParams { - startTime?: number; - endTime?: number; - page?: number; -} +getFlexibleSubscriptionPreview( + params: GetFlexibleSubscriptionPreviewParams, +): Promise ⋮---- -export interface SpotRebateHistoryRecord { - asset: string; - type: number; - amount: string; - updateTime: number; -} +getLockedSubscriptionPreview( + params: GetLockedSubscriptionPreviewParams, +): Promise ⋮---- -export interface GetSpotRebateHistoryRecordsResponse { - status: string; - type: string; - code: string; - data: { - page: number; - totalRecords: number; - totalPageNum: number; - data: SpotRebateHistoryRecord[]; - }; -} +setLockedProductRedeemOption(params: { + positionId: string; + redeemTo: 'SPOT' | 'FLEXIBLE'; +}): Promise< ⋮---- -export interface GetNftTransactionHistoryParams { - orderType: number; - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} +/** + * + * SIMPLE EARN Endpoints - History + * + **/ ⋮---- -export interface NftToken { - network: string; - tokenId: string; - contractAddress: string; -} +getFlexibleSubscriptionRecord( + params: GetFlexibleSubscriptionRecordParams, +): Promise< ⋮---- -export interface NftTransaction { - orderNo: string; - tokens: NftToken[]; - tradeTime: number; - tradeAmount: string; - tradeCurrency: string; -} +getLockedSubscriptionRecord( + params: GetLockedSubscriptionRecordParams, +): Promise< ⋮---- -export interface GetNftDepositHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} +getFlexibleRedemptionRecord( + params: GetFlexibleRedemptionRecordParams, +): Promise< ⋮---- -export interface NftDeposit { - network: string; - txID: string | null; - contractAdrress: string; - tokenId: string; - timestamp: number; -} +getLockedRedemptionRecord(params: GetLockedRedemptionRecordParams): Promise< ⋮---- -export interface GetNftWithdrawHistoryParams { - startTime?: number; - endTime?: number; - limit?: number; - page?: number; -} +getFlexibleRewardsHistory(params: GetFlexibleRewardsHistoryParams): Promise< ⋮---- -export interface NftWithdraw { - network: string; - txID: string; - contractAdrress: string; - tokenId: string; - timestamp: number; - fee: number; - feeAsset: string; -} +getLockedRewardsHistory(params: GetLockedRewardsHistoryParams): Promise< ⋮---- -export interface GetNftAssetParams { - limit?: number; - page?: number; -} +getCollateralRecord(params: GetCollateralRecordParams): Promise< ⋮---- -export interface NftAsset { - network: string; - contractAddress: string; - tokenId: string; -} +getRateHistory(params: GetRateHistoryParams): Promise< ⋮---- -export interface CreateGiftCardParams { - token: string; - amount: number; -} +/** + * + * VIP LOAN Endpoints - Market Data + * + **/ ⋮---- -export interface CreateDualTokenGiftCardParams { - baseToken: string; - faceToken: string; - baseTokenAmount: number; - discount?: number; -} +getVipBorrowInterestRate(params: { + loanCoin: string; +}): Promise ⋮---- -export interface RedeemGiftCardParams { - code: string; - externalUid?: string; -} +getVipLoanInterestRateHistory( + params: VipLoanInterestRateHistoryParams, +): Promise< ⋮---- -export interface SimpleEarnProductListParams { - asset?: string; - current?: number; - size?: number; -} +getVipLoanableAssets(params: GetLoanableAssetsDataParams): Promise< ⋮---- -export interface SimpleEarnFlexibleProduct { - asset: string; - latestAnnualInterestRate: string; - tierAnnualPercentageRate: Record; - airDropPercentageRate: string; - canPurchase: boolean; - canRedeem: boolean; - isSoldOut: boolean; - hot: boolean; - minPurchaseAmount: string; - productId: string; - subscriptionStartTime: number; - status: string; -} +getVipCollateralAssets(params: ⋮---- -export interface SimpleEarnLockedProduct { - projectId: string; - detail: { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: string; - subscriptionStartTime: number; - extraRewardAsset: string; - extraRewardAPR: string; - boostRewardAsset: string; - boostApr: string; - boostEndTime: string; - }; - quota: { - totalPersonalQuota: string; - minimum: string; - }; -} +/** + * + * VIP LOAN Endpoints - User Info + * + **/ ⋮---- -export interface SimpleEarnSubscribeProductParams { - productId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; -} +getVipLoanOpenOrders(params: GetVipLoanOngoingOrdersParams): Promise< ⋮---- -export interface SimpleEarnSubscribeFlexibleProductResponse { - purchaseId: string; - success: boolean; -} +getVipLoanRepaymentHistory( + params: GetVipLoanRepaymentHistoryParams, +): Promise< ⋮---- -export interface SimpleEarnSubscribeLockedProductResponse { - purchaseId: string; - positionId: string; - success: boolean; -} +checkVipCollateralAccount(params: CheckVipCollateralAccountParams): Promise< ⋮---- -export interface SimpleEarnRedeemFlexibleProductParams { - productId: string; - redeemAll?: boolean; - amount?: number; - destAccount?: 'SPOT' | 'FUND'; -} +getVipApplicationStatus(params: GetApplicationStatusParams): Promise< +⋮---- +/** + * + * VIP LOAN Endpoints - Trade + * + **/ ⋮---- -export interface SimpleEarnRedeemResponse { - success: boolean; - redeemId: string; -} +renewVipLoan(params: VipLoanRenewParams): Promise ⋮---- -export interface SimpleEarnFlexibleProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; -} +repayVipLoan(params: VipLoanRepayParams): Promise ⋮---- -export interface SimpleEarnLockedProductPositionParams { - asset?: string; - productId?: string; - current?: number; - size?: number; - positionId?: string; -} +borrowVipLoan(params: VipLoanBorrowParams): Promise ⋮---- -export interface SimpleEarnLockedProductPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - isRenewable: boolean; - isAutoRenew: boolean; - redeemDate: string; - boostRewardAsset: string; - boostApr: string; - totalBoostRewardAmt: string; -} +getVipLoanFixedRateMarket(params: GetVipLoanFixedRateMarketParams): Promise< ⋮---- -export interface SimpleEarnAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedinBTC: string; - totalLockedinUSDT: string; -} +borrowVipLoanFixedRate( + params: VipLoanFixedRateBorrowParams, +): Promise ⋮---- -export interface GetSubAccountDepositHistoryParams { - subAccountId?: string; - coin?: string; - status?: number; - startTime?: number; - endTime?: number; - limit?: number; - offset?: number; -} +/** + * + * DUAL INVESTMENT Endpoints - Market Data + * + **/ ⋮---- -export interface SubAccountDeposit { - depositId: number; - subAccountId: string; - address: string; - addressTag: string; - amount: string; - coin: string; - insertTime: number; - transferType: number; - network: string; - status: number; - txId: string; - sourceAddress: string; - confirmTimes: string; - selfReturnStatus: number; -} +getDualInvestmentProducts( + params: GetDualInvestmentProductListParams, +): Promise< ⋮---- -// Request interface for querying sub account spot asset info -export interface QuerySubAccountSpotMarginAssetInfoParams { - subAccountId?: string; - page?: number; - size?: number; -} +/** + * + * DUAL INVESTMENT Endpoints - Trade + * + **/ ⋮---- -export interface SubaccountBrokerSpotAsset { - subAccountId: string; - totalBalanceOfBtc: string; -} +subscribeDualInvestmentProduct( + params: SubscribeDualInvestmentProductParams, +): Promise ⋮---- -export interface SubAccountBrokerMarginAsset { - marginEnable: boolean; - subAccountId: string; - totalAssetOfBtc?: string; - totalLiabilityOfBtc?: string; - totalNetAssetOfBtc?: string; - marginLevel?: string; -} +getDualInvestmentPositions( + params: GetDualInvestmentPositionsParams, +): Promise< ⋮---- -// Request interface for querying sub account futures asset info -export interface QuerySubAccountFuturesAssetInfoParams { - subAccountId?: string; - futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures - page?: number; - size?: number; -} +getDualInvestmentAccounts(): Promise ⋮---- -futuresType: number; // 1: USD Margined Futures, 2: COIN Margined Futures +getVipLoanAccruedInterest(params?: VipLoanAccruedInterestParams): Promise< ⋮---- -// Response interface for querying sub account futures asset info (USD Margined Futures) -export interface UsdtMarginedFuturesResponse { - subAccountId: string; - totalInitialMargin: string; - totalMaintenanceMargin: string; - totalWalletBalance: string; - totalUnrealizedProfit: string; - totalMarginBalance: string; - totalPositionInitialMargin: string; - totalOpenOrderInitialMargin: string; - futuresEnable: boolean; - asset: string; -} +/** + * @deprecated Binance removed `POST /sapi/v1/dci/product/auto_compound/edit-status`. + * Calls to this method will fail. Configure auto-compound for Dual Investment positions + * in the Binance web UI. This method will be removed in a future major version. + * connector-js dual-investment v6.0.0 removed `changeAutoCompoundStatus`. The published + * binance-api-swagger spec still lists the endpoint, so this method stays deprecated. + */ +updateAutoCompoundStatus( + params: ChangeAutoCompoundStatusParams, +): Promise ⋮---- -// Response interface for querying sub account futures asset info (COIN Margined Futures) -export interface CoinMarginedFuturesResponse { - subAccountId: string; - totalWalletBalanceOfUsdt: string; - totalUnrealizedProfitOfUsdt: string; - totalMarginBalanceOfUsdt: string; - futuresEnable: boolean; -} +/** + * + * GIFT CARD Endpoints - Market Data + * + **/ ⋮---- -// Combined response interface for querying sub account futures asset info -export interface BrokerFuturesSubAccountAssets { - data: (UsdtMarginedFuturesResponse | CoinMarginedFuturesResponse)[]; - timestamp: number; -} +createGiftCard(params: CreateGiftCardParams): Promise ⋮---- -export interface BrokerUniversalTransfer { - toId: string; - asset: string; - qty: string; - time: number; - status: string; - txnId: string; - clientTranId: string; - fromAccountType: string; - toAccountType: string; -} +createDualTokenGiftCard(params: CreateDualTokenGiftCardParams): Promise ⋮---- -// Request interface for changing sub account commission -export interface ChangeSubAccountCommissionParams { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission?: number; - marginTakerCommission?: number; -} +redeemGiftCard(params: RedeemGiftCardParams): Promise ⋮---- -// Response interface for changing sub account commission -export interface ChangeSubAccountCommissionResponse { - subAccountId: string; - makerCommission: number; - takerCommission: number; - marginMakerCommission: number; - marginTakerCommission: number; -} +verifyGiftCard(params: ⋮---- -// Request interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionParams { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; -} +getTokenLimit(params: ⋮---- -// Response interface for changing sub account USDT-Ⓜ futures commission adjustment -export interface ChangeSubAccountFuturesCommissionResponse { - subAccountId: string; - symbol: string; - makerAdjustment: number; - takerAdjustment: number; - makerCommission: number; - takerCommission: number; -} +getRsaPublicKey(): Promise ⋮---- -// Request interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface QuerySubAccountFuturesCommissionParams { - subAccountId: string; - symbol?: string; -} +/** + * + * NFT Endpoints - REST api + * + **/ ⋮---- -// Response interface for querying sub account USDT-Ⓜ futures commission adjustment -export interface BrokerSubAccountFuturesCommission { - subAccountId: string; - symbol: string; - makerCommission: number; - takerCommission: number; -} +getNftTransactionHistory(params: GetNftTransactionHistoryParams): Promise< ⋮---- -export interface ChangeSubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair: string; - makerAdjustment: number; - takerAdjustment: number; - recvWindow?: number; - timestamp: number; -} +getNftDepositHistory(params: GetNftDepositHistoryParams): Promise< ⋮---- -export interface QuerySubAccountCoinFuturesCommissionParams { - subAccountId: string; - pair?: string; - recvWindow?: number; - timestamp: number; -} +getNftWithdrawHistory(params: GetNftWithdrawHistoryParams): Promise< ⋮---- -// Response interface for querying sub account COIN-Ⓜ futures commission adjustment -export interface BrokerSubAccountCoinFuturesCommission { - subAccountId: string; - pair: string; - makerCommission: number; - takerCommission: number; -} +getNftAsset(params: GetNftAssetParams): Promise< +⋮---- +/** + * + * C2C Endpoints + * + **/ ⋮---- -export interface QueryBrokerSpotCommissionRebateParams { - subAccountId?: string; - startTime?: number; - endTime?: number; - page?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} +getC2CTradeHistory( + params: GetC2CTradeHistoryParams, +): Promise ⋮---- -// Response interface for querying spot commission rebate recent record -export interface BrokerCommissionRebate { - subaccountId: string; - income: string; - asset: string; - symbol: string; - tradeId: number; - time: number; - status: number; -} +/** + * + * FIAT Endpoints - REST api + * + **/ ⋮---- -export interface QueryBrokerFuturesCommissionRebateParams { - futuresType: number; // 1: USDT Futures, 2: Coin Futures - startTime: number; - endTime: number; - page?: number; - size?: number; - filterResult?: boolean; - recvWindow?: number; - timestamp: number; -} +getFiatOrderHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -futuresType: number; // 1: USDT Futures, 2: Coin Futures +getFiatPaymentsHistory( + params: GetFiatOrderHistoryParams, +): Promise ⋮---- -export interface SubmitMarginOTOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - sideEffectType?: SideEffects; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - autoRepayAtCancel?: boolean; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: number; - workingQuantity: number; - workingIcebergQty?: number; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingType: OrderType; - pendingSide: 'BUY' | 'SELL'; - pendingClientOrderId?: string; - pendingPrice?: number; - pendingStopPrice?: number; - pendingTrailingDelta?: number; - pendingQuantity: number; - pendingIcebergQty?: number; - pendingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; -} +fiatWithdraw(params: WithdrawFiatParams): Promise< ⋮---- -export interface MarginOTOOrder { - orderListId: number; - contingencyType: string; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: string; - timeInForce: string; - type: string; - side: string; - selfTradePreventionMode: string; - }[]; -} +fiatDeposit(params: FiatDepositParams): Promise ⋮---- -export interface SubmitMarginOTOCOOrderParams { - symbol: string; - isIsolated?: 'TRUE' | 'FALSE'; - sideEffectType?: SideEffects; - autoRepayAtCancel?: boolean; - listClientOrderId?: string; - newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'; - selfTradePreventionMode?: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - workingType: 'LIMIT' | 'LIMIT_MAKER'; - workingSide: 'BUY' | 'SELL'; - workingClientOrderId?: string; - workingPrice: string; - workingQuantity: string; - workingIcebergQty?: string; - workingTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingSide: 'BUY' | 'SELL'; - pendingQuantity: string; - pendingAboveType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingAboveClientOrderId?: string; - pendingAbovePrice?: string; - pendingAboveStopPrice?: string; - pendingAboveTrailingDelta?: string; - pendingAboveIcebergQty?: string; - pendingAboveTimeInForce?: 'GTC' | 'IOC' | 'FOK'; - pendingBelowType: 'LIMIT_MAKER' | 'STOP_LOSS' | 'STOP_LOSS_LIMIT'; - pendingBelowClientOrderId?: string; - pendingBelowPrice?: string; - pendingBelowStopPrice?: string; - pendingBelowTrailingDelta?: string; - pendingBelowIcebergQty?: string; - pendingBelowTimeInForce?: 'GTC' | 'IOC' | 'FOK'; -} +getFiatOrderDetail( + params: GetFiatOrderDetailParams, +): Promise ⋮---- -export interface QueryMarginOpenOTOOrderListsParams { - isIsolated?: 'TRUE' | 'FALSE'; - symbol?: string; -} +/** + * + * Rebate Endpoints + * + **/ ⋮---- -export interface MarginOpenOTOOrderList { - orderListId: number; - contingencyType: 'OTO' | 'OTOCO'; - listStatusType: string; - listOrderStatus: string; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; -} +getSpotRebateHistoryRecords( + params: GetSpotRebateHistoryRecordsParams, +): Promise ⋮---- -export interface MarginOTOCOOrder { - orderListId: number; - contingencyType: 'OTO' | 'OTOCO'; - listStatusType: 'EXEC_STARTED'; - listOrderStatus: 'EXECUTING'; - listClientOrderId: string; - transactionTime: number; - symbol: string; - isIsolated: boolean; - orders: { - symbol: string; - orderId: number; - clientOrderId: string; - }[]; - orderReports: { - symbol: string; - orderId: number; - orderListId: number; - clientOrderId: string; - transactTime: number; - price: string; - origQty: string; - executedQty: string; - cummulativeQuoteQty: string; - status: - | 'NEW' - | 'PARTIALLY_FILLED' - | 'FILLED' - | 'CANCELED' - | 'PENDING_CANCEL' - | 'REJECTED' - | 'EXPIRED' - | 'PENDING_NEW'; - timeInForce: 'GTC' | 'IOC' | 'FOK'; - type: - | 'LIMIT' - | 'MARKET' - | 'STOP_LOSS' - | 'STOP_LOSS_LIMIT' - | 'TAKE_PROFIT' - | 'TAKE_PROFIT_LIMIT' - | 'LIMIT_MAKER'; - side: 'BUY' | 'SELL'; - stopPrice?: string; - selfTradePreventionMode: - | 'EXPIRE_TAKER' - | 'EXPIRE_MAKER' - | 'EXPIRE_BOTH' - | 'NONE'; - }[]; -} +/** + * + * DERIVATIVES - Portfolio Margin Pro - Market Data + * This is in mainclient because it shares the same base url + * + **/ ⋮---- -export interface CreateSpecialLowLatencyKeyParams { - apiName: string; - symbol?: string; - ip?: string; - publicKey?: string; -} +getPortfolioMarginIndexPrice(params?: { + asset?: string; +}): Promise ⋮---- -export interface SpecialLowLatencyKeyResponse { - apiKey: string; - secretKey: string | null; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} +getPortfolioMarginAssetLeverage(): Promise< + GetPortfolioMarginAssetLeverageResponse[] + > { + return this.getPrivate('sapi/v1/portfolio/margin-asset-leverage'); ⋮---- -export interface SpecialLowLatencyKeyInfo { - apiName: string; - apiKey: string; - ip: string; - type: 'HMAC_SHA256' | 'RSA' | 'Ed25519'; -} +getPortfolioMarginProCollateralRate(): Promise< + GetPortfolioMarginProCollateralRateResponse[] + > { + return this.get('sapi/v1/portfolio/collateralRate'); ⋮---- -export interface MarginLiquidationLoan { - asset: string; - amount: string; - repaidAmount: string; - remainingAmount: string; -} +getPortfolioMarginProTieredCollateralRate(): Promise ⋮---- -export interface RepayMarginLiquidationLoanParams { - asset: string; - amount: string; -} +/** + * + * DERIVATIVES - Portfolio Margin Pro - Account + * This is in mainclient because it shares the same base url + * + **/ ⋮---- -export type MarginLiquidationLoanRepayStatus = 'SUCCESS' | 'PENDING'; +getPortfolioMarginProAccountInfo(): Promise ⋮---- -export interface MarginLiquidationLoanRepayResponse { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} +getPortfolioDeltaMode(): Promise ⋮---- -export interface GetMarginLiquidationLoanRepayHistoryParams { - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +switchPortfolioDeltaMode( + params: SwitchPortfolioDeltaModeParams, +): Promise< ⋮---- -export interface MarginLiquidationLoanRepayHistoryRecord { - repayId: number; - asset: string; - amount: string; - status: MarginLiquidationLoanRepayStatus; - createTime: number; -} +setPortfolioMarginMarginCallLevel( + params: SetPortfolioMarginMarginCallLevelParams, +): Promise ⋮---- -export interface MarginLiquidationLoanRepayHistoryResponse { - total: number; - rows: MarginLiquidationLoanRepayHistoryRecord[]; -} +getPortfolioMarginMarginCallLevel(): Promise ⋮---- -export interface SolStakingAccount { - bnsolAmount: string; // Amount in bNSOL - holdingInSOL: string; // Holding in SOL - thirtyDaysProfitInSOL: string; // 30 days profit in SOL -} +deletePortfolioMarginMarginCallLevel(): Promise ⋮---- -bnsolAmount: string; // Amount in bNSOL -holdingInSOL: string; // Holding in SOL -thirtyDaysProfitInSOL: string; // 30 days profit in SOL +bnbTransfer(params: BnbTransferParams): Promise< ⋮---- -export interface SolStakingQuota { - leftStakingPersonalQuota: string; // Remaining personal staking quota - leftRedemptionPersonalQuota: string; // Remaining personal redemption quota - minStakeAmount: string; // Minimum stake amount - minRedeemAmount: string; // Minimum redeem amount - redeemPeriod: number; // Redemption period in days - stakeable: boolean; // Whether staking is possible - redeemable: boolean; // Whether redemption is possible - soldOut: boolean; // Whether the staking is sold out - commissionFee: string; // Commission fee - nextEpochTime: number; // Time for the next epoch - calculating: boolean; // Whether calculations are ongoing -} +submitPortfolioMarginProFullTransfer(): Promise< ⋮---- -leftStakingPersonalQuota: string; // Remaining personal staking quota -leftRedemptionPersonalQuota: string; // Remaining personal redemption quota -minStakeAmount: string; // Minimum stake amount -minRedeemAmount: string; // Minimum redeem amount -redeemPeriod: number; // Redemption period in days -stakeable: boolean; // Whether staking is possible -redeemable: boolean; // Whether redemption is possible -soldOut: boolean; // Whether the staking is sold out -commissionFee: string; // Commission fee -nextEpochTime: number; // Time for the next epoch -calculating: boolean; // Whether calculations are ongoing +/** + * Fund collection by asset (`POST /sapi/v1/portfolio/asset-collection`). + * + * Optional `amount` and `futureType` must be sent together. `futureType` + * is the target wallet (`UM`, `CM`, or `OPTION`; `OPTION` is SPAN only). + * If neither is sent, collection behavior is unchanged. + */ +submitPortfolioMarginProSpecificTransfer(params: { + asset: string; + amount?: number; + futureType?: 'UM' | 'CM' | 'OPTION'; +}): Promise< ⋮---- -export interface SubscribeSolStakingResponse { - success: boolean; // Indicates if the subscription was successful - bnsolAmount: string; // Amount in bNSOL received - exchangeRate: string; // SOL amount per 1 BNSOL -} +repayPortfolioMarginProBankruptcyLoan(params: { + from?: 'SPOT' | 'MARGIN'; +}): Promise< ⋮---- -success: boolean; // Indicates if the subscription was successful -bnsolAmount: string; // Amount in bNSOL received -exchangeRate: string; // SOL amount per 1 BNSOL +getPortfolioMarginProBankruptcyLoanAmount(): Promise ⋮---- -export interface RedeemSolResponse { - success: boolean; // Indicates if the redemption was successful - solAmount: string; // Amount in SOL received - exchangeRate: string; // SOL amount per 1 BNSOL - arrivalTime: number; // Time of arrival for the redeemed SOL -} +repayFuturesNegativeBalance(): Promise< ⋮---- -success: boolean; // Indicates if the redemption was successful -solAmount: string; // Amount in SOL received -exchangeRate: string; // SOL amount per 1 BNSOL -arrivalTime: number; // Time of arrival for the redeemed SOL +updateAutoRepayFuturesStatus(params: ⋮---- -export interface GetSolStakingHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} +getAutoRepayFuturesStatus(): Promise< ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +getPortfolioMarginProInterestHistory( + params: GetPortfolioMarginProInterestHistoryParams, +): Promise ⋮---- -export interface SolStakingHistoryRecord { - time: number; // Time of the staking event - asset: string; // Asset involved, e.g., SOL - amount: string; // Amount staked - distributeAsset: string; // Asset distributed, e.g., BNSOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event -} +getPortfolioMarginProSpanAccountInfo(): Promise ⋮---- -time: number; // Time of the staking event -asset: string; // Asset involved, e.g., SOL -amount: string; // Amount staked -distributeAsset: string; // Asset distributed, e.g., BNSOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the staking event +getPortfolioMarginProAccountBalance(params?: { + asset?: string; +}): Promise ⋮---- -export interface GetSolRedemptionHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} +/** + * @deprecated + * Check Simple Earn endpoints for new way of doing it + */ +mintPortfolioMarginBFUSD( + params: PMProMintBFUSDParams, +): Promise ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +/** + * @deprecated + * Check Simple Earn endpointsfor new way of doing it + */ +redeemPortfolioMarginBFUSD(params: { + fromAsset: string; // BFUSD only + targetAsset: string; // USDT only + amount: number; +}): Promise ⋮---- -export interface SolRedemptionHistoryRecord { - time: number; // Time of the redemption event - arrivalTime: number; // Time of arrival for the redeemed SOL - asset: string; // Asset redeemed, e.g., BNSOL - amount: string; // Amount redeemed - distributeAsset: string; // Asset distributed, e.g., SOL - distributeAmount: string; // Amount distributed - exchangeRate: string; // Exchange rate at the time - status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event -} +fromAsset: string; // BFUSD only +targetAsset: string; // USDT only ⋮---- -time: number; // Time of the redemption event -arrivalTime: number; // Time of arrival for the redeemed SOL -asset: string; // Asset redeemed, e.g., BNSOL -amount: string; // Amount redeemed -distributeAsset: string; // Asset distributed, e.g., SOL -distributeAmount: string; // Amount distributed -exchangeRate: string; // Exchange rate at the time -status: 'PENDING' | 'SUCCESS' | 'FAILED'; // Status of the redemption event +getPortfolioMarginBankruptcyLoanRepayHistory(params?: { + startTime?: number; + endTime?: number; + current?: number; + size?: number; +}): Promise< ⋮---- -export interface GetBnsolRewardsHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} +/** + * Transfer LDUSDT as collateral for all types of Portfolio Margin account + */ +transferLDUSDTPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; + amount: number; +}): Promise< ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +/** + * Get transferable earn asset balance for all types of Portfolio Margin account + */ +getTransferableEarnAssetBalanceForPortfolioMargin(params: { + asset: string; + transferType: 'EARN_TO_FUTURE' | 'FUTURE_TO_EARN'; +}): Promise< +⋮---- +/** + * + * DERIVATIVES - Futures Data - Market + * This is in mainclient because it shares the same base url + * + **/ ⋮---- -export interface BnsolRewardHistoryRecord { - time: number; // Time of the reward event - amountInSOL: string; // Reward amount in SOL - holding: string; // BNSOL holding balance - holdingInSOL: string; // BNSOL holding balance in SOL - annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) -} +getFuturesTickLevelOrderbookDataLink( + params: GetFutureTickLevelOrderbookDataLinkParams, +): Promise< ⋮---- -time: number; // Time of the reward event -amountInSOL: string; // Reward amount in SOL -holding: string; // BNSOL holding balance -holdingInSOL: string; // BNSOL holding balance in SOL -annualPercentageRate: string; // Annual Percentage Rate (e.g., "0.5" means 50%) +/** + * + * BLVT Endpoints + * BLVT category is possibly @deprecated, found only in old docs + **/ ⋮---- -export interface GetBnsolRateHistoryReq { - startTime?: number; // Optional, start time in milliseconds - endTime?: number; // Optional, end time in milliseconds - current?: number; // Optional, current page, default is 1 - size?: number; // Optional, number of records per page, default is 10, max is 100 - recvWindow?: number; // Optional, cannot be greater than 60000 - timestamp: number; // Mandatory -} +getBlvtInfo(params?: ⋮---- -startTime?: number; // Optional, start time in milliseconds -endTime?: number; // Optional, end time in milliseconds -current?: number; // Optional, current page, default is 1 -size?: number; // Optional, number of records per page, default is 10, max is 100 -recvWindow?: number; // Optional, cannot be greater than 60000 -timestamp: number; // Mandatory +subscribeBlvt(params: SubscribeBlvtParams): Promise ⋮---- -export interface SolBoostRewardsHistoryReq { - type: 'CLAIM' | 'DISTRIBUTE'; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getBlvtSubscriptionRecord( + params: GetBlvtSubscriptionRecordParams, +): Promise ⋮---- -export interface SolBoostRewardsHistoryRecord { - time: number; - token: string; - amount: string; - bnsolHolding?: string; // Only present if type is "DISTRIBUTE" - status?: string; // Only present if type is "CLAIM" -} +redeemBlvt(params: RedeemBlvtParams): Promise ⋮---- -bnsolHolding?: string; // Only present if type is "DISTRIBUTE" -status?: string; // Only present if type is "CLAIM" +getBlvtRedemptionRecord( + params: GetBlvtRedemptionRecordParams, +): Promise ⋮---- -export interface BnsolRateHistoryRecord { - annualPercentageRate: string; // BNSOL APR - exchangeRate: string; // SOL amount per 1 BNSOL - time: number; // Time of the rate record -} +getBlvtUserLimitInfo(params: { + tokenName?: string; +}): Promise ⋮---- -annualPercentageRate: string; // BNSOL APR -exchangeRate: string; // SOL amount per 1 BNSOL -time: number; // Time of the rate record +/** + * + * Pay endpoints + * Found only in old docs, possibly @deprecated + **/ +getPayTransactions(params: GetPayTradeHistoryParams): Promise ⋮---- -export interface RiskUnitMM { - asset: string; - uniMaintainUsd: string; -} +/** + * + * INSTITUTIONAL LOAN - Account Endpoints + * + **/ ⋮---- -export interface PortfolioMarginProSpanAccountInfo { - uniMMR: string; - accountEquity: string; - actualEquity: string; - accountMaintMargin: string; - riskUnitMMList: RiskUnitMM[]; - marginMM: string; - otherMM: string; - accountStatus: - | 'NORMAL' - | 'MARGIN_CALL' - | 'SUPPLY_MARGIN' - | 'REDUCE_ONLY' - | 'ACTIVE_LIQUIDATION' - | 'FORCE_LIQUIDATION' - | 'BANKRUPTED'; - accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) -} +getInstLoanRiskUnit( + params?: GetInstitutionalLoanRiskUnitDetailsParams, +): Promise ⋮---- -accountType: 'PM_1' | 'PM_2' | 'PM_3'; // PM_1 for classic PM, PM_2 for PM, PM_3 for PM Pro(SPAN) +closeInstLoanRiskUnit(): Promise ⋮---- -export interface PortfolioMarginProAccountBalance { - asset: string; - totalWalletBalance: string; - crossMarginAsset: string; - crossMarginBorrowed: string; - crossMarginFree: string; - crossMarginInterest: string; - crossMarginLocked: string; - umWalletBalance: string; - umUnrealizedPNL: string; - cmWalletBalance: string; - cmUnrealizedPNL: string; - updateTime: number; - negativeBalance: string; - optionWalletBalance: string; // only for PM PRO SPAN - optionEquity: string; // only for PM PRO SPAN -} +addInstLoanCollateralAccount( + params: AddInstitutionalLoanCollateralAccountParams, +): Promise ⋮---- -optionWalletBalance: string; // only for PM PRO SPAN -optionEquity: string; // only for PM PRO SPAN +getActiveInstLoanRiskUnits(): Promise ⋮---- -export interface PMProMintBFUSDParams { - fromAsset: string; // USDT only - targetAsset: string; // BFUSD only - amount: number; -} +getClosedInstLoanRiskUnits( + params?: GetClosedInstitutionalLoanRiskUnitsParams, +): Promise ⋮---- -fromAsset: string; // USDT only -targetAsset: string; // BFUSD only +/** + * + * INSTITUTIONAL LOAN - Trade Endpoints + * + **/ ⋮---- -export interface PMProMintBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} +getInstLoanForceLiquidationRecord( + params: GetInstitutionalLoanForceLiquidationParams, +): Promise +/** + * + * INSTITUTIONAL LOAN - TransferEndpoints + * + **/ ⋮---- -export interface PMProRedeemBFUSDResponse { - fromAsset: string; - targetAsset: string; - fromAssetQty: number; - targetAssetQty: number; - rate: number; -} +transferInstLoanRiskUnit( + params: InstitutionalLoanRiskUnitTransferParams, +): Promise ⋮---- -export interface PMProBankruptcyLoanRepaymentHistory { - asset: string; - amount: string; - repayTime: number; -} +/** + * + * INSTITUTIONAL LOAN - Borrow/Repay Endpoints + * + **/ ⋮---- -export interface VipLoanInterestRateHistoryParams { - coin: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +getInstitutionalLoanMaxBorrowable( + params: GetInstitutionalLoanMaxBorrowableParams, +): Promise ⋮---- -export interface VipLoanInterestRateRecord { - coin: string; - annualizedInterestRate: string; - time: number; -} +borrowInstitutionalLoan( + params: InstitutionalLoanBorrowParams, +): Promise ⋮---- -export interface VipLoanAccruedInterestParams { - orderId?: number; - loanCoin?: string; - startTime?: number; - endTime?: number; - current?: number; - limit?: number; -} +getInstLoanInterestHistory( + params?: GetInstitutionalLoanInterestHistoryParams, +): Promise ⋮---- -export interface VipLoanAccruedInterestRecord { - loanCoin: string; - principalAmount: string; - interestAmount: string; - annualInterestRate: string; - accrualTime: number; - orderId: number; -} +repayInstitutionalLoan( + params: InstitutionalLoanRepayParams, +): Promise ⋮---- -export interface WithdrawTravelRuleParams { - coin: string; - withdrawOrderId?: string; - network?: string; - address: string; - addressTag?: string; - amount: number; - transactionFeeFlag?: boolean; - name?: string; - walletType?: number; - questionnaire: string; -} +getInstLoanBorrowRepayRecords( + params: GetInstitutionalLoanBorrowRepayRecordsParams, +): Promise ⋮---- -export interface GetTravelRuleWithdrawHistoryParams { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; - startTime?: number; - endTime?: number; -} +getMarginInterestRebateBalance(): Promise +⋮---- +getMarginInterestRebateBalanceRecords( + params?: GetMarginInterestRebateBalanceRecordsParams, +): Promise +⋮---- +/** + * + * ALPHA TRADING - Market Data + * https://developers.binance.com/docs/alpha + */ ⋮---- -export interface GetTravelRuleWithdrawHistoryV2Params { - trId?: string; - txId?: string; - withdrawOrderId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - offset?: number; - limit?: number; - startTime?: number; - endTime?: number; -} +getAlphaTokenList(): Promise ⋮---- -export interface SubmitTravelRuleDepositQuestionnaireParams { - tranId: number; - questionnaire: string; -} +getAlphaExchangeInfo(): Promise ⋮---- -export interface GetTravelRuleDepositHistoryParams { - trId?: string; - txId?: string; - tranId?: string; - network?: string; - coin?: string; - travelRuleStatus?: number; - pendingQuestionnaire?: boolean; - startTime?: number; - endTime?: number; - offset?: number; - limit?: number; -} +getAlphaAggTrades(params: AlphaAggTradesParams): Promise ⋮---- -export interface TravelRuleWithdrawHistoryRecord { - id: string; - trId: number; - amount: string; - transactionFee: string; - coin: string; - withdrawalStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - applyTime: string; - network?: string; - transferType: number; - withdrawOrderId?: string; - info: string; - confirmNo: number; - walletType: number; - txKey: string; - questionnaire: string; - completeTime?: string; -} +getAlphaKlines(params: AlphaKlinesParams): Promise ⋮---- -export interface SubmitTravelRuleDepositQuestionnaireResponse { - trId: number; - accepted: boolean; - info: string; -} +getAlphaTicker(params: ⋮---- -export interface TravelRuleDepositHistoryRecord { - trId: number; - tranId: number; - amount: string; - coin: string; - network: string; - depositStatus: number; - travelRuleStatus: number; - address: string; - addressTag?: string; - txId: string; - insertTime: number; - transferType: number; - confirmTimes: string; - unlockConfirm: number; - walletType: number; - requireQuestionnaire: boolean; - questionnaire: string | null; -} +getAlphaFullDepth( + params: AlphaFullDepthParams, +): Promise ⋮---- -export interface VASPInfo { - vaspName: string; - vaspCode?: string; - /** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ - identifier?: string; -} +/** + * + * EXCHANGE LINK - Account Endpoints + * https://developers.binance.com/docs/binance_link + */ ⋮---- -/** For populating the `vasp` field in deposit/withdrawal questionnaire. Use this instead of vaspCode. Both accepted until 28 May 2026. */ +createBrokerSubAccount( + params: CreateBrokerSubAccountParams, +): Promise ⋮---- -export interface TravelRuleCountryInfo { - countryCode: string; - countryName: string; - blockType: 'supported' | 'limited' | 'blocked'; - depositAllowed: boolean; - withdrawalAllowed: boolean; - hasRegionRestrictions: boolean; -} +getBrokerSubAccount( + params: GetBrokerSubAccountParams, +): Promise ⋮---- -export interface TravelRuleCountryListResponse { - countries: TravelRuleCountryInfo[]; - lastUpdated: number; -} +enableMarginBrokerSubAccount( + params: EnableMarginBrokerSubAccountParams, +): Promise ⋮---- -export interface GetTravelRuleRegionListParams { - countryCode: string; -} +createApiKeyBrokerSubAccount( + params: CreateApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface TravelRuleRegionInfo { - regionName: string; - blockType: 'supported' | 'limited' | 'blocked'; - depositAllowed: boolean; - withdrawalAllowed: boolean; -} +changePermissionApiKeyBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface TravelRuleRegionListResponse { - countryCode: string; - regions: TravelRuleRegionInfo[]; - lastUpdated: number; -} +changeComissionBrokerSubAccount( + params: ChangePermissionApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface GetVipLoanFixedRateMarketParams { - loanCoin: string; - duration?: number; - current?: number; - size?: number; -} +enableUniversalTransferApiKeyBrokerSubAccount( + params: EnableUniversalTransferApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface VipLoanFixedRateMarketRecord { - requestId: number; - requestNo: number; - coin: string; - interestRate: numberInString; - duration: number; - minimumAmount: numberInString; - availableAmount: numberInString; - estimatedInterest: numberInString; -} +updateIpRestrictionForSubAccountApiKey( + params: UpdateIpRestrictionForSubApiKey, +): Promise< ⋮---- -export interface VipLoanFixedRateBorrowParams { - supplyRequest: string; - borrowCoin: string; - loanTerm: number; - borrowUid: number; - collateralCoin: string; - collateralAccountId: string; - autoRepay?: boolean; -} +deleteIPRestrictionForSubAccountApiKey(params: { + subAccountId: string; + subAccountApiKey: string; + ipAddress?: string; +}): Promise< ⋮---- -export interface VipLoanFixedRateBorrowResponse { - borrowCoin: string; - borrowAmount: numberInString; - actualReceivedAmount: numberInString; - collateralCoin: string; - collateralAccountId: string; - borrowInterestRate: numberInString; - duration: string; - autoRepay: boolean; - orderId: number; - status: 'Succeeds' | 'Failed' | 'Processing'; -} +deleteApiKeyBrokerSubAccount( + params: DeleteApiKeyBrokerSubAccountParams, +): Promise ⋮---- -// Institutional Loan types -export interface InstitutionalLoanLiability { - assetName: string; - principal: string; - interest: string; -} +getSubAccountBrokerIpRestriction(params: { + subAccountId: string; + subAccountApiKey: string; +}): Promise< ⋮---- -export interface InstitutionalLoanWallet { - accountType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; -} +getApiKeyBrokerSubAccount( + params: GetApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface InstitutionalLoanCollateralAccount { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - wallets: InstitutionalLoanWallet[]; -} +getBrokerInfo(): Promise ⋮---- -export interface InstitutionalLoanRiskUnitDetails { - groupId: number; - leverageTier: string; - initialLtv: string; - marginCallLtv: string; - liquidationLtv: string; - liquidationExitLtv: string; - maxTransferOutLtv: string; - parentEmail: string; - creditEmail: string; - updateTime: number; - ltv: string; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - // Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. - transferOutLtv: string; - parentAccountFrozenAmount: string; - maxTransferOutAmount: string; - maxAllowedBorrowLimit: string; - liabilities: InstitutionalLoanLiability[]; - collateralAccounts: InstitutionalLoanCollateralAccount[]; -} +updateSubAccountBNBBurn(params: { + subAccountId: string; + spotBNBBurn: 'true' | 'false'; +}): Promise< +⋮---- +updateSubAccountMarginInterestBNBBurn(params: { + subAccountId: string; + interestBNBBurn: 'true' | 'false'; +}): Promise< +⋮---- +getSubAccountBNBBurnStatus(params: +⋮---- +/** + * Caution: + * The operation will delete a sub account under your brokerage master account. + * Please transfer out all funds from the sub account and delete API key of the sub account before deleting it. + * The deleted sub account CANNOT be reverted. + * The daily deletion limit for a broker Master is 20 sub accounts. + * You need to enable "trade" option for the api key which requests this endpoint. + */ +deleteBrokerSubAccount(params: ⋮---- -// Transfer-out LTV. Excludes Spot-wallet collateral, so it can be higher than `ltv`. +/** + * + * EXCHANGE LINK - Asset Endpoints + * https://developers.binance.com/docs/binance_link + */ ⋮---- -export interface GetInstitutionalLoanRiskUnitDetailsParams { - groupId?: number; -} +transferBrokerSubAccount( + params: TransferBrokerSubAccountParams, +): Promise ⋮---- -export interface CloseInstitutionalLoanRiskUnitResponse { - groupId: number; - status: 'CLOSED'; -} +getBrokerSubAccountHistory( + params: GetBrokerSubAccountHistoryParams, +): Promise ⋮---- -export interface AddInstitutionalLoanCollateralAccountParams { - groupId: number; - subEmail: string; - enableSpot: boolean; - enableMargin: boolean; -} +submitBrokerSubFuturesTransfer(params: { + fromId?: string; + toId?: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + asset: string; + amount: number; + clientTranId?: string; // The max length is 32 characters +}): Promise< ⋮---- -export interface InstitutionalLoanRiskUnitMember { - email: string; - type: 'CREDIT' | 'COLLATERAL'; - enableMargin: boolean; - enableSpot: boolean; -} +futuresType: number; // 1: USDT Futures, 2: COIN Futures ⋮---- -export interface ActiveInstitutionalLoanRiskUnit { - groupId: number; - members: InstitutionalLoanRiskUnitMember[]; - createTime: number; -} -export interface ClosedInstitutionalLoanRiskUnit { - groupId: number; - parentEmail: string; - creditEmail: string; - enabled: boolean; - createTime: number; - closeTime: number; -} +clientTranId?: string; // The max length is 32 characters ⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsParams { - current?: number; - size?: number; -} +getSubAccountFuturesTransferHistory(params: { + subAccountId: string; + futuresType: number; // 1: USDT Futures, 2: COIN Futures + clientTranId?: string; + startTime?: number; + endTime?: number; + page?: number; + limit?: number; +}): Promise ⋮---- -export interface GetClosedInstitutionalLoanRiskUnitsResponse { - total: number; - rows: ClosedInstitutionalLoanRiskUnit[]; -} +futuresType: number; // 1: USDT Futures, 2: COIN Futures ⋮---- -// Institutional Loan Force Liquidation interfaces -export interface InstitutionalLoanLiquidationSnapshot { - subEmail: string; - memberType: 'CREDIT' | 'COLLATERAL'; - walletType: 'SPOT' | 'PORTFOLIO_MARGIN' | 'CROSS_MARGIN'; - netEquity: string; - maintainMargin: string; -} +getBrokerSubDepositHistory( + params: GetSubAccountDepositHistoryParams, +): Promise ⋮---- -export interface InstitutionalLoanLiquidationSnapshotData { - snapshots: InstitutionalLoanLiquidationSnapshot[]; - liabilities: InstitutionalLoanLiability[]; -} +getBrokerSubAccountSpotAssets( + params: QuerySubAccountSpotMarginAssetInfoParams, +): Promise< ⋮---- -export interface InstitutionalLoanForceLiquidationRecord { - groupId: number; - startLtv: number; - endLtv: number; - liquidationStartTime: number; - liquidationEndTime: number; - totalNetEquity: string; - totalMaintenanceMargin: string; - totalLiability: string; - liquidationSnapshot: InstitutionalLoanLiquidationSnapshotData; -} +getSubAccountMarginAssetInfo( + params: QuerySubAccountSpotMarginAssetInfoParams, +): Promise< ⋮---- -export interface GetInstitutionalLoanForceLiquidationParams { - groupId?: number; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} +querySubAccountFuturesAssetInfo( + params: QuerySubAccountFuturesAssetInfoParams, +): Promise< ⋮---- -export interface GetInstitutionalLoanForceLiquidationResponse { - total: number; - rows: InstitutionalLoanForceLiquidationRecord[]; -} +universalTransferBroker(params: UniversalTransferBrokerParams): Promise< ⋮---- -// Risk Unit Transfer interfaces -export interface InstitutionalLoanRiskUnitTransferParams { - subEmail?: string; // Optional: subEmail can be credit account or collateral account - asset: string; // Asset Name - amount: number; // Transfer amount of the asset -} +getUniversalTransferBroker( + params: GetUniversalTransferBrokerParams, +): Promise ⋮---- -subEmail?: string; // Optional: subEmail can be credit account or collateral account -asset: string; // Asset Name -amount: number; // Transfer amount of the asset +/** + * + * EXCHANGE LINK - Fee Endpoints + * https://developers.binance.com/docs/binance_link + */ ⋮---- -// Additional institutional loan types for borrow, repay, and interest history -export interface GetInstitutionalLoanMaxBorrowableParams { - groupId?: number; - assetName: string; -} +updateBrokerSubAccountCommission( + params: ChangeSubAccountCommissionParams, +): Promise ⋮---- -export interface InstitutionalLoanMaxBorrowableResponse { - maxBorrowableAmount: numberInString | null; -} +updateBrokerSubAccountFuturesCommission( + params: ChangeSubAccountFuturesCommissionParams, +): Promise ⋮---- -export interface InstitutionalLoanBorrowParams { - groupId: number; - assetName: string; - amount: number; -} +getBrokerSubAccountFuturesCommission( + params: QuerySubAccountFuturesCommissionParams, +): Promise ⋮---- -export interface InstitutionalLoanBorrowResponse { - transactionId: string; - amount: number; - status: string; -} +updateBrokerSubAccountCoinFuturesCommission( + params: ChangeSubAccountCoinFuturesCommissionParams, +): Promise ⋮---- -export interface InstitutionalLoanRepayParams { - groupId: number; - assetName: string; - amount: number; -} +getBrokerSubAccountCoinFuturesCommission( + params: QuerySubAccountCoinFuturesCommissionParams, +): Promise ⋮---- -export interface InstitutionalLoanRepayResponse { - transactionId: string; - amount: number; -} +getBrokerSpotCommissionRebate( + params: QueryBrokerSpotCommissionRebateParams, +): Promise ⋮---- -export interface GetInstitutionalLoanInterestHistoryParams { - groupId?: number; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +getBrokerFuturesCommissionRebate( + params: QueryBrokerFuturesCommissionRebateParams, +): Promise ⋮---- -export interface InstitutionalLoanInterestHistoryRecord { - groupId: number; - assetName: string; - principal: string; - interestRate: string; - interest: string; - interestTimestamp: number; -} +/** + * + * @deprecated + */ +// USD & Coin-M can be found under API getIncome() (find "API rebate" in results) +getBrokerSpotRebateHistory(days: 7 | 30, customerId?: string) ⋮---- -export interface InstitutionalLoanInterestHistoryResponse { - total: number; - rows: InstitutionalLoanInterestHistoryRecord[]; -} +/** + * Broker Endpoints - only on old docs + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead - https://developers.binance.com/docs/binance_link + */ ⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsParams { - groupId?: number; // Optional: Risk unit unique identifier - type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY - asset?: string; // Optional: Asset name - startTime?: number; // Optional: Start time - endTime?: number; // Optional: End time - current?: number; // Optional: The currently querying page. Start from 1. Default:1 - size?: number; // Optional: Default:10 Max:100 - recvWindow?: number; // Optional: The value cannot be greater than 60000 - timestamp: number; // Required -} +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerIfNewSpotUser(): Promise< ⋮---- -groupId?: number; // Optional: Risk unit unique identifier -type: 'BORROW' | 'REPAY'; // Required: BORROW or REPAY -asset?: string; // Optional: Asset name -startTime?: number; // Optional: Start time -endTime?: number; // Optional: End time -current?: number; // Optional: The currently querying page. Start from 1. Default:1 -size?: number; // Optional: Default:10 Max:100 -recvWindow?: number; // Optional: The value cannot be greater than 60000 -timestamp: number; // Required +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerSubAccountDepositHistory( + params?: GetBrokerSubAccountDepositHistoryParams, +): Promise +⋮---- +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +getBrokerUserCustomisedId(market: 'spot' | 'futures') ⋮---- -export interface InstitutionalLoanBorrowRepayRecord { - tranId: number; // Transaction ID - assetName: string; // Asset name - amount: number; // Amount - status: 'CONFIRM' | 'FAILED'; // Status - type: 'BORROW' | 'REPAY'; // Type - timestamp: number; // Create Time - principal?: number; // Only present for REPAY type - interest?: number; // Only present for REPAY type -} +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableFuturesBrokerSubAccount( + params: EnableFuturesBrokerSubAccountParams, +): Promise ⋮---- -tranId: number; // Transaction ID -assetName: string; // Asset name -amount: number; // Amount -status: 'CONFIRM' | 'FAILED'; // Status -type: 'BORROW' | 'REPAY'; // Type -timestamp: number; // Create Time -principal?: number; // Only present for REPAY type -interest?: number; // Only present for REPAY type +/** + * @deprecated, found only in old docs + * Use EXCHANGE LINK endpoints instead + **/ +enableMarginApiKeyBrokerSubAccount( + params: EnableMarginApiKeyBrokerSubAccountParams, +): Promise ⋮---- -export interface GetInstitutionalLoanBorrowRepayRecordsResponse { - total: number; - rows: InstitutionalLoanBorrowRepayRecord[]; -} +/** + * Validate syntax meets requirements set by binance. Log warning if not. + */ +private validateOrderId( + params: + | NewSpotOrderParams + | CancelOrderParams + | NewOCOParams + | CancelOCOParams + | NewOrderListParams, + orderIdProperty: OrderIdProperty, +): void ⋮---- -export interface MarginInterestRebateBalanceResponse { - asset: string; - balance: string; - totalGranted: string; - totalConsumed: string; -} +/** + * + * User Data Stream Endpoints + * + **/ ⋮---- -export interface GetMarginInterestRebateBalanceRecordsParams { - type?: 0 | 1 | 2; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +// spot +getSpotUserDataListenKey(): Promise< ⋮---- -export interface MarginInterestRebateBalanceRecord { - type: 'ADD' | 'DEDUCT' | 'INTEREST_OFFSET'; - rebateAsset: string; - delta: string; - createTime: number; - groupId?: number; - liabilityAsset?: string; - deductedInterest?: string; - exchangeRate?: string; -} +keepAliveSpotUserDataListenKey(listenKey: string): Promise ⋮---- -export interface MarginInterestRebateBalanceRecordsResponse { - total: number; - rows: MarginInterestRebateBalanceRecord[]; -} +closeSpotUserDataListenKey(listenKey: string): Promise ⋮---- -// On-chain Yields types +/** + * Get a cross margin user data listen key + */ +getMarginUserDataListenKey(): Promise< ⋮---- -export interface OnchainYieldsLockedProductListParams { - asset?: string; - current?: number; - size?: number; -} +keepAliveMarginUserDataListenKey(listenKey: string): Promise ⋮---- -export interface OnchainYieldsLockedProductDetail { - asset: string; - rewardAsset: string; - duration: number; - renewable: boolean; - isSoldOut: boolean; - apr: string; - status: 'PREHEATING' | 'PURCHASING'; - subscriptionStartTime: string; - canRedeemToFlex: boolean; -} +closeMarginUserDataListenKey(listenKey: string): Promise ⋮---- -export interface OnchainYieldsLockedProductQuota { - totalPersonalQuota: string; - minimum: string; -} +// isolated margin +getIsolatedMarginUserDataListenKey(params: { + symbol: string; +}): Promise< ⋮---- -export interface OnchainYieldsLockedProduct { - projectId: string; - detail: OnchainYieldsLockedProductDetail; - quota: OnchainYieldsLockedProductQuota; -} +keepAliveIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -export interface OnchainYieldsLockedProductListResponse { - rows: OnchainYieldsLockedProduct[]; - total: number; -} +closeIsolatedMarginUserDataListenKey(params: { + symbol: string; + listenKey: string; +}): Promise ⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaParams { - projectId: string; -} +/** + * Get a cross margin risk data listen key + */ +getMarginRiskUserDataListenKey(): Promise< ⋮---- -export interface OnchainYieldsLockedPersonalLeftQuotaResponse { - leftPersonalQuota: string; -} +keepAliveMarginRiskUserDataListenKey(listenKey: string): Promise ⋮---- -export interface OnchainYieldsLockedPositionParams { - asset?: string; - positionId?: number; - projectId?: string; - current?: number; - size?: number; -} +closeMarginRiskUserDataListenKey(): Promise ⋮---- -export interface OnchainYieldsLockedPosition { - positionId: string; - projectId: string; - asset: string; - amount: string; - purchaseTime: string; - duration: string; - accrualDays: string; - rewardAsset: string; - APY: string; - rewardAmt: string; - nextPay?: string; - nextPayDate?: string; - payPeriod?: string; - rewardsPayDate?: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; - redeemingAmt?: string; - redeemTo?: 'FLEXIBLE' | 'SPOT'; - canRedeemEarly: boolean; - autoSubscribe: boolean; - type: 'AUTO' | 'NORMAL'; - status: 'HOLDING' | 'REDEEMING' | 'RENEWING' | 'NEW_TRANSFERRING'; -} +/** + * Start a Margin user data stream (`POST /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. + * + * New and migrated accounts receive -3086 from + * `POST /sapi/v1/margin/listen-key` and `POST /sapi/v1/userListenToken`. + * Connect with `wss://fstream.binance.com/private/ws/`. + */ +getMarginUserDataListenKeyV2(): Promise< ⋮---- -export interface OnchainYieldsLockedPositionResponse { - rows: OnchainYieldsLockedPosition[]; - total: number; -} +/** + * Keepalive a Margin user data stream (`PUT /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. `listenKey` is a query parameter. + */ +keepAliveMarginUserDataListenKeyV2(listenKey: string): Promise ⋮---- -export interface OnchainYieldsAccountResponse { - totalAmountInBTC: string; - totalAmountInUSDT: string; - totalFlexibleAmountInBTC: string; - totalFlexibleAmountInUSDT: string; - totalLockedInBTC: string; - totalLockedInUSDT: string; -} +/** + * Close a Margin user data stream (`DELETE /sapi/v2/margin/listen-key`). + * Weight(IP): 1. USER_STREAM. The listen key is not a parameter. + */ +closeMarginUserDataListenKeyV2(): Promise ⋮---- -// On-chain Yields Earn types +getMarginUtaUserDataListenKey(): Promise< ⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; -} +keepAliveMarginUtaUserDataListenKey(listenKey: string): Promise ⋮---- -export interface OnchainYieldsLockedSubscriptionPreviewResponse { - rewardAsset: string; - totalRewardAmt: string; - nextPay?: string; - nextPayDate?: string; - rewardsPayDate?: string; - valueDate: string; - rewardsEndDate: string; - deliverDate?: string; - nextSubscriptionDate?: string; -} +closeMarginUtaUserDataListenKey(): Promise ⋮---- -export interface OnchainYieldsLockedSubscribeParams { - projectId: string; - amount: number; - autoSubscribe?: boolean; - sourceAccount?: 'SPOT' | 'FUND' | 'ALL'; - redeemTo?: 'SPOT' | 'FLEXIBLE'; - channelId?: string; - clientId?: string; -} +/** + * Get/create margin account listenToken for the user data stream + * https://developers.binance.com/docs/margin_trading/trade-data-stream + */ +getMarginListenToken(params?: { + symbol?: string; + isIsolated?: boolean; + validity?: number; +}): Promise< ⋮---- -export interface OnchainYieldsLockedSubscribeResponse { - purchaseId: number; - positionId: string; - amount: string; - success: boolean; -} +/** + * + * DEPRECATED ENDPOINTS + * + **/ +/** + * + * BSwap Endpoints + * @deprecated as of 2024-01-19 + **/ +⋮---- +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapLiquidity(params?: ⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeParams { - positionId: string; - autoSubscribe: boolean; -} +/** + * @deprecated as of 2024-01-19 + **/ +addBSwapLiquidity(params: AddBSwapLiquidityParams): Promise< ⋮---- -export interface OnchainYieldsLockedSetAutoSubscribeResponse { - success: boolean; -} +/** + * @deprecated as of 2024-01-19 + **/ +removeBSwapLiquidity(params: RemoveBSwapLiquidityParams): Promise< ⋮---- -export interface OnchainYieldsLockedSetRedeemOptionParams { - positionId: string; - redeemTo: 'SPOT' | 'FLEXIBLE'; -} +/** + * @deprecated as of 2024-01-19 + **/ +getBSwapOperations( + params?: BSwapOperationsParams, +): Promise ⋮---- -export interface OnchainYieldsLockedSetRedeemOptionResponse { - success: boolean; -} +/** + * + * Savings Endpoints + * @deprecated as of 2023-06-22, now Simple Earn + **/ ⋮---- -export interface OnchainYieldsLockedRedeemParams { - positionId: number; - channelId?: string; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyPurchaseQuotaFlexibleProduct(params: { + productId: string; +}): Promise ⋮---- -export interface OnchainYieldsLockedRedeemResponse { - redeemId: number; - success: boolean; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLeftDailyRedemptionQuotaFlexibleProduct(params: { + productId: string; + }): Promise< + LeftDailyPurchaseQuotaFlexibleProductResponse & { + dailyQuota: string; + minRedemptionAmount: string; + } + > { + return this.getPrivate('sapi/v1/lending/daily/userRedemptionQuota', params); ⋮---- -// On-chain Yields History types +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +purchaseFixedAndActivityProject(params: { + projectId: string; + lot: number; +}): Promise ⋮---- -export interface OnchainYieldsLockedSubscriptionRecordParams { - purchaseId?: string; - clientId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProjects( + params: FixedAndActivityProjectParams, +): Promise ⋮---- -export interface OnchainYieldsLockedSubscriptionRecord { - positionId: string; - purchaseId: string; - projectId: string; - clientId: string; - time: number; - asset: string; - amount: string; - lockPeriod: string; - type: 'NORMAL' | 'AUTO'; - sourceAccount: 'SPOT' | 'FUNDING' | 'SPOTANDFUNDING'; - amtFromSpot?: string; - amtFromFunding?: string; - status: 'PURCHASING' | 'SUCCESS' | 'FAILED'; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getFixedAndActivityProductPosition( + params: FixedAndActivityProjectPositionParams, +): Promise ⋮---- -export interface OnchainYieldsLockedSubscriptionRecordResponse { - rows: OnchainYieldsLockedSubscriptionRecord[]; - total: number; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getLendingAccount(): Promise ⋮---- -export interface OnchainYieldsLockedRewardsHistoryParams { - positionId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getPurchaseRecord(params: PurchaseRecordParams): Promise ⋮---- -export interface OnchainYieldsLockedRewardsRecord { - positionId: string; - time: number; - asset: string; - lockPeriod: string; - amount: string; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getRedemptionRecord(params: PurchaseRecordParams): Promise ⋮---- -export interface OnchainYieldsLockedRewardsHistoryResponse { - rows: OnchainYieldsLockedRewardsRecord[]; - total: number; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +getInterestHistory(params: PurchaseRecordParams): Promise ⋮---- -export interface OnchainYieldsLockedRedemptionRecordParams { - positionId?: number; - redeemId?: string; - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; -} +/** + * @deprecated as of 2023-06-22, now Simple Earn + */ +changeFixedAndActivityPositionToDailyPosition(params: { + projectId: string; + lot: number; + positionId?: number; +}): Promise ⋮---- -export interface OnchainYieldsLockedRedemptionRecord { - positionId: string; - redeemId: number; - time: number; - asset: string; - lockPeriod: string; - amount: string; - originalAmount: string; - type: 'NORMAL' | 'EARLY' | 'CONVERT'; - deliverDate: string; - lossAmount: string; - isComplete: boolean; - rewardAsset: string; - rewardAmt: string; - status: 'CREATED' | 'PAID'; -} +/** + * + * Wallet Endpoints + * @deprecated + **/ ⋮---- -export interface OnchainYieldsLockedRedemptionRecordResponse { - rows: OnchainYieldsLockedRedemptionRecord[]; - total: number; -} +/** + * @deprecated + */ +enableConvertSubAccount(params: EnableConvertSubAccountParams): Promise +⋮---- +/** + * @deprecated - deleted as of 2024-11-21 + * + */ +convertBUSD(params: ConvertTransfer): Promise ⋮---- /** - * ALPHA TRADING INTERFACES + * @deprecated + */ +getConvertBUSDHistory(params: GetConvertBUSDHistoryParams): Promise< + +================ +File: README.md +================ +# Node.js & JavaScript SDK for Binance REST APIs & WebSockets + +[![Build & Test](https://github.com/sieblyio/binance/actions/workflows/test.yml/badge.svg)](https://github.com/sieblyio/binance/actions/workflows/test.yml) +[![npm version](https://img.shields.io/npm/v/binance)][1] +[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1] +[![users count](https://dependents.info/sieblyio/binance/badge?label=users)](https://dependents.info/sieblyio/binance) +[![npm downloads](https://img.shields.io/npm/dt/binance)][1] +[![last commit](https://img.shields.io/github/last-commit/sieblyio/binance)][1] +[![CodeFactor](https://www.codefactor.io/repository/github/sieblyio/binance/badge)](https://www.codefactor.io/repository/github/sieblyio/binance) +[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) +[![Binance Tutorial](https://img.shields.io/badge/Binance%20Tutorial-siebly.io-blue)](https://siebly.io/sdk/binance/javascript/tutorial) + +

+ + + + SDK Logo + + +

+ +[1]: https://www.npmjs.com/package/binance + +> [!TIP] +> Upcoming change: As part of the [Siebly.io](https://siebly.io/) brand, this SDK is now hosted under our [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes. + +Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets. + +Spot user data stream (listen key is created and kept alive for you): + +```javascript +import { WebsocketClient } from 'binance'; +const ws = new WebsocketClient({ api_key: 'key', api_secret: 'secret' }); +ws.on('formattedMessage', (data) => console.log(data)); +ws.subscribeSpotUserDataStream(); +``` + +- Professional, robust & performant Binance SDK with leading trading volume in production (livenet). +- Extensive integration with Binance REST APIs, WebSockets & WebSocket APIs. +- Complete TypeScript support (with type declarations for all API requests & responses). +- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures. + - Strongly typed requests and responses. + - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. +- Actively maintained with a modern, promise-driven interface. +- Support for all authentication mechanisms available on Binance: + - HMAC + - RSA + - Ed25519 (required for WS API login, else each request is signed). + - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication. +- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM & CoinM Futures. + - Event driven messaging. + - Smart WebSocket persistence + - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect. + - Automatically handle listenKey persistence and expiration/refresh. + - Emit `reconnected` event when dropped connection is restored. + - Strongly typed on most WebSocket events, with typeguards available for TypeScript users. + - Optional: + - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers). + - Automatic beautification of REST responses (parsing numbers in strings to numbers). +- Supports WebSocket API on all available product groups, including Spot & Futures: + - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or; + - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration. +- Heavy automated end-to-end testing with real API calls. + - End-to-end testing before any release. + - Real API calls in e2e tests. +- Proxy support via axios integration. +- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). +- QuickStart Guide: [Binance JavaScript QuickStart Guide](https://siebly.io/sdk/binance/javascript) +- Binance JavaScript Tutorial: [Binance JavaScript REST API & WebSocket Tutorial](https://siebly.io/sdk/binance/javascript/tutorial) + +## Table of Contents + +- [Installation](#installation) +- [Examples](#examples) + - [REST API Examples](./examples/REST) + - [WebSocket Examples](./examples/WebSockets) + - [WebSocket Consumers](./examples/WebSockets/) + - [WebSocket API](./examples/WebSockets/ws-api-client.ts) +- [Issues & Discussion](#issues--discussion) +- [Related Projects](#related-projects) +- [Documentation Links](#documentation) +- [Usage](#usage) + - [Demo Trading vs Testnet](#demo-trading-vs-testnet) + - [REST API Clients](#rest-api-clients) + - [REST Main Client](#rest-main-client) + - [REST USD-M Futures](#rest-usd-m-futures) + - [REST COIN-M Futures](#rest-coin-m-futures) + - [REST Portfolio Margin](#rest-portfolio-margin) + - [WebSockets](#websockets) + - [WebSocket Consumers](#websocket-consumers) + - [WebSocket API](#websocket-api) + - [Event Driven API](#event-driven-api) + - [Promise Driven API](#async-await-api) + - [Market Maker Endpoints](#market-maker-endpoints) + - [Using Market Maker Endpoints](#using-market-maker-endpoints) + - [Best practice](#best-practice) + - [Customise Logging](#customise-logging) + - [Frontend Usage](#browserfrontend-usage) + - [Import](#import) + - [Webpack](#webpack) +- [LLMs & AI](#use-with-llms--ai) +- [Contributions & Thanks](#contributions--thanks) + +## Installation + +`npm install binance --save` + +## Examples + +Refer to the [examples](./examples) folder for implementation demos. + +## Issues & Discussion + +- Issues? Check the [issues tab](https://github.com/sieblyio/binance/issues). +- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. +- Questions about Binance APIs & WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram. +- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) + + + +## Related Projects + +Check out our JavaScript/TypeScript/Node.js SDKs & Projects: + +- Visit our website: [https://Siebly.io](https://siebly.io/) +- Try our REST API & WebSocket SDKs published on npmjs: + - [Bybit JavaScript SDK: bybit-api](https://www.npmjs.com/package/bybit-api) + - [Kraken JavaScript SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api) + - [OKX JavaScript SDK: okx-api](https://www.npmjs.com/package/okx-api) + - [Binance JavaScript SDK: binance](https://www.npmjs.com/package/binance) + - [Gate (gate.com) JavaScript SDK: gateio-api](https://www.npmjs.com/package/gateio-api) + - [Bitget JavaScript SDK: bitget-api](https://www.npmjs.com/package/bitget-api) + - [Kucoin JavaScript SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api) + - [Coinbase JavaScript SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api) + - [HTX JavaScript SDK: @siebly/htx-api](https://www.npmjs.com/package/@siebly/htx-api) +- Try my misc utilities: + - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks) + - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate) +- Check out my examples: + - [awesome-crypto-examples Node.js](https://github.com/sieblyio/awesome-crypto-examples) + + +## Documentation + +Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation. + +- Binance API Documentation + - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs) + - [ Derivatives ](https://developers.binance.com/docs/derivatives) + - [ Margin ](https://developers.binance.com/docs/margin_trading) + - [ Wallet ](https://developers.binance.com/docs/wallet) +- [Find all products here](https://developers.binance.com/en) +- [REST Endpoint Function List](./docs/endpointFunctionList.md) +- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance) + +## Structure + +This project uses typescript. Resources are stored in 3 key structures: + +- [src](./src) - the whole connector written in typescript +- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. +- [dist](./dist) - the packed bundle of the project for use in browser environments. + +--- + +# Usage + +Create API credentials at Binance + +- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO) +- [Testnet](https://testnet.binance.vision/). +- [Testnet Futures](testnet.binancefuture.com). +- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading. + +### Demo Trading vs Testnet + +Binance offers two testing environments: + +- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures. +- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing. + +To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information. + +## REST API Clients + +There are several REST API modules as there are some differences in each API group. + +1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management. +2. `USDMClient` for USD-M futures APIs. +3. `CoinMClient` for COIN-M futures APIs. +4. `PortfolioClient` for Portfolio Margin APIs. + +Vanilla Options is not yet available. Please get in touch if you're looking for this. + +### REST Main Client + +The MainClient covers all endpoints under the main "api\*.binance.com" subdomains, including but not limited to endpoints in the following product groups: + +- Spot +- Cross & isolated margin +- Convert +- Wallet +- Futures management (transfers & history) +- Sub account management +- Misc transfers +- Auto & dual invest +- Staking +- Mining +- Loans & VIP loans +- Simple Earn +- NFTs +- C2C +- Exchange Link +- Alpha trading + +Refer to the following links for a complete list of available endpoints: + +- [Binance Node.js & JavaScript SDK Endpoint Map](https://github.com/sieblyio/binance/blob/master/docs/endpointFunctionList.md) +- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints) + +Start by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. + +```javascript +import { MainClient } from 'binance'; + +// or, if you prefer `require()`: +// const { MainClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new MainClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getAccountTradeList({ symbol: 'BTCUSDT' }) + .then((result) => { + console.log('getAccountTradeList result: ', result); + }) + .catch((err) => { + console.error('getAccountTradeList error: ', err); + }); + +client + .getExchangeInfo() + .then((result) => { + console.log('getExchangeInfo inverse result: ', result); + }) + .catch((err) => { + console.error('getExchangeInfo inverse error: ', err); + }); +``` + +See [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc. + +### REST USD-M Futures + +Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls. + +```javascript +import { USDMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { USDMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewOrder error: ', err); + }); +``` + +See [usdm-client.ts](./src/usdm-client.ts) for further information. + +### REST COIN-M Futures + +Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { CoinMClient } from 'binance'; + +// or, if you prefer `require()`: +// const { CoinMClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getSymbolOrderBookTicker() + .then((result) => { + console.log('getSymbolOrderBookTicker result: ', result); + }) + .catch((err) => { + console.error('getSymbolOrderBookTicker error: ', err); + }); +``` + +See [coinm-client.ts](./src/coinm-client.ts) for further information. + +### REST Portfolio Margin + +Start by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials. + +```javascript +import { PortfolioClient } from 'binance'; + +// or, if you prefer `require()`: +// const { PortfolioClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +const client = new PortfolioClient({ + api_key: API_KEY, + api_secret: API_SECRET, + // Connect to testnet environment + // testnet: true, +}); + +client + .getBalance() + .then((result) => { + console.log('getBalance result: ', result); + }) + .catch((err) => { + console.error('getBalance error: ', err); + }); + +client + .submitNewUMOrder({ + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + }) + .then((result) => { + console.log('submitNewUMOrder result: ', result); + }) + .catch((err) => { + console.error('submitNewUMOrder error: ', err); + }); +``` + +See [portfolio-client.ts](./src/portfolio-client.ts) for further information. + +## WebSockets + +### WebSocket Consumers + +All websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required. + +The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance: + +```javascript +import { WebsocketClient } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketClient } = require('binance'); + +const API_KEY = 'xxx'; +const API_SECRET = 'yyy'; + +/** + * The WebsocketClient will manage individual connections for you, under the hood. + * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. */ -⋮---- -export interface AlphaToken { - alphaId: number; - symbol: string; - name: string; - chainId: string; - contractAddress: string; - decimals?: number; -} -⋮---- -export interface AlphaExchangeFilter { - filterType: string; - minPrice?: string; - maxPrice?: string; - tickSize?: string; - stepSize?: string; - maxQty?: string; - minQty?: string; - limit?: number; - minNotional?: string; - maxNotional?: string; - multiplierDown?: string; - multiplierUp?: string; - bidMultiplierUp?: string; - askMultiplierUp?: string; - bidMultiplierDown?: string; - askMultiplierDown?: string; -} -⋮---- -export interface AlphaSymbol { - symbol: string; - status: string; - baseAsset: string; - quoteAsset: string; - pricePrecision: number; - quantityPrecision: number; - baseAssetPrecision: number; - quotePrecision: number; - filters: AlphaExchangeFilter[]; - orderTypes: string[]; -} -⋮---- -export interface AlphaAsset { - asset: string; -} -⋮---- -export interface AlphaExchangeInfo { - timezone: string; - assets: AlphaAsset[]; - symbols: AlphaSymbol[]; -} -⋮---- -export interface AlphaAggTradesParams { - symbol: string; - fromId?: number; - startTime?: number; - endTime?: number; - limit?: number; -} -⋮---- -export interface AlphaAggTrade { - a: number; // aggregate trade ID - p: string; // price - q: string; // quantity - f: number; // first trade ID - l: number; // last trade ID - T: number; // timestamp - m: boolean; // is buyer market maker -} -⋮---- -a: number; // aggregate trade ID -p: string; // price -q: string; // quantity -f: number; // first trade ID -l: number; // last trade ID -T: number; // timestamp -m: boolean; // is buyer market maker -⋮---- -export interface AlphaKlinesParams { - symbol: string; - interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M - limit?: number; - startTime?: number; - endTime?: number; -} -⋮---- -interval: string; // 1s, 15s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M -⋮---- -export type AlphaKline = [ - string, // Open time - string, // Open price - string, // High price - string, // Low price - string, // Close price - string, // Volume - string, // Close time - string, // Quote asset volume - string, // Number of trades - string, // Taker buy base asset volume - string, // Taker buy quote asset volume - string, // Ignore (always "0") -]; -⋮---- -string, // Open time -string, // Open price -string, // High price -string, // Low price -string, // Close price -string, // Volume -string, // Close time -string, // Quote asset volume -string, // Number of trades -string, // Taker buy base asset volume -string, // Taker buy quote asset volume -string, // Ignore (always "0") -⋮---- -export interface AlphaTickerParams { - symbol: string; -} -⋮---- -export type AlphaFullDepthLimit = 5 | 10 | 20 | 50 | 100 | 500 | 1000; -⋮---- -export interface AlphaFullDepthParams { - symbol: string; - limit?: AlphaFullDepthLimit; -} -⋮---- -export interface AlphaFullDepthData { - lastUpdateId: number; - symbol: string; - bids: [string, string][]; - asks: [string, string][]; - E: number; - T: number; -} -⋮---- -export interface AlphaFullDepthResponse { - code: string; - message: string | null; - messageDetail: string | null; - success: boolean; - data: AlphaFullDepthData; -} -⋮---- -export interface AlphaTicker { - symbol: string; - priceChange: string; - priceChangePercent: string; - weightedAvgPrice: string; - lastPrice: string; - lastQty: string; - openPrice: string; - highPrice: string; - lowPrice: string; - volume: string; - quoteVolume: string; - openTime: number; - closeTime: number; - firstId: number; - lastId: number; - count: number; -} -⋮---- +const wsClient = new WebsocketClient({ + api_key: key, + api_secret: secret, + // Optional: when enabled, the SDK will try to format incoming data into more readable objects. + // Beautified data is emitted via the "formattedMessage" event + beautify: true, + // Disable ping/pong ws heartbeat mechanism (not recommended) + // disableHeartbeat: true, + // Connect to testnet environment + // testnet: true, +}); + +// receive raw events +wsClient.on('message', (data) => { + console.log('raw message received ', JSON.stringify(data, null, 2)); +}); + +// notification when a connection is opened +wsClient.on('open', (data) => { + console.log('connection opened open:', data.wsKey, data.wsUrl); +}); + +// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. +wsClient.on('formattedMessage', (data) => { + console.log('formattedMessage: ', data); +}); + +// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) +wsClient.on('response', (data) => { + console.log('log response: ', JSON.stringify(data, null, 2)); +}); + +// receive notification when a ws connection is reconnecting automatically +wsClient.on('reconnecting', (data) => { + console.log('ws automatically reconnecting.... ', data?.wsKey); +}); + +// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) +wsClient.on('reconnected', (data) => { + console.log('ws has reconnected ', data?.wsKey); +}); + +// Recommended: receive error events (e.g. first reconnection failed) +wsClient.on('exception', (data) => { + console.log('ws saw error ', data?.wsKey); +}); + /** - * Soft Staking interfaces + * Subscribe to public topics either one at a time or many in an array */ -export interface GetSoftStakingProductListParams { - asset?: string; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SoftStakingProduct { - asset: string; - minAmount: string; - maxCap: string; - apr: string; - stakedAmount: string; - totalProfit: string; -} -⋮---- -export interface GetSoftStakingProductListResponse { - status: boolean; - totalRewardsUsdt: string; - rows: SoftStakingProduct[]; - total: number; -} -⋮---- -export interface SetSoftStakingParams { - softStaking: boolean; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SetSoftStakingResponse { - success: boolean; -} -⋮---- -export interface GetSoftStakingRewardsHistoryParams { - asset?: string; - startTime?: number; - endTime?: number; - current?: number; - size?: number; - recvWindow?: number; - timestamp: number; -} -⋮---- -export interface SoftStakingRewardsRecord { - asset: string; - rewards: string; - rewardAsset: string; - avgAmount: string; - time: number; -} -⋮---- -export interface GetSoftStakingRewardsHistoryResponse { - rows: SoftStakingRewardsRecord[]; - total: number; + +// E.g. one at a time, routed to the coinm futures websockets: +wsClient.subscribe('btcusd@indexPrice', 'coinm'); +wsClient.subscribe('btcusd@miniTicker', 'coinm'); + +// Or send many topics at once to a stream, e.g. the usdm futures stream: +wsClient.subscribe( + ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'], + 'usdm', +); + +// spot & margin topics should go to "main" +// (similar how the MainClient is for REST APIs in that product group) +wsClient.subscribe( + [ + // All Market Rolling Window Statistics Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams + '!ticker_1h@arr', + // Individual Symbol Book Ticker Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams + 'btcusdt@bookTicker', + // Average Price + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price + 'btcusdt@avgPrice', + // Partial Book Depth Streams + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams + 'btcusdt@depth10@100ms', + // Diff. Depth Stream + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream + 'btcusdt@depth', + ], + // Look at the `WS_KEY_URL_MAP` for a list of values here: + // https://github.com/sieblyio/binance/blob/master/src/util/websockets/websocket-util.ts + // "main" connects to wss://stream.binance.com:9443/stream + // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams + 'main', +); + +/** + * For the user data stream, these convenient subscribe methods open a dedicated + * connection with the listen key workflow: + */ + +wsClient.subscribeSpotUserDataStream(); +wsClient.subscribeMarginUserDataStream(); +wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); +wsClient.subscribeUsdFuturesUserDataStream(); +wsClient.subscribePortfolioMarginUserDataStream(); +``` + +See [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples. + +#### Preserving large integers in WebSocket messages + +By default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`. +If you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`. + +Example using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder: + +```ts +import { WebsocketClient } from 'binance'; + +/** + * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details: + * https://github.com/sieblyio/binance/issues/208 + * + * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below: + */ +const ws = new WebsocketClient({ + // Default behaviour, if you don't include this: + // customParseJSONFn: (rawEvent) => { + // return JSON.parse(rawEvent); + // }, + + // Or, pre-process the raw event using RegEx, before using the same workflow: + customParseJSONFn: (rawEvent) => { + return JSON.parse( + rawEvent.replace(/"orderId":\s*(\d+)/g, '"orderId":"$1"'), + ); + }, + + // Or, use a 3rd party library such as json-bigint: + // customParseJSONFn: (rawEvent) => { + // return JSONbig({ storeAsString: true }).parse(rawEvent); + // }, +}); + +ws.on('message', (msg) => { + console.log(msg); +}); + +// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values. +// Use a custom replacer or JSONbig.stringify if you need to log/serialize: +// const replacer = (_k: string, v: unknown) => typeof v === 'bigint' ? v.toString() : v; +// console.log(JSON.stringify(msg, replacer)); +``` + +### WebSocket API + +Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. + +#### Authentication + +HMAC, RSA and Ed25519 keys are supported for the WebSocket API. However, only Ed25519 keys support WebSocket API login. When using HMAC or RSA keys, each WebSocket API command will need to be individually signed. + +This is no issue for most use cases, but if you are latency sensitive, you should consider using Ed25519 keys. This will allow the WebSocket API client to authenticate once after the connection opens, and all commands can then be sent without additional request signatures. + +#### Event Driven API + +The WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method. + +Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design. + +#### Async Await API + +The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to `sendWSAPIRequest(...)`, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient). + +It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection. + +Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. + +```typescript +import { WebsocketAPIClient } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketAPIClient } = require('binance'); + +/** + * Note: the WebSocket API is fastest with Ed25519 keys. HMAC & RSA will + * require each command to be individually signed. + * + * Check the rest-private-ed25519.md in this folder for more guidance + * on preparing this Ed25519 API key. + */ + +const publicKey = `-----BEGIN PUBLIC KEY----- +MCexampleQTxwLU9o= +-----END PUBLIC KEY----- +`; + +const privateKey = `-----BEGIN PRIVATE KEY----- +MC4CAQAexamplewqj5CzUuTy1 +-----END PRIVATE KEY----- +`; + +// API Key returned by binance, generated using the publicKey (above) via Binance's website +const apiKey = 'TQpJexamplerobdG'; + +// Make an instance of the WS API Client +const wsClient = new WebsocketAPIClient({ + api_key: apiKey, + api_secret: privateKey, + beautify: true, + + // Enforce testnet ws connections, regardless of supplied wsKey + // testnet: true, +}); + +// 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/sieblyio/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow +// wsClient.setTimeOffsetMs(-5000); + +// Optional, see above. Can be used to prepare a connection before sending commands +// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); + +// Make WebSocket API calls, very similar to a REST API: + +wsClient + .getFuturesAccountBalanceV2({ + timestamp: Date.now(), + recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); + +wsClient + .submitNewFuturesOrder('usdm', { + side: 'SELL', + symbol: 'BTCUSDT', + type: 'MARKET', + quantity: 0.001, + timestamp: Date.now(), + // recvWindow: 5000, + }) + .then((result) => { + console.log('getFuturesAccountBalanceV2 result: ', result); + }) + .catch((err) => { + console.error('getFuturesAccountBalanceV2 error: ', err); + }); +``` + +--- + +## Market Maker Endpoints + +Binance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program. + +These endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283 + +### Using Market Maker Endpoints + +To use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients): + +#### Market Maker REST API Clients + +```javascript +import { USDMClient, CoinMClient } from 'binance'; + +// USD-M Futures with MM endpoints +const usdmClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); + +// COIN-M Futures with MM endpoints +const coinmClient = new CoinMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` + +#### Market Maker WebSocket Clients + +```javascript +import { WebsocketClient, WebsocketAPIClient } from 'binance'; + +// WebSocket consumer with MM endpoints +const wsClient = new WebsocketClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); + +// WebSocket API client with MM endpoints +const wsApiClient = new WebsocketAPIClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMSubdomain: true, // Enable market maker endpoints +}); +``` + +**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments. + +### Best practice + +Since market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints. + +```javascript +import { USDMClient } from 'binance'; + +// MM client for USD-M futures +const futuresMMClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMEndpoints: true, // Use MM endpoints for futures +}); + +// Regular client for USD-M futures +const futuresRegularClient = new USDMClient({ + api_key: API_KEY, + api_secret: API_SECRET, + useMMEndpoints: false, // Use regular endpoints for futures +}); +``` + +## Customise Logging + +Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. + +```javascript +import { WebsocketClient, DefaultLogger } from 'binance'; + +// or, if you prefer `require()`: +// const { WebsocketClient, DefaultLogger } = require('binance'); + +// Enable all logging on the trace level (disabled by default) +DefaultLogger.trace = (...params) => { + console.trace('trace: ', params); +}; + +// Pass the updated logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + DefaultLogger +); + +// Or, create a completely custom logger with the 3 available functions +const customLogger = { + trace: (...params: LogParams): void => { + console.trace(new Date(), params); + }, + info: (...params: LogParams): void => { + console.info(new Date(), params); + }, + error: (...params: LogParams): void => { + console.error(new Date(), params); + }, } +// Pass the custom logger as the 2nd parameter +const ws = new WebsocketClient( + { + api_key: key, + api_secret: secret, + beautify: true, + }, + customLogger +); +``` + +## Browser/Frontend 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 crypto-browserify stream-browserify + ``` +2. Add this to your `tsconfig.json` + ```json + { + "compilerOptions": { + "paths": { + "crypto": [ + "./node_modules/crypto-browserify" + ], + "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. + +## 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` +- Sign up with my referral links: + - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004 + - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ + - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SIEBLY + - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103 + + + + +### Contributions & Pull Requests + +Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. + +## Used By + +[![Repository Users Preview Image](https://dependents.info/sieblyio/binance/image)](https://github.com/sieblyio/binance/network/dependents) + + + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) + + + ================ File: package.json ================ { "name": "binance", - "version": "3.6.9", + "version": "3.6.10", "description": "Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.", "main": "lib/index.js", "types": "lib/index.d.ts", @@ -29225,7 +29298,7 @@ File: package.json ], "dependencies": { "@types/ws": "8.18.1", - "axios": "1.18.1", + "axios": "1.20.0", "isomorphic-ws": "4.0.1", "nanoid": "3.3.18", "ws": "8.21.1" @@ -29233,7 +29306,7 @@ File: package.json "devDependencies": { "@types/jest": "^30.0.0", "@types/node": "^22.10.2", - "@typescript-eslint/eslint-plugin": "^8.18.0", + "@typescript-eslint/eslint-plugin": "8.70.0", "eslint": "^10.0.1", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.2.1", @@ -29251,12 +29324,12 @@ File: package.json "webpack-cli": "^5.1.4" }, "overrides": { - "brace-expansion@<2": "1.1.18", - "brace-expansion@>=2 <3": "2.1.4", - "brace-expansion@>=5 <6": "5.0.9", - "fast-uri@>=3 <4": "3.1.5", - "js-yaml@>=3 <4": "3.15.1", - "js-yaml@>=4 <5": "4.3.1" + "brace-expansion@<2": "1.1.21", + "brace-expansion@>=2 <3": "2.1.7", + "brace-expansion@>=5 <6": "5.0.12", + "fast-uri@>=3 <4": "3.1.8", + "js-yaml@>=3 <4": "3.15.2", + "js-yaml@>=4 <5": "4.3.2" }, "keywords": [ "binance",