Binance API Docs: A Trader's Guide to Automated Trading
Master the Binance API docs to build trading bots, pull market data, and automate your crypto strategies. Covers spot, futures, WebSocket streams, and rate limits.
Master the Binance API docs to build trading bots, pull market data, and automate your crypto strategies. Covers spot, futures, WebSocket streams, and rate limits.
The Binance API docs are the single most important resource for anyone building automated trading systems on the world's largest crypto exchange. Whether you're pulling kline data for backtesting, streaming real-time prices over WebSocket, or placing futures orders programmatically — everything starts with understanding the documentation. The problem? The docs are massive, spread across multiple repositories, and updated frequently. This guide cuts through the noise and gives you exactly what you need to start building.
Binance maintains separate API documentation for each product line. The Binance API docs spot section covers everything related to the spot exchange — order placement, account info, market data, and wallet operations. The Binance API docs futures section handles USDT-M and COIN-M perpetual contracts with their own set of endpoints, margin modes, and position management calls. There's also a separate section for European-style options and the lending/earn products.
The official Binance API docs GitHub repository (github.com/binance/binance-spot-api-docs) is where you'll find the raw markdown documentation, changelog entries, and community-reported issues. This is often more up-to-date than the rendered web version, and the Binance API docs changelog there will show you exactly what endpoints have changed or been deprecated. Bookmark it — you'll reference it constantly.
| Resource | What It Covers | URL Pattern |
|---|---|---|
| Spot API Docs | Trading, market data, wallet | binance-docs.github.io/apidocs/spot |
| Futures API Docs | USDT-M and COIN-M contracts | binance-docs.github.io/apidocs/futures |
| GitHub Repository | Raw docs, changelog, issues | github.com/binance/binance-spot-api-docs |
| WebSocket Streams | Real-time market and user data | Included in spot/futures docs |
While some traders look for a Binance API docs PDF, Binance doesn't provide an official PDF version. The documentation is a living document that changes frequently — a static PDF would be outdated within weeks. If you need offline access, cloning the GitHub repo is the better approach.
Every authenticated request to the Binance API requires an API key and secret. You generate these from your Binance account settings under API Management. The key goes in the X-MBX-APIKEY header, and the secret is used to create an HMAC SHA256 signature of your query parameters. The Binance Python API docs and the official python-binance library handle most of this for you, but understanding the raw mechanism matters when debugging failed requests.
import hashlib
import hmac
import time
import requests
API_KEY = 'your_api_key_here'
API_SECRET = 'your_api_secret_here'
BASE_URL = 'https://api.binance.com'
def signed_request(endpoint, params=None):
if params is None:
params = {}
params['timestamp'] = int(time.time() * 1000)
query_string = '&'.join(f'{k}={v}' for k, v in params.items())
signature = hmac.new(
API_SECRET.encode(), query_string.encode(), hashlib.sha256
).hexdigest()
params['signature'] = signature
headers = {'X-MBX-APIKEY': API_KEY}
response = requests.get(f'{BASE_URL}{endpoint}', params=params, headers=headers)
if response.status_code != 200:
print(f'Error {response.status_code}: {response.json()["msg"]}')
return None
return response.json()
# Get account balance
account = signed_request('/api/v3/account')
if account:
balances = [b for b in account['balances'] if float(b['free']) > 0]
for b in balances:
print(f"{b['asset']}: {b['free']} available, {b['locked']} locked")
Never hardcode your API keys in source files. Use environment variables or a .env file with python-dotenv. If your keys leak to a public GitHub repo, bots will drain your account within minutes.
Other exchanges follow similar patterns. Bybit uses an API key plus HMAC signature with a slightly different parameter format. OKX requires an additional passphrase alongside the key and secret. Once you've built one integration, the others follow naturally — the concepts are the same, only the specifics differ.
The Binance API docs klines endpoint is probably the most-used endpoint for algo traders and analysts. It returns OHLCV (open, high, low, close, volume) candlestick data for any trading pair and timeframe. This is the foundation for backtesting strategies, training ML models, or feeding data into platforms like VoiceOfChain for real-time signal generation.
import requests
import pandas as pd
def get_klines(symbol, interval='1h', limit=500):
"""Fetch kline/candlestick data from Binance.
Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
Max limit: 1000 candles per request
"""
url = 'https://api.binance.com/api/v3/klines'
params = {'symbol': symbol, 'interval': interval, 'limit': limit}
response = requests.get(url, params=params)
data = response.json()
df = pd.DataFrame(data, columns=[
'open_time', 'open', 'high', 'low', 'close', 'volume',
'close_time', 'quote_volume', 'trades',
'taker_buy_base', 'taker_buy_quote', 'ignore'
])
df['open_time'] = pd.to_datetime(df['open_time'], unit='ms')
for col in ['open', 'high', 'low', 'close', 'volume']:
df[col] = df[col].astype(float)
return df[['open_time', 'open', 'high', 'low', 'close', 'volume']]
# Pull 4h candles for BTC/USDT
btc = get_klines('BTCUSDT', '4h', 200)
print(btc.tail())
print(f"Current price: {btc['close'].iloc[-1]:.2f}")
print(f"24h range: {btc['low'].tail(6).min():.2f} - {btc['high'].tail(6).max():.2f}")
The klines endpoint doesn't require authentication — it's public market data. This makes it easy to prototype without dealing with API keys. You can pull historical data going back years by paginating with the startTime and endTime parameters. Just note the Binance API docs rate limit: public endpoints are capped at 1200 request weight per minute per IP address, and the klines endpoint costs between 1-5 weight depending on the limit parameter.
REST APIs are fine for periodic data pulls, but if you're running a live trading bot, you need the Binance API docs WebSocket streams. WebSocket connections give you a persistent, low-latency feed of market data without the overhead of repeated HTTP requests. Binance offers individual streams (one symbol, one data type) and combined streams (multiple symbols in a single connection).
import json
import websocket
def on_message(ws, message):
data = json.loads(message)
if data.get('e') == 'trade':
print(f"{data['s']} | Price: {data['p']} | Qty: {data['q']} | {'BUY' if data['m'] is False else 'SELL'}")
elif data.get('e') == 'kline':
k = data['k']
if k['x']: # kline closed
print(f"Closed {k['i']} candle: O={k['o']} H={k['h']} L={k['l']} C={k['c']} V={k['v']}")
def on_error(ws, error):
print(f"WebSocket error: {error}")
def on_close(ws, code, msg):
print(f"Connection closed ({code}): {msg}")
# Subscribe to BTC/USDT trade stream and 1m klines
stream_url = 'wss://stream.binance.com:9443/stream?streams=btcusdt@trade/btcusdt@kline_1m'
ws = websocket.WebSocketApp(
stream_url,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
Binance allows up to 5 messages per second per WebSocket connection and a maximum of 1024 streams per connection. If you're tracking the entire USDT perpetual market, you'll need multiple connections. The Binance API docs WebSocket section also covers user data streams — these push order updates, balance changes, and position updates to your bot without polling.
Competitors handle streaming differently. Bybit uses a similar WebSocket approach but with a different subscription format. Coinbase Pro uses a channels-based subscription model. The principle is always the same — maintain a persistent connection and react to incoming events — but the payload structures vary. If you're building a multi-exchange bot, abstract your data handlers behind a common interface.
The Binance API docs rate limit system is weight-based. Each endpoint has an assigned weight, and you get a budget of 1200 weight per minute for order-related endpoints and 6000 per minute for raw requests. Exceed the limit and you'll get a 429 response with a Retry-After header. Get banned (HTTP 418) and you're locked out for a duration that escalates with repeat violations.
Production bots need proper error handling. Network timeouts, signature errors, insufficient balance, and rate limit hits are all common. The difference between a bot that runs for months and one that crashes on day one is how well it handles these edge cases. Always implement exponential backoff on retries, and log every error with the full request context so you can debug issues after the fact.
Use Binance's testnet (testnet.binance.vision for spot, testnet.binancefuture.com for futures) to develop and test your bot. It has the same API endpoints but uses fake money. Switch to production only after thorough testing.
The Binance API docs spot and futures sections look similar at first glance, but there are critical differences. Futures trading adds concepts like leverage, margin modes (isolated vs cross), position side (long/short with hedge mode), and funding rates. The base URLs differ — api.binance.com for spot vs fapi.binance.com for USDT-M futures and dapi.binance.com for COIN-M futures.
| Feature | Spot API | Futures API |
|---|---|---|
| Base URL | api.binance.com | fapi.binance.com |
| Order Types | LIMIT, MARKET, STOP_LOSS, etc. | Same + STOP_MARKET, TAKE_PROFIT_MARKET |
| Position Concept | None (you hold assets) | Long/Short positions with leverage |
| Margin | Not applicable | Cross or Isolated, 1x-125x leverage |
| Funding Rate | Not applicable | /fapi/v1/fundingRate endpoint |
| Rate Limit Weight | 1200/min | 2400/min |
If you're running strategies that combine spot holdings with futures hedging, you need both API integrations. Platforms like Bitget and KuCoin offer similar unified margin accounts through their APIs, but Binance keeps them strictly separated. Your bot architecture should reflect this — separate clients, separate rate limit tracking, separate error handling for each product.
The Binance API docs are comprehensive but dense. Start with one product (spot or futures), get comfortable with authentication and basic market data pulls, then layer on WebSocket streams for real-time data. Build your error handling and rate limit management early — retrofitting these into a running bot is painful. Use the testnet until your bot handles all edge cases cleanly, and keep an eye on the Binance API docs changelog for breaking changes that could affect your code.
For traders who want market signals without building the entire pipeline themselves, VoiceOfChain provides real-time trading signals that aggregate data across multiple exchanges including Binance, Bybit, and OKX. Whether you're building custom tools on top of the raw API or using pre-built signal platforms, understanding how the Binance API works under the hood makes you a better trader and a more effective builder.