### Binance Trading Bot Implementation in JavaScript Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt A JavaScript implementation of a Binance trading bot. It includes handlers for order updates, account updates, and methods to start and stop the bot. It utilizes the Binance API for trading operations and data streams. This example assumes the existence of a BinanceTradingBot class with methods like limitSell, getAccount, startMarketStream, and startUserDataStream. ```javascript class BinanceTradingBot { constructor(apiKey, apiSecret) { this.apiKey = apiKey; this.apiSecret = apiSecret; this.marketWs = null; this.userWs = null; } // Placeholder for sell order logic limitSell(symbol, quantity, price) { console.log(`Executing limit sell for ${symbol}: ${quantity} at ${price}`); // Actual API call would go here } // Placeholder for getting account info async getAccount() { console.log('Getting account info...'); // Actual API call would go here return { accountType: 'SPOT', canTrade: true }; } // Placeholder for starting market stream startMarketStream(symbol) { console.log(`Starting market stream for ${symbol}`); // WebSocket connection logic would go here this.marketWs = { close: () => console.log('Market stream closed') }; } // Placeholder for starting user data stream async startUserDataStream() { console.log('Starting user data stream...'); // WebSocket connection logic would go here this.userWs = { close: () => console.log('User data stream closed') }; } // Order update handler onOrderUpdate(event) { if (event.X === 'FILLED') { console.log(`Order ${event.i} filled: ${event.z} ${event.s} @ ${event.L}`); } else if (event.X === 'CANCELED') { console.log(`Order ${event.i} canceled`); } } // Account update handler onAccountUpdate(event) { event.B.forEach(balance => { if (parseFloat(balance.f) > 0 || parseFloat(balance.l) > 0) { console.log(`${balance.a}: ${balance.f} (${balance.l} locked)`); } }); } // Start the bot async start(symbol) { console.log('Starting trading bot...'); // Get initial account info const account = await this.getAccount(); console.log(`Account Type: ${account.accountType}`); console.log(`Can Trade: ${account.canTrade}`); // Start streams this.startMarketStream(symbol); await this.startUserDataStream(); console.log(`Bot running for ${symbol}`); } // Stop the bot stop() { if (this.marketWs) this.marketWs.close(); if (this.userWs) this.userWs.close(); console.log('Bot stopped'); } } // Usage const bot = new BinanceTradingBot('YOUR_API_KEY', 'YOUR_API_SECRET'); bot.start('BTCUSDT').catch(console.error); // Graceful shutdown process.on('SIGINT', () => { console.log('\nShutting down...'); bot.stop(); process.exit(); }); ``` -------------------------------- ### Get Current Open Orders - Binance API Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt This example demonstrates how to retrieve a list of all current open orders on Binance using a GET request to the `/api/v3/openOrders` endpoint. You can query open orders for a specific symbol or all open orders across all symbols. Both methods require a timestamp and a signature, authenticated with the API key. ```bash # Get open orders for specific symbol curl -X GET 'https://api.binance.com/api/v3/openOrders?symbol=BTCUSDT×tamp=1499827319559&signature=...' \ -H "X-MBX-APIKEY: YOUR_API_KEY" ``` ```bash # Get all open orders (all symbols) curl -X GET 'https://api.binance.com/api/v3/openOrders?timestamp=1499827319559&signature=...' \ -H "X-MBX-APIKEY: YOUR_API_KEY" ``` -------------------------------- ### GET /api/v3/account Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Retrieves current account information, including balances for all assets, trading permissions, and commission rates. ```APIDOC ## GET /api/v3/account ### Description Get current account information including balances. ### Method GET ### Endpoint /api/v3/account ### Parameters #### Query Parameters - **timestamp** (integer) - Required - The current timestamp in milliseconds. - **signature** (string) - Required - The signed signature of the payload. - **recvWindow** (integer) - Optional - The number of milliseconds the server waits for the request to be completed. ### Request Example ```bash curl -X GET 'https://api.binance.com/api/v3/account?timestamp=1499827319559&signature=...' \ -H "X-MBX-APIKEY: YOUR_API_KEY" ``` ### Response #### Success Response (200) - **makerCommission** (integer) - Maker commission rate. - **takerCommission** (integer) - Taker commission rate. - **buyerCommission** (integer) - Buyer commission rate. - **sellerCommission** (integer) - Seller commission rate. - **commissionRates** (object) - Commission rates object. - **maker** (string) - Maker commission rate. - **taker** (string) - Taker commission rate. - **buyer** (string) - Buyer commission rate. - **seller** (string) - Seller commission rate. - **canTrade** (boolean) - Whether trading is enabled. - **canWithdraw** (boolean) - Whether withdrawals are enabled. - **canDeposit** (boolean) - Whether deposits are enabled. - **brokered** (boolean) - Whether the account is brokered. - **requireSelfTradePrevention** (boolean) - Whether self-trade prevention is required. - **preventSor** (boolean) - Whether SOR is enabled. - **updateTime** (integer) - The last account update time. - **accountType** (string) - The account type (e.g., SPOT, MARGIN). - **balances** (array) - An array of account balances. - **asset** (string) - The asset symbol (e.g., BTC, USDT). - **free** (string) - The available balance. - **locked** (string) - The locked balance. - **permissions** (array) - Trading permissions for the account. #### Response Example ```json { "makerCommission": 15, "takerCommission": 15, "buyerCommission": 0, "sellerCommission": 0, "commissionRates": { "maker": "0.00150000", "taker": "0.00150000", "buyer": "0.00000000", "seller": "0.00000000" }, "canTrade": true, "canWithdraw": true, "canDeposit": true, "brokered": false, "requireSelfTradePrevention": false, "preventSor": false, "updateTime": 123456789, "accountType": "SPOT", "balances": [ { "asset": "BTC", "free": "4723846.89208129", "locked": "0.00000000" }, { "asset": "USDT", "free": "10000.00000000", "locked": "2500.00000000" } ], "permissions": ["SPOT"] } ``` ``` -------------------------------- ### JavaScript: User Data Stream via WebSocket API Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Establishes a WebSocket connection to the Binance User Data stream endpoint using API credentials. Requires 'ws' and 'crypto' modules. It demonstrates starting a user data stream, handling order updates ('executionReport'), and account position updates ('outboundAccountPosition'). ```javascript const WebSocket = require('ws'); const crypto = require('crypto'); const apiKey = 'YOUR_API_KEY'; const apiSecret = 'YOUR_API_SECRET'; const timestamp = Date.now(); const signature = crypto.createHmac('sha256', apiSecret) .update(`timestamp=${timestamp}`) .digest('hex'); const ws = new WebSocket('wss://ws-api.binance.com:443/ws-api/v3'); ws.on('open', function open() { // Start user data stream const startStreamMsg = { "id": "user-stream-start", "method": "userDataStream.start", "params": { "apiKey": apiKey, "signature": signature, "timestamp": timestamp } }; ws.send(JSON.stringify(startStreamMsg)); }); ws.on('message', function message(data) { const msg = JSON.parse(data); if (msg.id === 'user-stream-start') { console.log('User data stream started:', msg.result); } else if (msg.e === 'executionReport') { console.log('Order update:', msg); } else if (msg.e === 'outboundAccountPosition') { console.log('Account update:', msg); } }); ``` -------------------------------- ### JavaScript: Dynamic Subscription Management via WebSocket Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Manages WebSocket subscriptions dynamically by sending SUBSCRIBE, UNSUBSCRIBE, and LIST_SUBSCRIPTIONS messages. Requires the 'ws' library. The code includes examples for subscribing to multiple streams, unsubscribing, and listing current subscriptions, with confirmation messages. ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://stream.binance.com:9443/ws'); ws.on('open', function open() { // Subscribe to streams const subscribeMsg = { "method": "SUBSCRIBE", "params": [ "btcusdt@aggTrade", "btcusdt@depth" ], "id": 1 }; ws.send(JSON.stringify(subscribeMsg)); }); ws.on('message', function message(data) { const msg = JSON.parse(data); if (msg.result === null && msg.id === 1) { console.log('Successfully subscribed'); } else if (msg.e) { console.log(`Event: ${msg.e} for ${msg.s}`); } }); // Later, unsubscribe setTimeout(() => { const unsubscribeMsg = { "method": "UNSUBSCRIBE", "params": ["btcusdt@depth"], "id": 2 }; ws.send(JSON.stringify(unsubscribeMsg)); }, 10000); // List current subscriptions setTimeout(() => { const listMsg = { "method": "LIST_SUBSCRIPTIONS", "id": 3 }; ws.send(JSON.stringify(listMsg)); }, 12000); ``` -------------------------------- ### Test New Order - Binance API Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt This example shows how to test a new order placement on the Binance API without actually executing the trade. It uses the `/api/v3/order/test` endpoint and requires similar parameters to a live order, including symbol, side, type, quantity, price, timestamp, and a signature. A successful test returns an empty JSON object. ```bash curl -X POST 'https://api.binance.com/api/v3/order/test' \ -H "X-MBX-APIKEY: YOUR_API_KEY" \ -d 'symbol=BTCUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=50000×tamp=1499827319559&signature=...' ``` -------------------------------- ### GET /api/v3/exchangeInfo Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Get current exchange trading rules and symbol information. ```APIDOC ## GET /api/v3/exchangeInfo ### Description Retrieve current exchange trading rules, symbols, and filters. ### Method GET ### Endpoint /api/v3/exchangeInfo ### Parameters #### Path Parameters None #### Query Parameters - **symbols** (string) - Optional. A JSON array of symbols to query, e.g., `["BTCUSDT","ETHUSDT"]`. #### Request Body None ### Request Example ```bash # Get all exchange info curl -X GET 'https://api.binance.com/api/v3/exchangeInfo' # Get specific symbols curl -X GET 'https://api.binance.com/api/v3/exchangeInfo?symbols=["BTCUSDT","ETHUSDT"]' ``` ### Response #### Success Response (200) - **timezone** (string) - The timezone of the exchange. - **serverTime** (integer) - The current server time in milliseconds. - **rateLimits** (array) - Rate limit information. - **symbols** (array) - Information about trading symbols. - **symbol** (string) - Trading pair symbol. - **status** (string) - Current status of the symbol (e.g., TRADING). - **baseAsset** (string) - The base asset of the trading pair. - **quoteAsset** (string) - The quote asset of the trading pair. - **orderTypes** (array of strings) - Allowed order types for the symbol. - **filters** (array) - Trading rules and filters for the symbol. #### Response Example ```json { "timezone": "UTC", "serverTime": 1565246363776, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000 } ], "symbols": [ { "symbol": "BTCUSDT", "status": "TRADING", "baseAsset": "BTC", "quoteAsset": "USDT", "orderTypes": ["LIMIT", "MARKET", "STOP_LOSS_LIMIT"], "filters": [ { "filterType": "PRICE_FILTER", "minPrice": "0.01000000", "maxPrice": "1000000.00000000", "tickSize": "0.01000000" } ] } ] } ``` ``` -------------------------------- ### Test Connectivity and Get Server Time (Bash) Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Tests server connectivity using the 'ping' endpoint and retrieves the current server time. These endpoints do not require authentication. ```bash # Test connectivity (no authentication required) curl -X GET 'https://api.binance.com/api/v3/ping' # Response {} # Get server time curl -X GET 'https://api.binance.com/api/v3/time' # Response { "serverTime": 1499827319559 } ``` -------------------------------- ### GET /api/v3/ping Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Test server connectivity. This endpoint does not require authentication. ```APIDOC ## GET /api/v3/ping ### Description Test server connectivity. ### Method GET ### Endpoint /api/v3/ping ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET 'https://api.binance.com/api/v3/ping' ``` ### Response #### Success Response (200) An empty JSON object `{}` indicates successful connection. #### Response Example ```json {} ``` ``` -------------------------------- ### JavaScript: Get Partial Book Depth Streams via WebSocket Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Connects to a Binance WebSocket stream to receive top bids and asks at defined levels for a given symbol. Requires the 'ws' library. The output provides the length of bids and asks arrays, with detailed bid/ask information within the message. ```javascript const WebSocket = require('ws'); // Top 5 bids and asks, updated every 1000ms const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@depth5@1000ms'); ws.on('message', function message(data) { const depth = JSON.parse(data); console.log(`Bids: ${depth.bids.length}, Asks: ${depth.asks.length}`); /* { "lastUpdateId": 160, // Last update ID "bids": [ ["50000.00", "2.5"], // [Price level, Quantity] ["49999.50", "1.0"] ], "asks": [ ["50000.50", "1.8"], ["50001.00", "3.2"] ] } */ }); ``` -------------------------------- ### Place Market and Limit Orders - Binance API Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt This snippet demonstrates how to place market and limit orders on the Binance exchange using the API. It requires parameters like symbol, side, type, quantity, and for limit orders, price and timeInForce. The requests must include an API key and a signature for authentication. ```bash curl -X POST 'https://api.binance.com/api/v3/order' \ -H "X-MBX-APIKEY: YOUR_API_KEY" \ -d 'symbol=BTCUSDT&side=BUY&type=MARKET&quantity=0.001×tamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71' ``` ```bash curl -X POST 'https://api.binance.com/api/v3/order' \ -H "X-MBX-APIKEY: YOUR_API_KEY" \ -d 'symbol=ETHUSDT&side=SELL&type=LIMIT&timeInForce=GTC&quantity=1.5&price=2500.00×tamp=1499827319559&signature=...' ``` -------------------------------- ### GET /api/v3/trades Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Get recent trades for a specified symbol. ```APIDOC ## GET /api/v3/trades ### Description Get recent trades for a symbol. ### Method GET ### Endpoint /api/v3/trades ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required. The trading symbol (e.g., BTCUSDT). - **limit** (integer) - Optional. Default is 500. Maximum is 1000. #### Request Body None ### Request Example ```bash # Get last 500 trades (default) curl -X GET 'https://api.binance.com/api/v3/trades?symbol=BTCUSDT&limit=500' ``` ### Response #### Success Response (200) - **id** (integer) - Trade ID. - **price** (string) - Price of the trade. - **qty** (string) - Quantity of the trade. - **quoteQty** (string) - Total quote order quantity. - **time** (integer) - Trade time in milliseconds. - **isBuyerMaker** (boolean) - If the buyer is the maker. - **isBestMatch** (boolean) - If the trade was the best price match. #### Response Example ```json [ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "48.000012", "time": 1499865549590, "isBuyerMaker": true, "isBestMatch": true } ] ``` ``` -------------------------------- ### POST /api/v3/order - Place an Order Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Places a new order on the Binance exchange. Supports market and limit orders with various parameters. ```APIDOC ## POST /api/v3/order ### Description Places a new order on the Binance exchange. This endpoint supports various order types like MARKET and LIMIT. ### Method POST ### Endpoint /api/v3/order ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., BTCUSDT). - **side** (string) - Required - Order side (BUY or SELL). - **type** (string) - Required - Order type (MARKET, LIMIT, etc.). - **timeInForce** (string) - Optional - Time in force (e.g., GTC, IOC, FOK). - **quantity** (decimal) - Required - The quantity of the asset to trade. - **price** (decimal) - Optional - The price for limit orders. - **newClientOrderId** (string) - Optional - Used to uniquely identify the order. - **stopPrice** (decimal) - Optional - For stop loss or take profit orders. - **trailingDelta** (integer) - Optional - For trailing stop orders. - **cancelRestrictions** (string) - Optional - For self-trade prevention. - **timestamp** (long) - Required - UTC timestamp in milliseconds. - **signature** (string) - Required - Signature generated using HMAC SHA256. #### Request Body This endpoint typically uses URL-encoded form data in the request body, not a JSON body. ### Request Example ```bash curl -X POST 'https://api.binance.com/api/v3/order' \ -H "X-MBX-APIKEY: YOUR_API_KEY" \ -d 'symbol=BTCUSDT&side=BUY&type=MARKET&quantity=0.001×tamp=1499827319559&signature=c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71' ``` ### Response #### Success Response (200) - **symbol** (string) - Trading pair. - **orderId** (long) - Order ID. - **orderListId** (long) - Order list ID. - **clientOrderId** (string) - Client order ID. - **transactTime** (long) - Transaction time. - **price** (string) - Order price. - **origQty** (string) - Original quantity. - **executedQty** (string) - Executed quantity. - **cummulativeQuoteQty** (string) - Cumulative quote quantity. - **status** (string) - Order status. - **timeInForce** (string) - Time in force. - **type** (string) - Order type. - **side** (string) - Order side. - **workingTime** (long) - Working time. - **selfTradePreventionMode** (string) - Self-trade prevention mode. - **fills** (array) - Array of executed trades for this order. #### Response Example ```json { "symbol": "BTCUSDT", "orderId": 28, "orderListId": -1, "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", "transactTime": 1507725176595, "price": "0.00000000", "origQty": "0.00100000", "executedQty": "0.00100000", "cummulativeQuoteQty": "10.00000000", "status": "FILLED", "timeInForce": "GTC", "type": "MARKET", "side": "BUY", "workingTime": 1507725176595, "selfTradePreventionMode": "NONE", "fills": [ { "price": "4000.00000000", "qty": "0.00100000", "commission": "4.00000000", "commissionAsset": "USDT", "tradeId": 56 } ] } ``` ``` -------------------------------- ### GET /api/v3/ticker/price Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Get the latest price for a specific symbol or all symbols. ```APIDOC ## GET /api/v3/ticker/price ### Description Get latest price for symbol(s). ### Method GET ### Endpoint /api/v3/ticker/price ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Optional. The trading symbol (e.g., BTCUSDT). #### Request Body None ### Request Example ```bash # Single symbol curl -X GET 'https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT' # All symbols curl -X GET 'https://api.binance.com/api/v3/ticker/price' ``` ### Response #### Success Response (200) If a single symbol is requested: - **symbol** (string) - Trading pair symbol. - **price** (string) - The latest price. If no symbol is provided, a JSON array of the above objects for all symbols will be returned. #### Response Example ```json { "symbol": "BTCUSDT", "price": "6000.01" } ``` ``` -------------------------------- ### GET /api/v3/depth Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Get the order book depth for a specific symbol. ```APIDOC ## GET /api/v3/depth ### Description Retrieve the current order book for a symbol. ### Method GET ### Endpoint /api/v3/depth ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required. The trading symbol (e.g., BTCUSDT). - **limit** (integer) - Optional. Default is 100. Valid limits: 5, 10, 20, 50, 100, 500, 1000, 5000. #### Request Body None ### Request Example ```bash # Get order book with 100 levels curl -X GET 'https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=100' ``` ### Response #### Success Response (200) - **lastUpdateId** (integer) - The last update ID for the order book. - **bids** (array) - An array of bid orders, each represented as `[price, quantity]`. - **asks** (array) - An array of ask orders, each represented as `[price, quantity]`. #### Response Example ```json { "lastUpdateId": 1027024, "bids": [ ["4.00000000", "431.00000000"], ["3.99000000", "200.00000000"] ], "asks": [ ["4.00000200", "12.00000000"], ["4.01000000", "150.00000000"] ] } ``` ``` -------------------------------- ### Order Placement and Error Handling Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt This section covers placing orders and provides detailed error handling for common API response codes and filter-specific rejections. ```APIDOC ## Order Placement ### Method POST ### Endpoint /api/v3/order ### Description Places an order on the exchange. It's crucial to handle potential errors during order placement. ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair (e.g., 'BTCUSDT'). - **side** (string) - Required - Order side ('BUY' or 'SELL'). - **type** (string) - Required - Order type ('LIMIT', 'MARKET', etc.). - **timeInForce** (string) - Optional - Time in force (e.g., 'GTC', 'IOC', 'FOK'). - **quantity** (number) - Required - The quantity of the asset to trade. - **price** (number) - Optional - The price for limit orders. - **timestamp** (integer) - Required - The current timestamp in milliseconds. ### Request Example ```javascript const axios = require('axios'); const apiKey = 'YOUR_API_KEY'; async function placeOrder(orderParams) { try { const response = await axios.post( 'https://api.binance.com/api/v3/order', orderParams, { headers: { 'X-MBX-APIKEY': apiKey } } ); return response.data; } catch (error) { // Error handling logic follows throw error; } } // Example usage: placeOrder({ symbol: 'BTCUSDT', side: 'BUY', type: 'MARKET', quantity: 0.001, timestamp: Date.now() }).catch(err => console.error('Order failed:', err.message)); ``` ## Error Handling ### Common Error Codes Handle API errors gracefully by checking the error `code` and `msg` in the response. #### Error Response Body ```json { "code": -1000, "msg": "An unknown error occurred while processing the request." } ``` #### Common Error Code Mapping - **-1000**: Unknown error - **-1003**: Rate limit exceeded - **-1013**: Invalid message - **-1021**: Timestamp out of sync - **-1022**: Invalid signature - **-2010**: Order rejected - **-2011**: Cancel rejected - **-2013**: Order does not exist - **-2015**: Invalid API key format ### Filter Failures Handle order rejection due to exchange filter violations (e.g., PRICE_FILTER, LOT_SIZE). #### Common Filter Errors and Solutions - **PRICE_FILTER**: Price must be within minPrice and maxPrice, and a multiple of tickSize. - **LOT_SIZE**: Quantity must be within minQty and maxQty, and a multiple of stepSize. - **MIN_NOTIONAL**: The total order value (price * quantity) must meet the minimum notional requirement. - **NOTIONAL**: The total order value must be within the specified minNotional and maxNotional. - **PERCENT_PRICE**: Price must be within multiplierUp/Down of the average price. - **MAX_NUM_ORDERS**: Too many open orders for the symbol. Cancel existing orders before placing new ones. ### Request Example with Filter Handling ```javascript // Assuming placeOrder function is defined as above const filterErrorHandling = { 'Filter failure: PRICE_FILTER': (price, symbol) => { console.log(`Adjust price ${price} to match filter for ${symbol}`); }, 'Filter failure: LOT_SIZE': (quantity, symbol) => { console.log(`Adjust quantity ${quantity} to match filter for ${symbol}`); }, 'Filter failure: MIN_NOTIONAL': (value, symbol) => { console.log(`Order value ${value} too small for ${symbol}`); }, 'Filter failure: NOTIONAL': (value, symbol) => { console.log(`Order value ${value} out of range for ${symbol}`); }, 'Filter failure: PERCENT_PRICE': (price, symbol) => { console.log(`Price ${price} too far from average for ${symbol}`); }, 'Filter failure: MAX_NUM_ORDERS': (symbol) => { console.log(`Cancel some orders for ${symbol} before placing new ones`); } }; async function placeOrderWithFilters(symbol, side, quantity, price) { try { return await placeOrder({ symbol, side, type: 'LIMIT', timeInForce: 'GTC', quantity, price }); } catch (error) { const errorMsg = error.response?.data?.msg || ''; for (const [filterError, handler] of Object.entries(filterErrorHandling)) { if (errorMsg.includes(filterError)) { handler(price || quantity, symbol); // Optionally retry with adjusted parameters break; } } throw error; } } ``` ``` -------------------------------- ### Establish Binance User Data Stream (Deprecated REST Method) Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt This JavaScript code demonstrates how to establish a user data stream from the Binance API using a deprecated REST API method to obtain a listen key. It includes steps to create the listen key, connect to the WebSocket stream, and periodically keep the listen key alive to prevent disconnection. Dependencies include 'axios' for HTTP requests and 'ws' for WebSocket communication. ```javascript const axios = require('axios'); const WebSocket = require('ws'); const apiKey = 'YOUR_API_KEY'; // Step 1: Create listen key via REST API async function createListenKey() { const response = await axios.post( 'https://api.binance.com/api/v3/userDataStream', {}, { headers: { 'X-MBX-APIKEY': apiKey } } ); return response.data.listenKey; } // Step 2: Connect to user data stream async function connectUserDataStream() { const listenKey = await createListenKey(); console.log('Listen key:', listenKey); const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${listenKey}`); ws.on('message', function message(data) { const event = JSON.parse(data); console.log('Event:', event.e); }); // Step 3: Keep listen key alive (every 30 minutes) setInterval(async () => { await axios.put( `https://api.binance.com/api/v3/userDataStream?listenKey=${listenKey}`, {}, { headers: { 'X-MBX-APIKEY': apiKey } } ); console.log('Listen key keepalive sent'); }, 30 * 60 * 1000); return { ws, listenKey }; } connectUserDataStream().catch(console.error); ``` -------------------------------- ### GET /api/v3/ticker/24hr Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Get 24-hour rolling window price change statistics for a symbol. ```APIDOC ## GET /api/v3/ticker/24hr ### Description Get 24-hour rolling window price change statistics. ### Method GET ### Endpoint /api/v3/ticker/24hr ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Optional. The trading symbol (e.g., BTCUSDT). - **symbols** (string) - Optional. A JSON array of symbols to query, e.g., `["BTCUSDT","ETHUSDT"]`. #### Request Body None ### Request Example ```bash # Single symbol curl -X GET 'https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT' # Multiple symbols curl -X GET 'https://api.binance.com/api/v3/ticker/24hr?symbols=["BTCUSDT","ETHUSDT"]' ``` ### Response #### Success Response (200) If a single symbol is requested: - **symbol** (string) - Trading pair symbol. - **priceChange** (string) - Price change. - **priceChangePercent** (string) - Price change percentage. - **weightedAvgPrice** (string) - Weighted average price. - **prevClosePrice** (string) - Previous closing price. - **lastPrice** (string) - Last price. - **lastQty** (string) - Last quantity. - **bidPrice** (string) - Bid price. - **askPrice** (string) - Ask price. - **openPrice** (string) - Open price. - **highPrice** (string) - High price. - **lowPrice** (string) - Low price. - **volume** (string) - Volume. - **quoteVolume** (string) - Quote volume. - **openTime** (integer) - Open time in milliseconds. - **closeTime** (integer) - Close time in milliseconds. - **firstId** (integer) - First trade ID. - **lastId** (integer) - Last trade ID. - **count** (integer) - Number of trades. If multiple symbols are requested, a JSON array of the above objects will be returned. #### Response Example ```json { "symbol": "BTCUSDT", "priceChange": "-94.99999800", "priceChangePercent": "-95.960", "weightedAvgPrice": "0.29628482", "prevClosePrice": "0.10002000", "lastPrice": "4.00000200", "lastQty": "200.00000000", "bidPrice": "4.00000000", "askPrice": "4.00000200", "openPrice": "99.00000000", "highPrice": "100.00000000", "lowPrice": "0.10000000", "volume": "8913.30000000", "quoteVolume": "15.30000000", "openTime": 1499783499040, "closeTime": 1499869899040, "firstId": 28385, "lastId": 28460, "count": 76 } ``` ``` -------------------------------- ### GET /api/v3/klines Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Retrieve candlestick chart data for a symbol. ```APIDOC ## GET /api/v3/klines ### Description Retrieve candlestick chart data. ### Method GET ### Endpoint /api/v3/klines ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required. The trading symbol (e.g., BTCUSDT). - **interval** (string) - Required. The interval of the klines (e.g., `1m`, `5m`, `15m`, `30m`, `1h`, `6h`, `1d`, `1w`, `1M`). - **startTime** (integer) - Optional. Time in milliseconds. - **endTime** (integer) - Optional. Time in milliseconds. - **limit** (integer) - Optional. Default is 500. Maximum is 1000. #### Request Body None ### Request Example ```bash # Get klines (1 hour interval, limit 500) curl -X GET 'https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=500' # With time range curl -X GET 'https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&startTime=1499040000000&endTime=1499644800000' ``` ### Response #### Success Response (200) A list of candlestick data arrays. Each array contains: - **0**: Kline open time (milliseconds) - **1**: Open price - **2**: High price - **3**: Low price - **4**: Close price - **5**: Volume - **6**: Kline close time (milliseconds) - **7**: Quote asset volume - **8**: Number of trades - **9**: Taker buy base asset volume - **10**: Taker buy quote asset volume - **11**: Unused field #### Response Example ```json [ [ 1499040000000, // Kline open time "0.01634790", // Open price "0.80000000", // High price "0.01575800", // Low price "0.01577100", // Close price "148976.11427815", // Volume 1499644799999, // Kline close time "2434.19055334", // Quote asset volume 308, // Number of trades "1756.87402397", // Taker buy base asset volume "28.46694368", // Taker buy quote asset volume "0" // Unused field ] ] ``` ``` -------------------------------- ### GET /api/v3/time Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Retrieve the current server time from Binance. ```APIDOC ## GET /api/v3/time ### Description Retrieve the current server time. ### Method GET ### Endpoint /api/v3/time ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET 'https://api.binance.com/api/v3/time' ``` ### Response #### Success Response (200) - **serverTime** (integer) - Current server time in milliseconds. #### Response Example ```json { "serverTime": 1499827319559 } ``` ``` -------------------------------- ### POST /api/v3/order (RSA) Source: https://context7.com/binance-exchange/binance-official-api-docs/llms.txt Place an order using RSA private key for signature generation. This method supports various order types like LIMIT. ```APIDOC ## POST /api/v3/order (RSA) ### Description Place an order using RSA private key for signature generation. This method supports various order types like LIMIT. ### Method POST ### Endpoint `/api/v3/order` ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., BTCUSDT). - **side** (string) - Required - BUY or SELL. - **type** (string) - Required - Order type (e.g., LIMIT). - **timeInForce** (string) - Required for LIMIT orders - Time in force (e.g., GTC). - **quantity** (number) - Required - The amount of the asset to trade. - **price** (number) - Required for LIMIT orders - The price of the order. - **timestamp** (integer) - Required - Current timestamp in milliseconds. - **signature** (string) - Required - Base64 encoded RSA SHA256 signature. #### Request Body This endpoint does not have a request body. All parameters are sent as query parameters. ### Request Example ```python import time import requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding import base64 with open('private_key.pem', 'rb') as f: private_key = serialization.load_pem_private_key(f.read(), password=None) api_key = 'YOUR_API_KEY' symbol = 'BTCUSDT' side = 'BUY' order_type = 'LIMIT' timeInForce = 'GTC' quantity = 0.1 price = 50000 timestamp = int(time.time() * 1000) query_string = f'symbol={symbol}&side={side}&type={order_type}&timeInForce={timeInForce}&quantity={quantity}&price={price}×tamp={timestamp}' signature = private_key.sign( query_string.encode('utf-8'), padding.PKCS1v15(), hashes.SHA256() ) signature_b64 = base64.b64encode(signature).decode('utf-8') url = f'https://api.binance.com/api/v3/order?{query_string}&signature={signature_b64}' headers = {'X-MBX-APIKEY': api_key} response = requests.post(url, headers=headers) print(response.json()) ``` ### Response #### Success Response (200) - **symbol** (string) - The trading pair. - **orderId** (integer) - The ID of the placed order. - **price** (string) - The price of the order. - **qty** (string) - The quantity of the order. - **commission** (string) - The commission paid. - **commissionAsset** (string) - The asset in which commission is paid. - **time** (integer) - The time the order was placed. - **isBuyer** (boolean) - True if the buyer was the maker, false otherwise. - **isMaker** (boolean) - True if the order was a maker order, false otherwise. - **isBestMatch** (boolean) - True if this was the best match. #### Response Example ```json { "symbol": "BTCUSDT", "id": 100234, "orderId": 100234, "orderListId": -1, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "48.000012", "commission": "10.10000000", "commissionAsset": "USDT", "time": 1499865549590, "isBuyer": true, "isMaker": false, "isBestMatch": true } ``` ```