UNPKG

@binance/connector-typescript

Version:

This is a lightweight library that works as a connector to the Binance public API.

1,199 lines (1,175 loc) 286 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { AccountSnapshotType: () => AccountSnapshotType, AddLiquidityPreviewType: () => AddLiquidityPreviewType, AutoCompoundPlan: () => AutoCompoundPlan, BusdStableCoinsConversion: () => BusdStableCoinsConversion, CancelReplaceMode: () => CancelReplaceMode, CancelRestrictions: () => CancelRestrictions, CancelResult: () => CancelResult, ConvertExpiredType: () => ConvertExpiredType, ConvertOrderStatus: () => ConvertOrderStatus, ConvertSide: () => ConvertSide, CrossMarginAccountTransferType: () => CrossMarginAccountTransferType, CrossMarginAccountType: () => CrossMarginAccountType, CrossMarginTrans: () => CrossMarginTrans, DepositHistory: () => DepositHistory, Direction: () => Direction, DualInvestmentPurchaseStatus: () => DualInvestmentPurchaseStatus, DustAccountType: () => DustAccountType, Featured: () => Featured, FixedAndActivityProductType: () => FixedAndActivityProductType, FlexibleProductStatus: () => FlexibleProductStatus, FlexibleProductType: () => FlexibleProductType, FromAccountType: () => FromAccountType, FuturesTransferType: () => FuturesTransferType, FuturesType: () => FuturesType, GetCrossMargingTransferHistoryType: () => GetCrossMargingTransferHistoryType, HisrecStatus: () => HisrecStatus, HistoryStatus: () => HistoryStatus, IncomeType: () => IncomeType, InterestBNBBurn: () => InterestBNBBurn, Interval: () => Interval, IsFreeze: () => IsFreeze, IsIsolatedMargin: () => IsIsolatedMargin, LendingType: () => LendingType, LiquidityAddType: () => LiquidityAddType, LiquidityRemoveType: () => LiquidityRemoveType, LogLevel: () => LogLevel, MarginArchive: () => MarginArchive, MarginBorrowRepayType: () => MarginBorrowRepayType, MarginInterestHistory: () => MarginInterestHistory, MarginLevelStatus: () => MarginLevelStatus, MarginStatus: () => MarginStatus, MarginSubAccountTransferType: () => MarginSubAccountTransferType, MarginTransferType: () => MarginTransferType, MargintransferType: () => MargintransferType, NeedBtcValuation: () => NeedBtcValuation, NewOrderRespType: () => NewOrderRespType, NewOrderResult: () => NewOrderResult, OcoNewOrderRespType: () => OcoNewOrderRespType, Operation: () => Operation, OptionType: () => OptionType, OptionalFixedAndActivityProductStatus: () => OptionalFixedAndActivityProductStatus, OptionalFlexibleProductStatus: () => OptionalFlexibleProductStatus, OptionalSide: () => OptionalSide, OptionalTransFrom: () => OptionalTransFrom, OptionalTransTo: () => OptionalTransTo, OrderListAboveBelowType: () => OrderListAboveBelowType, OrderListOrderStatus: () => OrderListOrderStatus, OrderListStatusType: () => OrderListStatusType, OrderListWorkingType: () => OrderListWorkingType, OrderStatus: () => OrderStatus, OrderType: () => OrderType, OtoPendingType: () => OtoPendingType, Permissions: () => Permissions, PortfolioAccountStatus: () => PortfolioAccountStatus, PortfolioAccountType: () => PortfolioAccountType, PortfolioMarginFrom: () => PortfolioMarginFrom, PositionSide: () => PositionSide, PositionStatus: () => PositionStatus, QuerySubAccountList: () => QuerySubAccountList, RedeemDestAccount: () => RedeemDestAccount, RedeemOption: () => RedeemOption, RemoveLiquidityPreviewType: () => RemoveLiquidityPreviewType, RestConvertTypes: () => types_exports, RestDualInvestmentTypes: () => types_exports2, RestMarginTypes: () => types_exports3, RestMarketTypes: () => types_exports4, RestPortfolioMarginTypes: () => types_exports5, RestSimpleEarnTypes: () => types_exports6, RestStreamTypes: () => types_exports7, RestSubAccountTypes: () => types_exports8, RestTradeTypes: () => types_exports9, RestWalletTypes: () => types_exports10, SelfTradePreventionMode: () => SelfTradePreventionMode, Side: () => Side, SideEffectType: () => SideEffectType, SimpleEarnDestAccount: () => SimpleEarnDestAccount, SimpleEarnFlexibleRewards: () => SimpleEarnFlexibleRewards, SimpleEarnLockedRedemption: () => SimpleEarnLockedRedemption, SimpleEarnSourceAccount: () => SimpleEarnSourceAccount, SimpleEarnStatus: () => SimpleEarnStatus, SimpleEarnType: () => SimpleEarnType, SortBy: () => SortBy, Spot: () => Spot, SpotBNBBurn: () => SpotBNBBurn, StopLimitTimeInForce: () => StopLimitTimeInForce, SubAccountStatus: () => SubAccountStatus, SubAccountTransferLog: () => SubAccountTransferLog, SubUserHistoryType: () => SubUserHistoryType, SubscribeSourceAccount: () => SubscribeSourceAccount, SwapStatus: () => SwapStatus, SymbolStatus: () => SymbolStatus, TimeInForce: () => TimeInForce, ToAccountType: () => ToAccountType, TradeType: () => TradeType, TransFrom: () => TransFrom, TransTo: () => TransTo, TransactionType: () => TransactionType, TransferSide: () => TransferSide, UnivStatus: () => UnivStatus, UnivTransferType: () => UnivTransferType, Urgency: () => Urgency, ValidTime: () => ValidTime, WalletType: () => WalletType, WebsocketAPI: () => WebsocketAPI, WebsocketStream: () => WebsocketStream, WithdrawHistory: () => WithdrawHistory, WorkingFloor: () => WorkingFloor, WsAccountTypes: () => types_exports11, WsMarketTypes: () => types_exports12, WsTradeTypes: () => types_exports13, WsUserDataTypes: () => methods_exports, WssTypes: () => methods_exports2 }); module.exports = __toCommonJS(src_exports); // src/modules/restful/convert/types.ts var types_exports = {}; // src/modules/restful/dualInvestment/types.ts var types_exports2 = {}; // src/modules/restful/margin/types.ts var types_exports3 = {}; // src/modules/restful/market/types.ts var types_exports4 = {}; // src/modules/restful/portfolioMargin/types.ts var types_exports5 = {}; // src/modules/restful/simpleEarn/types.ts var types_exports6 = {}; // src/modules/restful/stream/types.ts var types_exports7 = {}; // src/modules/restful/subAccount/types.ts var types_exports8 = {}; // src/modules/restful/trade/types.ts var types_exports9 = {}; // src/modules/restful/wallet/types.ts var types_exports10 = {}; // src/modules/websocket/websocketAPI/account/types.ts var types_exports11 = {}; // src/modules/websocket/websocketAPI/market/types.ts var types_exports12 = {}; // src/modules/websocket/websocketAPI/trade/types.ts var types_exports13 = {}; // src/modules/websocket/websocketAPI/userData/methods.ts var methods_exports = {}; // src/modules/websocket/websocketStream/methods.ts var methods_exports2 = {}; // src/helpers/utils.ts var import_axios = __toESM(require("axios")); // package.json var package_default = { name: "@binance/connector-typescript", version: "0.3.16", description: "This is a lightweight library that works as a connector to the Binance public API.", main: "./dist/index.js", module: "./dist/index.mjs", types: "./dist/index.d.ts", scripts: { test: "npx jest --runInBand", build: "tsup", dev: "ts-node ./examples/restful/market.ts", lint: "eslint --config .eslintrc.json --ext ts . --fix" }, keywords: [ "Binance", "API" ], author: "Binance", license: "MIT", files: [ "dist" ], devDependencies: { "@types/jest": "^29.5.4", "@types/node": "22.9.0", "@types/ws": "^8.5.5", "@typescript-eslint/eslint-plugin": "7.17.0", "@typescript-eslint/parser": "7.17.0", dotenv: "^16.3.1", eslint: "8.57.0", jest: "^29.6.4", "ts-jest": "^29.1.1", "ts-node": "^10.9.1", tsup: "^7.2.0", typescript: "^5.7.2" }, dependencies: { axios: "^1.7.4", ws: "^8.17.1" } }; // src/helpers/constants.ts var appName = package_default.name; var appVersion = package_default.version; // src/helpers/utils.ts var crypto = __toESM(require("crypto")); async function httpRequest(config) { try { const { baseURL, apiKey, method, url, timeout, proxy, httpsAgent } = config; const options = { baseURL, timeout, proxy, httpsAgent, method, url, headers: { "Content-Type": "application/json", "X-MBX-APIKEY": apiKey, "User-Agent": `${appName}/${appVersion}` } }; const { data } = await import_axios.default.request(options); return data; } catch (error) { if (import_axios.default.isAxiosError(error) && error.response) { throw error.response.data.msg; } else { throw new Error("Http request error"); } } } function removeEmptyValue(obj) { if (!(obj instanceof Object)) return {}; return Object.fromEntries( Object.entries(obj).filter(([, value]) => value !== null && value !== void 0 && value !== "") ); } function buildQueryString(params) { if (!params) return ""; return Object.entries(params).map(stringifyKeyValuePair).join("&"); } function stringifyKeyValuePair([key, value]) { const valueString = Array.isArray(value) ? `["${value.join('","')}"]` : value; return `${key}=${encodeURIComponent(valueString)}`; } function validateRequiredParameters(paramObject) { if (!paramObject || isEmptyValue(paramObject)) { throw new Error("Missing Parameters"); } const emptyParams = []; Object.keys(paramObject).forEach((param) => { if (isEmptyValue(paramObject[param])) { emptyParams.push(param); } }); if (emptyParams.length) { throw new Error("Missing Parameters"); } } function isEmptyValue(input) { return !input && input !== false && input !== 0 || typeof input === "string" && /^\s+$/.test(input) || input instanceof Object && !Object.keys(input).length || Array.isArray(input) && !input.length; } function randomString() { return crypto.randomBytes(16).toString("hex"); } function sortObject(obj) { return Object.keys(obj).sort().reduce((res, key) => { res[key] = obj[key]; return res; }, {}); } // src/setters/mixinBase.ts var crypto2 = __toESM(require("crypto")); // src/modules/restful/convert/convert.ts function mixinConvert(base) { return class extends base { /** * List All Convert Pairs (USER_DATA) {@link https://developers.binance.com/docs/convert/market-data/List-all-convert-pairs} * * @param {object} [options] * @param {string} [options.fromAsset] - User spends coin * @param {string} [options.toAsset] - User receives coin * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async listAllConvertPairs(options) { const url = this.prepareSignedPath( "/sapi/v1/convert/exchangeInfo", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query order quantity precision per asset (USER_DATA) {@link https://developers.binance.com/docs/convert/market-data/Query-order-quantity-precision-per-asset} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getOrderQuantityPrecisionPerAsset(options) { const url = this.prepareSignedPath( "/sapi/v1/convert/assetInfo", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Send quote request (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Send-quote-request} * * @param {string} fromAsset * @param {string} toAsset * @param {object} [options] * @param {number} [options.fromAmount] - When specified, it is the amount you will be debited after the conversion * @param {number} [options.toAmount] - When specified, it is the amount you will be debited after the conversion * @param {WalletType} [options.walletType] - SPOT or FUNDING. Default is SPOT * @param {ValidTime} [options.validTime] - 10s, 30s, 1m, 2m, default 10s * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async sendQuoteRequest(fromAsset, toAsset, options) { validateRequiredParameters({ fromAsset, toAsset }); const url = this.prepareSignedPath( "/sapi/v1/convert/getQuote", Object.assign( options ? options : {}, { fromAsset, toAsset } ) ); return await this.makeRequest("POST", url); } /** * Accept Quote (TRADE) {@link https://developers.binance.com/docs/convert/trade/Accept-Quote} * * @param {string} quoteId * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async acceptQuote(quoteId, options) { validateRequiredParameters({ quoteId }); const url = this.prepareSignedPath( "/sapi/v1/convert/acceptQuote", Object.assign( options ? options : {}, { quoteId } ) ); return await this.makeRequest("POST", url); } /** * Order status (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Order-Status} * * @param {object} [options] * @param {string} [options.orderId] - Either orderId or quoteId is required * @param {string} [options.quoteId] - Either orderId or quoteId is required * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async orderStatus(options) { const url = this.prepareSignedPath( "/sapi/v1/convert/orderStatus", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Place limit order (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Place-Order} * * @param {string} baseAsset - base asset (use the response fromIsBase from GET /sapi/v1/convert/exchangeInfo api to check which one is baseAsset) * @param {string} quoteAsset - quote asset * @param {number} limitPrice - Symbol limit price (from baseAsset to quoteAsset) * @param {ConvertSide} side - BUY or SELL * @param {ConvertExpiredType} expiredType - 1_D, 3_D, 7_D, 30_D (D means day) * @param {object} [options] * @param {number} [options.baseAmount] - Base asset amount. (One of baseAmount or quoteAmount is required) * @param {number} [options.quoteAmount] - Quote asset amount. (One of baseAmount or quoteAmount is required) * @param {WalletType} [options.walletType] - SPOT or FUNDING or SPOT_FUNDING. It is to use which type of assets. Default is SPOT. * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async placeLimitOrder(baseAsset, quoteAsset, limitPrice, side, expiredType, options) { validateRequiredParameters({ baseAsset, quoteAsset, limitPrice, side, expiredType }); const url = this.prepareSignedPath( "/sapi/v1/convert/limit/placeOrder", Object.assign( options ? options : {}, { baseAsset, quoteAsset, limitPrice, side, expiredType } ) ); return await this.makeRequest("POST", url); } /** * Cancel limit order (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Cancel-Order} * * @param {number} orderId - The orderId from placeOrder api * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async cancelLimitOrder(orderId, options) { validateRequiredParameters({ orderId }); const url = this.prepareSignedPath( "/sapi/v1/convert/limit/cancelOrder", Object.assign( options ? options : {}, { orderId } ) ); return await this.makeRequest("POST", url); } /** * Query limit open orders (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Query-Order} * * @param {object} [options] * @param {number} [options.recvWindow] - default 100, max 1000 */ async queryLimitOpenOrders(options) { const url = this.prepareSignedPath( "/sapi/v1/convert/limit/queryOpenOrders", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Get Convert Trade History (USER_DATA) {@link https://developers.binance.com/docs/convert/trade/Get-Convert-Trade-History} * * @param {number} startTime - UTC timestamp in ms * @param {number} endTime - UTC timestamp in ms * @param {object} [options] * @param {number} [options.limit] - default 100, max 1000 * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getConvertTradeHistory(startTime, endTime, options) { validateRequiredParameters({ startTime, endTime }); const url = this.prepareSignedPath( "/sapi/v1/convert/tradeFlow", Object.assign( options ? options : {}, { startTime, endTime } ) ); return await this.makeRequest("GET", url); } }; } // src/modules/restful/dualInvestment/dualInvestment.ts function mixinDualInvestment(base) { return class extends base { /** * Get Dual Investment product list {@link https://developers.binance.com/docs/dual_investment/market-data} * * @param {OptionType} optionType - Input CALL or PUT * @param {string} exercisedCoin - Target exercised asset, e.g.: If you subscribe to a high sell product (call option), you should input: optionType: CALL, exercisedCoin: USDT, investCoin: BNB; If you subscribe to a low buy product (put option), you should input: optionType: PUT, exercisedCoin: BNB, investCoin: USDT; * @param {string} investCoin - Asset used for subscribing, e.g.: If you subscribe to a high sell product (call option), you should input: optionType: CALL, exercisedCoin: USDT, investCoin: BNB; If you subscribe to a low buy product (put option), you should input: optionType: PUT, exercisedCoin: BNB, investCoin: USDT; * @param {object} [options] * @param {number} [options.pageSize] - MIN 1, MAX 100; Default 100 * @param {number} [options.pageIndex] - Page number, default is first page, start form 1 * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getDualInvestmentProductList(optionType, exercisedCoin, investCoin, options) { validateRequiredParameters({ optionType, exercisedCoin, investCoin }); const url = this.prepareSignedPath( "/sapi/v1/dci/product/list", Object.assign( options ? options : {}, { optionType, exercisedCoin: exercisedCoin.toUpperCase(), investCoin: investCoin.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Subscribe Dual Investment products (USER_DATA) {@link https://developers.binance.com/docs/dual_investment/trade} * * @param {string} id - get id from /sapi/v1/dci/product/list * @param {string} orderId - get orderId from /sapi/v1/dci/product/list * @param {number} depositAmount * @param {AutoCompoundPlan} autoCompoundPlan - NONE: switch off the plan, STANDARD: standard plan, ADVANCED: advanced plan; * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async subscribeDualInvestmentProducts(id, orderId, depositAmount, autoCompoundPlan, options) { validateRequiredParameters({ id, orderId, depositAmount, autoCompoundPlan }); const url = this.prepareSignedPath( "/sapi/v1/dci/product/subscribe", Object.assign( options ? options : {}, { id, orderId, depositAmount, autoCompoundPlan } ) ); return await this.makeRequest("POST", url); } /** * Get Dual Investment positions (USER_DATA) {@link https://developers.binance.com/docs/dual_investment/trade/Get-Dual-Investment-positions} * * @param {object} [options] * @param {Status} [options.status] - - PENDING: Products are purchasing, will give results later;, - PURCHASE_SUCCESS: purchase successfully;, - SETTLED: Products are finish settling;, - PURCHASE_FAIL: fail to purchase;, - REFUNDING: refund ongoing;, - REFUND_SUCCESS: refund to spot account successfully;, - SETTLING: Products are settling. , If don't fill this field, will response all the position status. * @param {number} [options.pageSize] - MIN 1, MAX 100; Default 100 * @param {number} [options.pageIndex] - Page number, default is first page, start form 1 * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getDualInvestmentPositions(options) { const url = this.prepareSignedPath( "/sapi/v1/dci/product/positions", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Check Dual Investment accounts (USER_DATA) {@link https://developers.binance.com/docs/dual_investment/trade/Check-Dual-Investment-accounts} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async checkDualInvestmentAccounts(options) { const url = this.prepareSignedPath( "/sapi/v1/dci/product/accounts", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Change Auto-Compound status (USER_DATA) {@link https://developers.binance.com/docs/dual_investment/trade/Change-Auto-Compound-status} * * @param {string} positionId - Get positionId from /sapi/v1/dci/product/positions * @param {AutoCompoundPlan} autoCompoundPlan - NONE: switch off the plan, STANDARD: standard plan, ADVANCED: advanced plan; * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async changeAutoCompoundStatus(positionId, autoCompoundPlan, options) { validateRequiredParameters({ positionId, autoCompoundPlan }); const url = this.prepareSignedPath( "/sapi/v1/dci/product/auto_compound/edit-status", Object.assign( options ? options : {}, { positionId, autoCompoundPlan } ) ); return await this.makeRequest("POST", url); } }; } // src/modules/restful/margin/margin.ts function mixinMargin(base) { return class extends base { /** * Get All Margin Assets (MARKET_DATA) {@link https://developers.binance.com/docs/margin_trading/market-data/Get-All-Margin-Assets} * * @param {object} [options] * @param {string} [options.asset] */ async getAllMarginAssets(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/allAssets", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Get All Cross Margin Pairs (MARKET_DATA) {@link https://developers.binance.com/docs/margin_trading/market-data/Get-All-Cross-Margin-Pairs} * * @param {object} [options] * @param {string} [options.symbol] */ async getAllCrossMarginPairs(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/allPairs", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin PriceIndex (MARKET_DATA) {@link https://developers.binance.com/docs/margin_trading/market-data/Query-Margin-PriceIndex} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT */ async getMarginPriceIndex(symbol) { validateRequiredParameters({ symbol }); const url = this.preparePath( "/sapi/v1/margin/priceIndex", { symbol: symbol.toUpperCase() } ); return await this.makeRequest("GET", url); } /** * Margin Account New Order (TRADE) {@link https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-Order} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {Side} side * @param {OrderType} type - Order type * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.quantity] * @param {number} [options.quoteOrderQty] - Quote quantity * @param {number} [options.price] - Order price * @param {number} [options.stopPrice] - Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. * @param {string} [options.newClientOrderId] - Used to uniquely identify this cancel. Automatically generated by default * @param {number} [options.icebergQty] - Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order. * @param {NewOrderRespType} [options.newOrderRespType] - Set the response JSON. * @param {SideEffectType} [options.sideEffectType] - Default `NO_SIDE_EFFECT` * @param {TimeInForce} [options.timeInForce] - Order time in force * @param {SelfTradePreventionMode} [options.selfTradePreventionMode] - The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE * @param {Boolean} [options.autoRepayAtCancel] - Only when MARGIN_BUY or AUTO_BORROW_REPAY order takes effect, true means that the debt generated by the order needs to be repay after the order is cancelled. The default is true * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async marginAccountNewOrder(symbol, side, type, options) { validateRequiredParameters({ symbol, side, type }); const url = this.prepareSignedPath( "/sapi/v1/margin/order", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase(), side, type } ) ); return await this.makeRequest("POST", url); } /** * Margin Account Cancel Order (TRADE) {@link https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-Order} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.orderId] - Order id * @param {string} [options.origClientOrderId] - Order id from client * @param {string} [options.newClientOrderId] - Used to uniquely identify this cancel. Automatically generated by default * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async marginAccountCancelOrder(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/order", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("DELETE", url); } /** * Margin Account Cancel all Open Orders on a Symbol (TRADE) {@link https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-All-Open-Orders} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async marginAccountCancelAllOpenOrdersOnASymbol(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/openOrders", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("DELETE", url); } /** * Adjust cross margin max leverage (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Adjust-Cross-Margin-Max-Leverage} * * @param {number} maxLeverage - Can only adjust 3 , 5 or 10,Example: maxLeverage=10 for Cross Margin Pro ,maxLeverage = 5 or 3 for Cross Margin Classic */ async adjustCrossMarginMaxLeverage(maxLeverage) { validateRequiredParameters({ maxLeverage }); const url = this.prepareSignedPath( "/sapi/v1/margin/max-leverage", { maxLeverage } ); return await this.makeRequest("POST", url); } /** * Get Cross Margin Transfer History (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/transfer/Get-Cross-Margin-Transfer-History} * * @param {object} [options] * @param {string} [options.asset] * @param {GetCrossMargingTransferHistoryType} [options.type] - Transfer Type * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {number} [options.current] - Current querying page. Start from 1. Default:1 * @param {number} [options.size] - Default:10 Max:100 * @param {string} [options.isolatedSymbol] - Symbol in Isolated Margin * @param {string} [options.archived] - Default: false. Set to true for archived data from 6 months ago * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getCrossMarginTransferHistory(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/transfer", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Get Interest History (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-Interest-History} * * @param {object} [options] * @param {string} [options.asset] * @param {string} [options.isolatedSymbol] - Isolated symbol * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {number} [options.current] - Current querying page. Start from 1. Default:1 * @param {number} [options.size] - Default:10 Max:100 * @param {string} [options.archived] - Default: false. Set to true for archived data from 6 months ago * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getInterestHistory(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/interestHistory", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Get Force Liquidation Record (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Get-Force-Liquidation-Record} * * @param {object} [options] * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {string} [options.isolatedSymbol] - Isolated symbol * @param {number} [options.current] - Current querying page. Start from 1. Default:1 * @param {number} [options.size] - Default:10 Max:100 * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getForceLiquidationRecord(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/forceLiquidationRec", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Cross Margin Account Details (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Query-Cross-Margin-Account-Details} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getCrossMarginAccountDetails(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/account", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Account's Order (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Order} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.orderId] - Order id * @param {string} [options.origClientOrderId] - Order id from client * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountOrder(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/order", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Query Margin Account's Open Orders (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Open-Orders} * * @param {object} [options] * @param {string} [options.symbol] - Trading symbol, e.g. BNBUSDT * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountOpenOrders(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/openOrders", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Account's All Orders (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.orderId] - Order id * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {number} [options.limit] - Default 500; max 1000. * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountAllOrders(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/allOrders", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Margin Account New OCO (TRADE) {@link https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-OCO} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {Side} side * @param {number} quantity * @param {number} price - Order price * @param {number} stopPrice * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {string} [options.listClientOrderId] - A unique Id for the entire orderList * @param {string} [options.limitClientOrderId] - A unique Id for the limit order * @param {number} [options.limitIcebergQty] * @param {string} [options.stopClientOrderId] - A unique Id for the stop loss/stop loss limit leg * @param {number} [options.stopLimitPrice] - If provided, stopLimitTimeInForce is required. * @param {number} [options.stopIcebergQty] * @param {StopLimitTimeInForce} [options.stopLimitTimeInForce] * @param {NewOrderRespType} [options.newOrderRespType] - Set the response JSON. * @param {SideEffectType} [options.sideEffectType] - Default `NO_SIDE_EFFECT` * @param {SelfTradePreventionMode} [options.selfTradePreventionMode] - The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE * @param {Boolean} [options.autoRepayAtCancel] - Only when MARGIN_BUY or AUTO_BORROW_REPAY order takes effect, true means that the debt generated by the order needs to be repay after the order is cancelled. The default is true * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async marginAccountNewOco(symbol, side, quantity, price, stopPrice, options) { validateRequiredParameters({ symbol, side, quantity, price, stopPrice }); const url = this.prepareSignedPath( "/sapi/v1/margin/order/oco", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase(), side, quantity, price, stopPrice } ) ); return await this.makeRequest("POST", url); } /** * Margin Account Cancel OCO (TRADE) {@link https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-OCO} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.orderListId] - Order list id * @param {string} [options.listClientOrderId] - A unique Id for the entire orderList * @param {string} [options.newClientOrderId] - Used to uniquely identify this cancel. Automatically generated by default * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async marginAccountCancelOco(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/orderList", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("DELETE", url); } /** * Query Margin Account's OCO (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-OCO} * * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {string} [options.symbol] - Mandatory for isolated margin, not supported for cross margin * @param {number} [options.orderListId] - Order list id * @param {string} [options.origClientOrderId] - Order id from client * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountOco(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/orderList", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Account's all OCO (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-OCO} * * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {string} [options.symbol] - Mandatory for isolated margin, not supported for cross margin * @param {string} [options.fromId] - If supplied, neither `startTime` or `endTime` can be provided * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {number} [options.limit] - Default Value: 500; Max Value: 1000 * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountAllOco(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/allOrderList", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Account's Open OCO (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Open-OCO} * * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {string} [options.symbol] - Mandatory for isolated margin, not supported for cross margin * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountOpenOco(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/openOrderList", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Account's Trade List (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Trade-List} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {IsIsolatedMargin} [options.isIsolated] - * `TRUE` - For isolated margin, * `FALSE` - Default, not for isolated margin * @param {number} [options.orderId] * @param {number} [options.startTime] - UTC timestamp in ms * @param {number} [options.endTime] - UTC timestamp in ms * @param {number} [options.fromId] - Trade id to fetch from. Default gets most recent trades. * @param {number} [options.limit] - Default 500; max 1000. * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMarginAccountTradeList(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/myTrades", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Query Max Borrow (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Max-Borrow} * * @param {string} asset * @param {object} [options] * @param {string} [options.isolatedSymbol] - Isolated symbol * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMaxBorrow(asset, options) { validateRequiredParameters({ asset }); const url = this.prepareSignedPath( "/sapi/v1/margin/maxBorrowable", Object.assign( options ? options : {}, { asset: asset.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Query Max Transfer-Out Amount (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/transfer/Query-Max-Transfer-Out-Amount} * * @param {string} asset * @param {object} [options] * @param {string} [options.isolatedSymbol] - Isolated symbol * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getMaxTransferoutAmount(asset, options) { validateRequiredParameters({ asset }); const url = this.prepareSignedPath( "/sapi/v1/margin/maxTransferable", Object.assign( options ? options : {}, { asset: asset.toUpperCase() } ) ); return await this.makeRequest("GET", url); } /** * Get Summary of Margin account (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Get-Summary-Of-Margin-Account} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getSummaryOfMarginAccount(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/tradeCoeff", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Isolated Margin Account Info (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Account-Info} * * @param {object} [options] * @param {string} [options.symbols] - Max 5 symbols can be sent; separated by ',' * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getIsolatedMarginAccountInfo(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/isolated/account", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Disable Isolated Margin Account (TRADE) {@link https://developers.binance.com/docs/margin_trading/account/Disable-Isolated-Margin-Account} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async disableIsolatedMarginAccount(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/isolated/account", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("DELETE", url); } /** * Enable Isolated Margin Account (TRADE) {@link https://developers.binance.com/docs/margin_trading/account/Enable-Isolated-Margin-Account} * * @param {string} symbol - Trading symbol, e.g. BNBUSDT * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async enableIsolatedMarginAccount(symbol, options) { validateRequiredParameters({ symbol }); const url = this.prepareSignedPath( "/sapi/v1/margin/isolated/account", Object.assign( options ? options : {}, { symbol: symbol.toUpperCase() } ) ); return await this.makeRequest("POST", url); } /** * Query Enabled Isolated Margin Account Limit (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Query-Enabled-Isolated-Margin-Account-Limit} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getEnabledIsolatedMarginAccountLimit(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/isolated/accountLimit", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Get All Isolated Margin Symbol (MARKET_DATA) {@link https://developers.binance.com/docs/margin_trading/market-data/Get-All-Isolated-Margin-Symbol} * * @param {object} [options] * @param {string} [options.symbol] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getAllIsolatedMarginSymbol(options) { const url = this.prepareSignedPath( "/sapi/v1/margin/isolated/allPairs", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Toggle BNB Burn On Spot Trade And Margin Interest (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Toggle-BNB-Burn-On-Spot-Trade-And-Margin-Interest} * * @param {object} [options] * @param {SpotBNBBurn} [options.spotBNBBurn] - Determines whether to use BNB to pay for trading fees on SPOT * @param {InterestBNBBurn} [options.interestBNBBurn] - Determines whether to use BNB to pay for margin loan interest * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async toggleBnbBurnOnSpotTradeAndMarginInterest(options) { const url = this.prepareSignedPath( "/sapi/v1/bnbBurn", options ? options : {} ); return await this.makeRequest("POST", url); } /** * Get BNB Burn Status (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/account/Get-BNB-Burn-Status} * * @param {object} [options] * @param {number} [options.recvWindow] - The value cannot be greater than 60000 */ async getBnbBurnStatus(options) { const url = this.prepareSignedPath( "/sapi/v1/bnbBurn", options ? options : {} ); return await this.makeRequest("GET", url); } /** * Query Margin Interest Rate History (USER_DATA) {@link https://developers.binance.com/docs/margin_trading/b