### Introduction and Getting Started Source: https://github.com/suenot/binance-docs-markdown/blob/main/README.md Provides foundational information about the Binance API, including general concepts, API types, base URLs, authentication methods, error codes, and rate limits. ```APIDOC ## Getting Started ### Description This section covers the basics of using the Binance API, including an introduction to concepts, available API types, base URLs for different services, authentication procedures (API Key, Secret Key, HMAC SHA256 signature generation), common error codes, and guidelines for handling rate limits. ### Documentation Links - **Introduction**: `./docs/introduction.md` - **Endpoints Overview**: `./docs/endpoints.md` - **Authentication**: `./docs/authentication.md` - **Error Codes**: `./docs/error-codes.md` - **Rate Limits**: `./docs/rate-limits.md` ``` -------------------------------- ### Query COIN-M Futures Order - Example Request Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/trade/query-order.md This example demonstrates how to construct a GET request to query a specific order on the COIN-M Futures market. It includes the necessary query parameters such as symbol, orderId (or origClientOrderId), timestamp, and signature. Ensure the timestamp is within 1000ms of the server time and the signature is correctly generated using HMAC SHA256. ```HTTP GET https://dapi.binance.com/dapi/v1/order?symbol=BTCUSD_PERP&orderId=4022044081×tamp=1669202762447&signature=xxx ``` -------------------------------- ### Get Spot Open Orders (JSON Example) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/trade/open-orders.md Illustrates the expected JSON response format for retrieving current open orders on the Spot market. This format typically includes details for each order such as symbol, order ID, price, quantity, and status. ```json [ { "symbol": "BTCUSDT", "orderId": 29, "orderListId": -1, "clientOrderId": "myOpenOrder1", "price": "58000.00", "origQty": "0.1", "executedQty": "0.0", "cummulativeQuoteQty": "0.0", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "stopPrice": "0.0", "icebergQty": "0.0", "time": 1619888400000, "updateTime": 1619888400000, "isWorking": true, "origQuoteOrderQty": "0.0" } ] ``` -------------------------------- ### Spot Account Information JSON Response Example Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/account/account-info.md An example JSON response payload for retrieving Spot account information. This includes details like commission rates, trading permissions, account type, and a list of asset balances with their free and locked amounts. The 'balances' array contains all assets, regardless of whether their balance is zero. ```json { "makerCommission": 15, "takerCommission": 15, "buyerCommission": 0, "sellerCommission": 0, "canTrade": true, "canWithdraw": true, "canDeposit": true, "updateTime": 123456789, "accountType": "SPOT", "balances": [ { "asset": "BTC", "free": "4723846.89208129", "locked": "0.00000000" }, { "asset": "LTC", "free": "4763368.68006011", "locked": "0.00000000" } ], "permissions": [ "SPOT" ] } ``` -------------------------------- ### Get Spot Kline Data - JSON Example Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/market/kline-data.md This example demonstrates the structure of the JSON response when retrieving candlestick data from the Binance Spot API. Each inner array represents a single kline with 12 data points. ```json [ [ 1499040000000, // Open time "0.01634790", // Open "0.80000000", // High "0.01575800", // Low "0.01577100", // Close "148976.11427815", // Volume 1499644799999, // 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" // Ignore ] // ... more klines ] ``` -------------------------------- ### Get USDⓈ-M Futures Account Balance - Example JSON Response Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/usds-m-futures/account/balance.md This JSON structure represents a conceptual example of the response payload for retrieving USDⓈ-M Futures account balances. It includes fields like asset name, wallet balance, unrealized PnL, and available balance for each asset. Note that the exact fields, types, and precision should be verified in the official Binance documentation. ```json [ { "accountAlias": "SgsR", "asset": "USDT", "balance": "10000.00000000", "crossWalletBalance": "10000.00000000", "crossUnPnl": "0.00000000", "availableBalance": "9990.00000000", "maxWithdrawAmount": "9990.00000000", "marginAvailable": true, "updateTime": 1620000000000 }, { "accountAlias": "SgsR", "asset": "BUSD", "balance": "500.00000000", "crossWalletBalance": "500.00000000", "crossUnPnl": "0.00000000", "availableBalance": "500.00000000", "maxWithdrawAmount": "500.00000000", "marginAvailable": true, "updateTime": 1620000000000 } ] ``` -------------------------------- ### SDK Examples Source: https://github.com/suenot/binance-docs-markdown/blob/main/README.md Links to various Software Development Kits (SDKs) in different programming languages to facilitate integration with the Binance API. ```APIDOC ## SDK Examples ### Description This section provides links to Software Development Kits (SDKs) for various programming languages to help developers integrate with the Binance API more easily. These links may point to official or community-maintained resources. ### SDKs - **Python SDK**: `./docs/sdk/python.md` - **Java SDK**: `./docs/sdk/java.md` - **Node.js SDK**: `./docs/sdk/nodejs.md` - **Go SDK**: `./docs/sdk/go.md` - **C# SDK**: `./docs/sdk/csharp.md` ``` -------------------------------- ### Create and Connect to Binance Spot User Data Stream Source: https://context7.com/suenot/binance-docs-markdown/llms.txt This snippet demonstrates how to obtain a listen key and establish a WebSocket connection to receive real-time account updates for the Binance Spot market. It includes handling order fills and balance changes. The connection requires a valid API key and is kept alive with periodic keep-alive requests. ```bash # Step 1: Create listen key curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://api.binance.com/api/v3/userDataStream' # Response { "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" } # Step 2: Connect to WebSocket with listen key # wss://stream.binance.com:9443/ws/pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1 ``` ```javascript // JavaScript example const listenKey = 'pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1'; const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${listenKey}`); ws.on('message', function(data) { const message = JSON.parse(data); // Handle order updates if (message.e === 'executionReport') { console.log('Order Update:', { symbol: message.s, orderId: message.i, status: message.X, side: message.S, price: message.p, quantity: message.q, executedQty: message.z }); } // Handle account balance updates if (message.e === 'outboundAccountPosition') { console.log('Balance Update:', message.B); } }); // Step 3: Keep-alive (every 30 minutes) setInterval(() => { fetch('https://api.binance.com/api/v3/userDataStream', { method: 'PUT', headers: { 'X-MBX-APIKEY': 'YourApiKey' }, body: `listenKey=${listenKey}` }); }, 30 * 60 * 1000); ``` -------------------------------- ### Get COIN-M Futures Open Orders (JavaScript Example) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/trade/open-orders.md This JavaScript snippet demonstrates how to fetch current open orders for COIN-M Futures. It requires an API key and signature, and can optionally filter by symbol or pair. The response is an array of order objects. ```javascript const axios = require('axios'); const crypto = require('crypto'); const apiKey = 'YOUR_API_KEY'; const apiSecret = 'YOUR_API_SECRET'; const baseUrl = 'https://dapi.binance.com'; async function getOpenOrders(symbol) { const timestamp = Date.now(); const queryString = symbol ? `symbol=${symbol}×tamp=${timestamp}` : `timestamp=${timestamp}`; const signature = crypto.createHmac('sha256', apiSecret).update(queryString).digest('hex'); const url = `${baseUrl}/dapi/v1/openOrders?${queryString}&signature=${signature}`; try { const response = await axios.get(url, { headers: { 'X-MBX-APIKEY': apiKey } }); return response.data; } catch (error) { console.error('Error fetching open orders:', error.response ? error.response.data : error.message); throw error; } } // Example usage: getOpenOrders('BTCUSD_PERP') .then(orders => { console.log('Open Orders:', JSON.stringify(orders, null, 2)); }) .catch(err => { console.error('Failed to get open orders.'); }); // To get all open orders for all symbols: // getOpenOrders() // .then(orders => { // console.log('All Open Orders:', JSON.stringify(orders, null, 2)); // }) // .catch(err => { // console.error('Failed to get all open orders.'); // }); ``` -------------------------------- ### Interact with Binance Spot API and WebSockets using Python SDK Source: https://context7.com/suenot/binance-docs-markdown/llms.txt This Python example utilizes the Binance Connector for Python to interact with both REST API endpoints and WebSocket streams for the Spot market. It covers initializing the client, fetching account information, placing and canceling limit orders, and subscribing to real-time trade data via WebSockets. The example includes a message handler for processing incoming trade data. ```python from binance.spot import Spot from binance.websocket.spot.websocket_client import SpotWebsocketClient # Initialize Spot client client = Spot( api_key='YourApiKey', api_secret='YourSecretKey' ) # Get account information account = client.account() print(f"USDT Balance: {[b for b in account['balances'] if b['asset'] == 'USDT'][0]}") # Place a limit order order = client.new_order( symbol='BTCUSDT', side='BUY', type='LIMIT', timeInForce='GTC', quantity=0.001, price=50000 ) print(f"Order ID: {order['orderId']}") # Cancel order cancel_response = client.cancel_order( symbol='BTCUSDT', orderId=order['orderId'] ) print(f"Canceled: {cancel_response['status']}") # WebSocket example def message_handler(message): print(f"Price: {message['p']}, Qty: {message['q']}") ws_client = SpotWebsocketClient() ws_client.start() # Subscribe to trades ws_client.agg_trade( symbol='btcusdt', id=1, callback=message_handler ) # Keep connection alive import time time.sleep(60) ws_client.stop() ``` -------------------------------- ### Get COIN-M Futures Balance (JavaScript Example) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/account/balance.md This snippet demonstrates how to retrieve the COIN-M Futures account balance using JavaScript. It requires a valid API Key and Signature for authentication. The response is a JSON array containing balance details for each asset. ```javascript const accountAlias = "SgsR"; // unique account code const asset = "BTC"; // asset name const balance = "1.00000000"; // wallet balance const withdrawAvailable = "1.00000000"; // available withdraw amount const crossWalletBalance = "1.00000000"; // crossed wallet balance const crossUnPnl = "0.00000000"; // unrealized profit of crossed positions const availableBalance = "1.00000000"; // available balance const updateTime = 1617936249376; // last update time // Example of a second asset const asset2 = "ETH"; const balance2 = "10.00000000"; const withdrawAvailable2 = "10.00000000"; const crossWalletBalance2 = "10.00000000"; const crossUnPnl2 = "0.00000000"; const availableBalance2 = "10.00000000"; const updateTime2 = 1617936249376; const response = [ { "accountAlias": accountAlias, "asset": asset, "balance": balance, "withdrawAvailable": withdrawAvailable, "crossWalletBalance": crossWalletBalance, "crossUnPnl": crossUnPnl, "availableBalance": availableBalance, "updateTime": updateTime }, { "accountAlias": "SgsR", "asset": asset2, "balance": balance2, "withdrawAvailable": withdrawAvailable2, "crossWalletBalance": crossWalletBalance2, "crossUnPnl": crossUnPnl2, "availableBalance": availableBalance2, "updateTime": updateTime2 } ]; console.log(response); ``` -------------------------------- ### Python SDK Example Source: https://context7.com/suenot/binance-docs-markdown/llms.txt Demonstrates using the official Binance Connector for Python to interact with REST API and WebSocket streams. ```APIDOC ## Python SDK Example ### Description Use the official Binance Connector for Python to interact with REST API and WebSocket streams. ### Initialization ```python from binance.spot import Spot from binance.websocket.spot.websocket_client import SpotWebsocketClient # Initialize Spot client client = Spot( api_key='YourApiKey', api_secret='YourSecretKey' ) ``` ### REST API Examples #### Get Account Information ```python # Get account information account = client.account() print(f"USDT Balance: {[b for b in account['balances'] if b['asset'] == 'USDT'][0]}") ``` #### Place a Limit Order ```python # Place a limit order order = client.new_order( symbol='BTCUSDT', side='BUY', type='LIMIT', timeInForce='GTC', quantity=0.001, price=50000 ) print(f"Order ID: {order['orderId']}") ``` #### Cancel Order ```python # Cancel order cancel_response = client.cancel_order( symbol='BTCUSDT', orderId=order['orderId'] ) print(f"Canceled: {cancel_response['status']}") ``` ### WebSocket Example #### Subscribe to Trades ```python def message_handler(message): print(f"Price: {message['p']}, Qty: {message['q']}") ws_client = SpotWebsocketClient() ws_client.start() # Subscribe to trades ws_client.agg_trade( symbol='btcusdt', id=1, callback=message_handler ) # Keep connection alive import time time.sleep(60) ws_client.stop() ``` ``` -------------------------------- ### Best Practices for API Rate Limits Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/rate-limits.md Provides a list of recommended practices for interacting with the Binance API to effectively manage and avoid rate limits. ```APIDOC ## Best Practices * **Monitor Headers:** Actively check the rate limit headers in responses. * **Implement Backoff:** Use exponential backoff when receiving `429` errors. * **Optimize Calls:** Combine requests where possible (e.g., fetching multiple tickers) and avoid polling excessively. * **Use WebSockets:** For real-time data, prefer WebSocket streams over polling REST endpoints. * **Distribute Load:** If necessary, use multiple IP addresses or API keys (within Binance's terms of service). ``` -------------------------------- ### Get 24hr Ticker Statistics (JSON Example) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/options/market/ticker-data.md Example JSON response structure for the 24hr Ticker Statistics API endpoint. This data includes price change, last traded price, volume, bid/ask prices, and other relevant metrics for an options symbol. ```json [ { "symbol": "BTC-200730-9000-C", "priceChange": "-16.2038", "priceChangePercent": "-0.0162", "lastPrice": "1000", "lastQty": "1000", "open": "1016.2038", "high": "1016.2038", "low": "0", "volume": "5", "amount": "1", "bidPrice":"999.34", "askPrice":"1000.23", "openTime": 1592317127349, "closeTime": 1592380593516, "firstTradeId": 1, "tradeCount": 5, "strikePrice": "9000", "exercisePrice": "3000.3356" } ] ``` -------------------------------- ### Node.js: Interact with Binance Spot API Source: https://context7.com/suenot/binance-docs-markdown/llms.txt This snippet demonstrates how to use the Binance Connector for Node.js to fetch account information, place a limit order, and cancel it. It requires API keys for authentication and handles responses and errors. The WebSocket example shows how to subscribe to real-time trade streams. ```javascript const { Spot } = require('@binance/connector'); // Initialize client const client = new Spot( 'YourApiKey', 'YourSecretKey' ); // Get account information client.account() .then(response => { const usdtBalance = response.data.balances.find(b => b.asset === 'USDT'); console.log('USDT Balance:', usdtBalance); }) .catch(error => console.error(error)); // Place limit order client.newOrder('BTCUSDT', 'BUY', 'LIMIT', { quantity: 0.001, price: 50000, timeInForce: 'GTC' }) .then(response => { console.log('Order placed:', response.data.orderId); // Cancel the order return client.cancelOrder('BTCUSDT', { orderId: response.data.orderId }); }) .then(cancelResponse => { console.log('Order canceled:', cancelResponse.data.status); }) .catch(error => console.error(error)); // WebSocket example const { WebsocketStream } = require('@binance/connector'); const callbacks = { open: () => console.log('WebSocket connected'), close: () => console.log('WebSocket closed'), message: data => { const message = JSON.parse(data); console.log(`Price: ${message.p}, Qty: ${message.q}`); } }; const wsClient = new WebsocketStream({ callbacks }); wsClient.aggTrade('btcusdt'); // Unsubscribe after 60 seconds setTimeout(() => { wsClient.disconnect(); }, 60000); ``` -------------------------------- ### Retrieve All Orders (Conceptual JSON) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/usds-m-futures/trade/all-orders.md This is a conceptual representation of the JSON response payload for the 'Get All Orders' endpoint. It shows an array of order objects, each containing details such as order ID, symbol, status, price, quantities, and timestamps. Note that this is not executable code but a data structure example. ```json [ { "orderId": 2831942115, "symbol": "BTCUSDT", "status": "FILLED", "clientOrderId": "myOrder1", "price": "9000", "avgPrice": "9001.50", "origQty": "0.001", "executedQty": "0.001", "cumQuote": "9.0015", "timeInForce": "GTC", "type": "LIMIT", "reduceOnly": false, "closePosition": false, "side": "BUY", "positionSide": "BOTH", "stopPrice": "0", "workingType": "CONTRACT_PRICE", "priceProtect": false, "origType": "LIMIT", "time": 1578966608735, "updateTime": 1578966609500 }, { "orderId": 2831942116, "symbol": "BTCUSDT", "status": "CANCELED", "clientOrderId": "myOpenOrder2", "price": "9100", "avgPrice": "0.00000", "origQty": "0.002", "executedQty": "0", "cumQuote": "0", "timeInForce": "GTC", "type": "LIMIT", "reduceOnly": false, "closePosition": false, "side": "SELL", "positionSide": "BOTH", "stopPrice": "0", "workingType": "CONTRACT_PRICE", "priceProtect": false, "origType": "LIMIT", "time": 1578966610000, "updateTime": 1578966615000 } // ... other orders matching criteria ] ``` -------------------------------- ### WebSocket Streams Source: https://github.com/suenot/binance-docs-markdown/blob/main/README.md Documentation for establishing WebSocket connections and subscribing to real-time market data and account updates for various Binance products. ```APIDOC ## WebSocket Streams ### Description This section details how to connect to Binance's WebSocket servers to receive real-time data streams. It covers connection establishment and specific streams for Spot, USDⓈ-M Futures, COIN-M Futures, and Options trading. ### Streams - **Connection**: `./docs/websocket/connection.md` - **Spot Streams**: `./docs/websocket/spot.md` - **USDⓈ-M Futures Streams**: `./docs/websocket/usds-m-futures.md` - **COIN-M Futures Streams**: `./docs/websocket/coin-m-futures.md` - **Options Streams**: `./docs/websocket/options.md` ``` -------------------------------- ### Get COIN-M Futures Position Information (JavaScript Example) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/account/position-info.md This JavaScript snippet demonstrates how to retrieve COIN-M Futures position information from the Binance API. It shows a sample JSON response structure, including details for multiple symbols and their respective position metrics. ```javascript [ { "symbol": "BTCUSD_PERP", "positionAmt": "10", // Position amount "entryPrice": "40000.0", // Average entry price "markPrice": "41000.0", // Current mark price "unRealizedProfit": "1000.0", // Unrealized PnL "liquidationPrice": "35000.0", // Liquidation price "leverage": "10", // Current initial leverage "maxNotionalValue": "1000000", // Maximum notional value allowed for this symbol "marginType": "isolated", // isolated or cross "isolatedMargin": "1000.0", // Isolated margin "isAutoAddMargin": "false", "positionSide": "BOTH", // BOTH, LONG, SHORT "updateTime": 1622540000000 // Last update time }, { "symbol": "ETHUSD_PERP", "positionAmt": "-5", "entryPrice": "2500.0", "markPrice": "2400.0", "unRealizedProfit": "500.0", "liquidationPrice": "3000.0", "leverage": "5", "maxNotionalValue": "500000", "marginType": "cross", "isolatedMargin": "0.0", "isAutoAddMargin": "false", "positionSide": "SHORT", "updateTime": 1622540100000 } ] ``` -------------------------------- ### Spot Trading API Source: https://github.com/suenot/binance-docs-markdown/blob/main/README.md Documentation for interacting with the Binance Spot Trading API, including endpoints for market data, trading operations, account management, and margin trading. ```APIDOC ## Spot Trading (api.binance.com) ### Description This section covers the REST API endpoints for Binance's Spot Trading service. It includes functionalities for retrieving market data, placing and managing orders, querying account information, and performing margin trading operations. ### Market Data Endpoints - **Exchange Info**: `./docs/spot/market/exchange-info.md` - **Order Book**: `./docs/spot/market/order-book.md` - **Recent Trades**: `./docs/spot/market/recent-trades.md` - **Candlestick (Kline) Data**: `./docs/spot/market/kline-data.md` - **Ticker Data**: `./docs/spot/market/ticker-data.md` ### Trading Endpoints - **Place Order**: `./docs/spot/trade/place-order.md` - **Cancel Order**: `./docs/spot/trade/cancel-order.md` - **Query Order**: `./docs/spot/trade/query-order.md` - **Current Open Orders**: `./docs/spot/trade/open-orders.md` - **All Orders**: `./docs/spot/trade/all-orders.md` ### Account Endpoints - **Account Information**: `./docs/spot/account/account-info.md` - **Account Trade List**: `./docs/spot/account/trade-list.md` ### Margin Trading Endpoints - **Borrow**: `./docs/spot/margin/borrow.md` - **Repay**: `./docs/spot/margin/repay.md` - **Margin Account Details**: `./docs/spot/margin/account-details.md` ``` -------------------------------- ### Example JSON Response for Recent Trades Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/usds-m-futures/market/recent-trades.md This JSON snippet illustrates the structure of the response payload when retrieving recent trades. Each object represents a trade with details like ID, price, quantity, and timestamp. This is a conceptual example and may vary slightly in actual API responses. ```json [ { "id": 28457, "price": "9700.01", "qty": "1.2", "quoteQty": "11640.012", "time": 1589436922972, "isBuyerMaker": true } // ... more trades ] ``` -------------------------------- ### Binance API Overview Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/introduction.md This section provides a high-level overview of the Binance API, its supported trading features, account types, and general conventions. ```APIDOC ## Binance API Overview ### Description Provides an overview of the Binance API, including supported trading features (Spot, Margin, Futures, Options), account types, API key management, and general data conventions. ### Key Features * **Spot Trading:** Buy/sell cryptocurrencies at current market prices. * **Margin Trading:** Trade with borrowed funds. * **USDⓈ-Margined Futures:** Trade futures settled in stablecoins. * **COIN-Margined Futures:** Trade futures settled in the base cryptocurrency. * **Options Trading:** Trade European-style vanilla options. * **Portfolio Margin:** Unified risk management across asset classes. * **Wallet Management:** Access balances, deposit/withdrawal history, and perform transfers. ### Account Types * **Spot (`SPOT`):** Enabled by default. * **Margin (`MARGIN`):** Required for margin trading. * **Futures (`FUTURES`):** Required for USDⓈ-M and COIN-M Futures. * **Options (`OPTION`):** Required for options trading. ### API Key Setup * **Creation:** Generate API Keys via Binance account security settings. * **Security:** Never share API Key/Secret Key. Restrict by IP address. Delete compromised keys. * **Permissions:** `Enable Reading` (default), `Enable Trading`, `Enable Withdrawals` (requires 2FA). ### General Conventions * **Data Format:** JSON. * **Order:** Ascending (oldest first). * **Timestamps:** Milliseconds since UNIX epoch. ``` -------------------------------- ### Example JSON Response for Recent Trades Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/market/recent-trades.md An example of the JSON response when requesting recent trades for a symbol. Each object represents a trade with details like ID, price, quantity, time, and buyer maker status. This format is consistent across API calls for this endpoint. ```json [ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "48.000012", "time": 1499865549590, "isBuyerMaker": true, "isBestMatch": true } // ... more trades ] ``` -------------------------------- ### COIN-M Futures Order Book Depth Example (JSON) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/market/order-book.md An example of the JSON response payload when retrieving the order book depth for a COIN-M Futures symbol. It includes the last update ID, timestamps, and arrays of bid and ask orders, each with price and quantity. ```json { "lastUpdateId": 123456789, "E": 1591702614000, "T": 1591702613950, "bids": [ ["9000.1", "150"], ["9000.0", "200"] ], "asks": [ ["9000.2", "120"], ["9000.3", "80"] ] } ``` -------------------------------- ### Place Spot Trading Order on Binance Source: https://context7.com/suenot/binance-docs-markdown/llms.txt Allows placing buy or sell orders on the Spot market. Supports limit orders with specified price and quantity, and market orders using quote quantity for immediate execution. ```bash # Place a limit buy order for 0.001 BTC at $50,000 curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=BUY&type=LIMIT&quantity=0.001&price=50000&timeInForce=GTC&recvWindow=5000×tamp=1591702613943&signature=21fd819734bf0e5c68740eed892909414d693635c5f7fffab1313925ae13556a' # Response { "symbol": "BTCUSDT", "orderId": 28, "orderListId": -1, "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", "transactTime": 1507725176595, "price": "50000.00", "origQty": "0.001", "executedQty": "0.00", "cummulativeQuoteQty": "0.00", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "fills": [] } # Place a market buy order with quote amount (buy $100 worth of BTC) curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=BUY&type=MARKET"eOrderQty=100×tamp=1591702613943&signature=YourSignatureHere' ``` -------------------------------- ### Get Spot Order Book Depth Example (JSON) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/market/order-book.md This example demonstrates the JSON response structure when requesting the order book depth for a symbol (e.g., BTCUSDT) with a limit of 5. It shows the last update ID and the arrays for bids and asks, where each entry consists of price and quantity. ```json { "lastUpdateId": 1027024, "bids": [ ["4.00000000", "431.00000000"], ["3.99900000", "212.00000000"], ["3.99800000", "50.00000000"], ["3.99700000", "100.00000000"], ["3.99600000", "25.00000000"] ], "asks": [ ["4.00100000", "120.00000000"], ["4.00200000", "55.00000000"], ["4.00300000", "301.00000000"], ["4.00400000", "87.00000000"], ["4.00500000", "99.00000000"] ] } ``` -------------------------------- ### Place Options Trading Order (REST API) Source: https://context7.com/suenot/binance-docs-markdown/llms.txt Creates options positions with European-style vanilla calls and puts. This example shows placing a limit buy order for a call option. It requires API key, signature, and specifies the symbol, side, type, quantity, price, and time in force. ```bash # Place a limit buy order for a call option curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://eapi.binance.com/eapi/v1/order?symbol=BTC-250101-50000-C&side=BUY&type=LIMIT&quantity=0.1&price=1000&timeInForce=GTC&recvWindow=5000×tamp=1591702613943&signature=YourSignatureHere' ``` -------------------------------- ### Place COIN-M Futures Order (REST API) Source: https://context7.com/suenot/binance-docs-markdown/llms.txt Creates leveraged futures positions settled in cryptocurrency for COIN-M futures. This example demonstrates placing a limit buy order for BTCUSD_PERP. It requires API key, signature, and specifies order parameters like symbol, side, type, quantity, and price. ```bash # Place a limit buy order on BTCUSD_PERP curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://dapi.binance.com/dapi/v1/order?symbol=BTCUSD_PERP&side=BUY&positionSide=BOTH&type=LIMIT&quantity=1&price=50000&timeInForce=GTC&recvWindow=5000×tamp=1591702613943&signature=YourSignatureHere' ``` -------------------------------- ### User Data Stream (Spot) Source: https://context7.com/suenot/binance-docs-markdown/llms.txt Subscribe to real-time account updates including order fills and balance changes via WebSocket. ```APIDOC ## WebSocket - User Data Stream (Spot) ### Description Subscribe to real-time account updates including order fills and balance changes. ### Step 1: Create Listen Key **Method:** POST **Endpoint:** `/api/v3/userDataStream` **Headers:** - `X-MBX-APIKEY`: Your API Key **Request Example:** ```bash curl -H "X-MBX-APIKEY: YourApiKey" -X POST \ 'https://api.binance.com/api/v3/userDataStream' ``` **Response Example (200 OK):** ```json { "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" } ``` ### Step 2: Connect to WebSocket **Endpoint:** `wss://stream.binance.com:9443/ws/` **Description:** Connect to the WebSocket stream using the obtained listen key. **JavaScript Example:** ```javascript const listenKey = 'pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1'; const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${listenKey}`); ws.onmessage = function(event) { const message = JSON.parse(event.data); // Handle order updates if (message.e === 'executionReport') { console.log('Order Update:', { symbol: message.s, orderId: message.i, status: message.X, side: message.S, price: message.p, quantity: message.q, executedQty: message.z }); } // Handle account balance updates if (message.e === 'outboundAccountPosition') { console.log('Balance Update:', message.B); } }; ``` ### Step 3: Keep-Alive **Method:** PUT **Endpoint:** `/api/v3/userDataStream` **Headers:** - `X-MBX-APIKEY`: Your API Key **Body:** - `listenKey` (string) - Required - The listen key obtained in Step 1. **Description:** Ping the server every 30 minutes to keep the listen key alive. **JavaScript Example:** ```javascript setInterval(() => { fetch('https://api.binance.com/api/v3/userDataStream', { method: 'PUT', headers: { 'X-MBX-APIKEY': 'YourApiKey' }, body: `listenKey=${listenKey}` }); }, 30 * 60 * 1000); ``` ``` -------------------------------- ### Get Exchange Information (COIN-M Futures) - JSON Example Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/coin-m-futures/market/exchange-info.md This snippet shows the conceptual JSON response structure for the COIN-M Futures exchange information endpoint. It includes details about rate limits, symbol configurations, and various filters that govern trading rules. Understanding this structure is vital for integrating with the API and ensuring valid order placement. ```json { "timezone": "UTC", "serverTime": 1591702613943, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 1200 } ], "exchangeFilters": [], "symbols": [ { "symbol": "BTCUSD_PERP", "pair": "BTCUSD", "contractType": "PERPETUAL", "deliveryDate": 0, "onboardDate": 1591702613943, "status": "TRADING", "maintMarginPercent": "2.5000", "requiredMarginPercent": "5.0000", "baseAsset": "BTC", "quoteAsset": "USD", "marginAsset": "BTC", "pricePrecision": 1, "quantityPrecision": 0, "baseAssetPrecision": 8, "quotePrecision": 8, "underlyingType": "COIN", "underlyingSubType": [], "settlePlan": 0, "triggerProtect": "0.0500", "liquidationFee": "0.010000", "marketTakeBound": "0.05", "orderTypes": [ "LIMIT", "MARKET", "STOP", "STOP_MARKET", "TAKE_PROFIT", "TAKE_PROFIT_MARKET", "TRAILING_STOP_MARKET" ], "timeInForce": [ "GTC", "IOC", "FOK", "GTX" ], "filters": [ { "filterType": "PRICE_FILTER", "maxPrice": "100000", "minPrice": "0.1", "tickSize": "0.1" }, { "filterType": "LOT_SIZE", "maxQty": "1000", "minQty": "1", "stepSize": "1" }, { "filterType": "MARKET_LOT_SIZE", "maxQty": "1000", "minQty": "1", "stepSize": "1" }, { "filterType": "MAX_NUM_ORDERS", "limit": 200 }, { "filterType": "MAX_NUM_ALGO_ORDERS", "limit": 100 }, { "filterType": "MIN_NOTIONAL", "notional": "1.0" }, { "filterType": "PERCENT_PRICE", "multiplierUp": "1.05", "multiplierDown": "0.95", "multiplierDecimal": 4 } ] } ] } ``` -------------------------------- ### Sample Spot Order Response (JSON) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/trade/place-order.md This JSON object represents a successful order placement confirmation for a LIMIT order on the Spot market. It includes details such as the symbol, order ID, price, quantity, status, and any executed trades. This is a conceptual example; consult official documentation for precise structures. ```json { "symbol": "BTCUSDT", "orderId": 28, "orderListId": -1, // OCO order ID, -1 otherwise "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", "transactTime": 1507725176595, "price": "0.00001000", "origQty": "10.00000000", "executedQty": "0.00000000", "cummulativeQuoteQty": "0.00000000", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "fills": [] // Array of trade fills, empty for non-executed orders } ``` -------------------------------- ### Spot Account Trade List API Response Example (JSON) Source: https://github.com/suenot/binance-docs-markdown/blob/main/docs/spot/account/trade-list.md This JSON object represents a sample response from the Binance Spot API's 'Get Account Trade List' endpoint. It details individual trades, including symbol, IDs, price, quantity, commission, and timestamps. This structure is conceptual and exact fields may vary. ```json [ { "symbol": "BTCUSDT", "id": 28457, "orderId": 100234, "orderListId": -1, "price": "4.00000100", "qty": "12.00000000", "quoteQty": "48.000012", "commission": "0.00001200", "commissionAsset": "BTC", "time": 1499865549590, "isBuyer": true, "isMaker": false, "isBestMatch": true } // ... more trades ] ```