Binance API Bot Integration
Binance is the largest cryptocurrency exchange by trading volume. The API is well-documented, stable, and offers extensive capabilities: spot, margin, futures, and options. For most trading bots, Binance is the first choice due to its liquidity and API maturity.
Binance API Types
- Spot API: Basic trading, balances, and history
- Margin API: Margin trading
- Futures API (FAPI): USD-M perpetual futures
- Coin-M Futures (DAPI): COIN-M futures
- WebSocket Streams: Real-time market data
Connection via CCXT
import ccxt.async_support as ccxt
# Spot
spot = ccxt.binance({
'apiKey': API_KEY,
'secret': SECRET,
'options': {'defaultType': 'spot'},
'enableRateLimit': True,
})
# Futures (USDT-M Perpetual)
futures = ccxt.binance({
'apiKey': API_KEY,
'secret': SECRET,
'options': {'defaultType': 'future'},
})
async def get_ticker(symbol: str):
return await spot.fetch_ticker(symbol)
async def place_futures_order(symbol: str, side: str, quantity: float, leverage: int = 10):
# Set leverage
await futures.set_leverage(leverage, symbol)
return await futures.create_order(symbol, 'market', side, quantity)
WebSocket for Real-time Data
import websockets, json, asyncio
async def subscribe_streams():
streams = [
'btcusdt@bookTicker', # best bid/ask
'btcusdt@aggTrade', # aggregated trades
'btcusdt@kline_1m', # 1m candles
]
url = f"wss://stream.binance.com:9443/stream?streams={'/'.join(streams)}"
async with websockets.connect(url) as ws:
async for message in ws:
data = json.loads(message)
stream = data['stream']
payload = data['data']
if '@bookTicker' in stream:
process_book_ticker(payload)
elif '@aggTrade' in stream:
process_trade(payload)
elif '@kline' in stream:
process_kline(payload['k'])
User Data Stream (Private WebSocket)
For real-time order and balance updates without polling:
async def start_user_data_stream():
# 1. Get listen key
listen_key = await get_listen_key() # REST: POST /api/v3/userDataStream
# 2. Subscribe
url = f"wss://stream.binance.com:9443/ws/{listen_key}"
async with websockets.connect(url) as ws:
# 3. Keepalive every 30 minutes
asyncio.create_task(keepalive_listen_key(listen_key))
async for message in ws:
event = json.loads(message)
if event['e'] == 'executionReport':
# Order update
order_id = event['i']
status = event['X'] # NEW, PARTIALLY_FILLED, FILLED, CANCELED
filled_qty = event['z']
last_price = event['L']
process_order_update(order_id, status, filled_qty, last_price)
elif event['e'] == 'outboundAccountPosition':
# Balance update
for asset in event['B']:
process_balance_update(asset['a'], asset['f'], asset['l'])
Rate Limits
Binance has two types of limits:
- Request Weight Limit: 6000 weight/minute. Different endpoints have different weights (GET /ticker/price = 1, GET /depth?limit=5000 = 250)
- Order Rate Limit: 10 orders/sec, 100,000 orders/24 hours
# Check rate limit headers in each response
async def check_rate_limits(response_headers: dict):
used_weight = int(response_headers.get('X-MBX-USED-WEIGHT-1M', 0))
order_count = int(response_headers.get('X-MBX-ORDER-COUNT-10S', 0))
if used_weight > 5000: # > 83% of limit — slow down
await asyncio.sleep(1)
if order_count > 8: # > 80% of limit — pause
await asyncio.sleep(0.5)
Trading bot integration with Binance API (spot or futures) with WebSocket data stream and user data stream: 1–2 weeks. Binance sandbox (https://testnet.binance.vision/) is available for testing without real money.







