💡 China users: Binance’s official site can’t be accessed directly from mainland China—you’ll need your own networking tools. Fiat deposits don’t support bank cards; the main method is C2C (USDT↔CNY) channels.

An unlocked padlock rests on a computer keyboard.

The Binance API is your gateway to quantitative trading. If you want your strategy to execute automatically—auto buy, auto stop-loss, auto position monitoring—you need the API.

This article covers everything from scratch: requesting an API Key, configuring security, setting up Python, and making your first query and test order. No prior quant experience needed—just follow along.

Prerequisites

  1. Completed Binance account KYC verification
  2. Python 3.8+ (python --version to confirm)
  3. Two-factor authentication (2FA) enabled; Google Authenticator recommended

Binance registration: → Sign up (earn fee rebates via referral link)

Applying for an API Key

Steps

  1. Log into Binance, click your avatar (top right) → API Management
  2. Click “Create API”
  3. Select “System Generated (Recommended)”
  4. Enter an API label (name), click Next
  5. Complete 2FA verification
  6. Save your API Key and Secret Key

Important: Your Secret Key appears only once. After you close the page, it cannot be viewed again. Save it immediately to a password manager.

Permission Configuration

After creating your API, configure permissions in API Management:

PermissionEnable?Notes
Read✓ (default)Query account info, Kline data
Spot TradingAs neededPlace spot orders
Futures TradingAs neededPlace futures orders
WithdrawAbsolutely notQuantitative strategies don’t need this; enabling it is a security risk

IP Whitelist (highly recommended): Bind your server IP in API settings—only that IP can use this API Key. Even if the key leaks, other IPs can’t use it.

Security Principles

  • Use a separate API Key for each strategy; don’t share keys across multiple strategies
  • Use different keys for your quant server and personal computer
  • Rotate keys regularly (every 3–6 months)
  • Never commit keys to GitHub or share them with anyone

Setting Up Python Environment

Install the official SDK:

pip install python-binance

First API Call: Checking Account Balance

from binance.client import Client

# Load API Key from environment variables, never hardcode
import os
api_key = os.environ["BINANCE_API_KEY"]
api_secret = os.environ["BINANCE_API_SECRET"]

client = Client(api_key, api_secret)

# Query account info
account = client.get_account()

# Display non-zero balances
print("Current balance:")
for asset in account["balances"]:
    free = float(asset["free"])
    locked = float(asset["locked"])
    if free > 0 or locked > 0:
        print(f"  {asset['asset']}: Available {free}, Locked {locked}")

If you see your balances after running this, your API is configured correctly.

Querying Market Data

# Query current BTC/USDT price
ticker = client.get_symbol_ticker(symbol="BTCUSDT")
print(f"BTC current price: {ticker['price']}")

# Query 24h market stats
stats = client.get_ticker(symbol="BTCUSDT")
print(f"24h high: {stats['highPrice']}")
print(f"24h low: {stats['lowPrice']}")
print(f"24h volume: {stats['volume']} BTC")

# Query Kline data (last 10 hourly candles)
klines = client.get_klines(
    symbol="BTCUSDT",
    interval=Client.KLINE_INTERVAL_1HOUR,
    limit=10
)

for k in klines:
    timestamp = k[0]
    open_price = float(k[1])
    close_price = float(k[4])
    volume = float(k[5])
    print(f"Open: {open_price:.2f}, Close: {close_price:.2f}, Volume: {volume:.2f}")

Placing Orders on Testnet

Strongly recommended: practice on testnet first without spending real money.

Get a testnet API Key:

  1. Go to testnet.binance.vision
  2. Log in with your GitHub account
  3. Create a testnet API Key
from binance.client import Client

# Testnet API Key
client = Client(
    api_key="your_testnet_API_KEY",
    api_secret="your_testnet_SECRET",
    testnet=True         # Critical: points to testnet
)

# Place a limit buy order (BTC/USDT, buy 0.001 BTC at 20000 USDT)
order = client.create_order(
    symbol="BTCUSDT",
    side=Client.SIDE_BUY,
    type=Client.ORDER_TYPE_LIMIT,
    timeInForce=Client.TIME_IN_FORCE_GTC,
    quantity=0.001,
    price="20000"
)

print(f"Order ID: {order['orderId']}")
print(f"Status: {order['status']}")

# Query order status
status = client.get_order(
    symbol="BTCUSDT",
    orderId=order['orderId']
)
print(f"Current status: {status['status']}")

# Cancel order
client.cancel_order(
    symbol="BTCUSDT",
    orderId=order['orderId']
)
print("Order canceled")

WebSocket Real-Time Data Stream

REST API is for placing orders and queries; WebSocket is more efficient for real-time data:

from binance import ThreadedWebsocketManager

def handle_ticker(msg):
    """Handle real-time price updates"""
    if msg['e'] == 'error':
        print(f"Error: {msg['m']}")
        return
    
    price = float(msg['c'])         # Latest trade price
    volume = float(msg['v'])        # 24h volume
    print(f"BTC price: {price:.2f}, 24h volume: {volume:.2f}")

# Start WebSocket manager
twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)
twm.start()

# Subscribe to BTC/USDT real-time ticker
twm.start_symbol_ticker_socket(callback=handle_ticker, symbol="BTCUSDT")

# Stop after 30 seconds
import time
time.sleep(30)
twm.stop()

Rate Limits

Binance API enforces rate limits; exceeding them triggers temporary bans:

TypeLimit
Request Weight1200 weight/minute
Order Rate10 orders/second, 100,000 orders/24h
WebSocket ConnectionsMax 1024

Weight for common endpoints:

  • GET /api/v3/ticker/price: 2 weight
  • GET /api/v3/klines: 2 weight
  • POST /api/v3/order (place order): 1 weight

Querying the latest price every 5 seconds = 12 times/minute × 2 weight = 24 weight—well below the limit.

For real-time data, always use WebSocket instead of polling REST endpoints.

Next Steps

Once you’ve got the basics working:

  • Learn the Kline data structure and start building your first strategy logic
  • Study position sizing: how much to allocate per order
  • Set up Prometheus monitoring for strategy health

→ See Binance Fee Reduction Tips → See Binance API Security Configuration → See Quant Tech Stack: Strategy to Monitoring


📷 Cover image · Generated by Flux Schnell AI · panshi.io brand style