Algo Trading with Exchange APIs
Binance, Bybit, and dYdX API integration: authentication, order lifecycle, WebSocket feeds, rate limiting, and building your first algorithmic trading bot.
From Thrive on YouTube
Watch the matching Thrive video
Exchange Security for Traders: Protect Your Account From the Common Attacks
Part of Trading Psychology for Futures Traders. Education only. Not financial advice.
Exchange API Architecture
Algorithmic trading starts at the API layer. Every exchange exposes two primary interfaces: a REST API for account management and order placement, and a WebSocket API for real-time market data streams. The REST API is request-response. You send a signed HTTP request and receive a JSON response. The WebSocket API maintains a persistent bidirectional connection, pushing price updates, order fills, and account changes to your client the instant they occur. Understanding both interfaces, their rate limits, and their failure modes is the foundation of every automated trading system.
Authentication follows a common pattern across exchanges: you generate an API key pair (public key and secret key), then sign each request using HMAC-SHA256 with your secret. The signature covers the request parameters and a timestamp to prevent replay attacks. Never expose your secret key in code repositories, logs, or client-side applications. Use environment variables or a dedicated secrets manager.
1import hmac2import hashlib3import time4import requests5from urllib.parse import urlencode67API_KEY = os.environ['BINANCE_API_KEY']8API_SECRET = os.environ['BINANCE_API_SECRET']910def sign_request(params: dict) -> dict:11 """Sign a Binance REST API request with HMAC-SHA256."""12 params['timestamp'] = int(time.time() * 1000)13 query_string = urlencode(params)14 signature = hmac.new(15 API_SECRET.encode('utf-8'),16 query_string.encode('utf-8'),17 hashlib.sha25618 ).hexdigest()19 params['signature'] = signature20 return params2122def get_account_info():23 url = 'https://api.binance.com/api/v3/account'24 params = sign_request({})25 headers = {'X-MBX-APIKEY': API_KEY}26 resp = requests.get(url, params=params, headers=headers, timeout=10)27 resp.raise_for_status()28 return resp.json()Binance: REST + WebSocket
Binance is the highest-volume centralized exchange and has the most mature API. The REST API supports all order book operations: market, limit, stop-limit, stop-market, trailing stop, and OCO (one-cancels-the-other) orders. Rate limits are tiered: 1,200 request weight per minute for most endpoints, with individual endpoints consuming 1-50 weight depending on complexity. IP whitelisting is mandatory for withdrawal permissions and strongly recommended for trading keys.
1import ccxt2import os34exchange = ccxt.binance({5 'apiKey': os.environ['BINANCE_API_KEY'],6 'secret': os.environ['BINANCE_API_SECRET'],7 'enableRateLimit': True,8 'options': {'defaultType': 'future'}, # Use futures API9})1011# Place a limit buy order12order = exchange.create_order(13 symbol='BTC/USDT',14 type='limit',15 side='buy',16 amount=0.01, # 0.01 BTC17 price=62000, # Limit price18 params={19 'timeInForce': 'GTC', # Good-til-cancelled20 }21)22print(f"Order ID: {order['id']}, Status: {order['status']}")2324# Place a stop-market order (stop loss)25stop_order = exchange.create_order(26 symbol='BTC/USDT',27 type='stop_market',28 side='sell',29 amount=0.01,30 params={31 'stopPrice': 60000,32 'closePosition': False,33 }34)3536# Modify an existing order37modified = exchange.edit_order(38 id=order['id'],39 symbol='BTC/USDT',40 type='limit',41 side='buy',42 amount=0.01,43 price=61500,44)4546# Cancel an order47exchange.cancel_order(order['id'], 'BTC/USDT')Binance WebSocket Feeds
Binance WebSocket streams provide real-time data without polling. The three essential feeds for algo trading are: the order book depth stream (partial or full book updates), the trade stream (individual fills as they happen), and the user data stream (your order fills, account updates, and margin calls). The user data stream requires a listen key obtained via REST, which must be refreshed every 30 minutes via a keepalive request.
1import ccxt.pro as ccxtpro2import asyncio34async def stream_orderbook_and_trades():5 exchange = ccxtpro.binance({6 'apiKey': os.environ['BINANCE_API_KEY'],7 'secret': os.environ['BINANCE_API_SECRET'],8 'options': {'defaultType': 'future'},9 })1011 async def watch_book():12 while True:13 book = await exchange.watch_order_book('BTC/USDT', limit=20)14 best_bid = book['bids'][0][0] if book['bids'] else None15 best_ask = book['asks'][0][0] if book['asks'] else None16 spread = best_ask - best_bid if best_bid and best_ask else 017 print(f"Bid: {best_bid} | Ask: {best_ask} | Spread: {spread:.2f}")1819 async def watch_fills():20 while True:21 orders = await exchange.watch_orders('BTC/USDT')22 for o in orders:23 print(f"Fill: {o['side']} {o['filled']}/{o['amount']} @ {o['price']}")2425 await asyncio.gather(watch_book(), watch_fills())2627asyncio.run(stream_orderbook_and_trades())Bybit: Unified API v5
Bybit's unified v5 API consolidates spot, linear perpetual futures, inverse perpetuals, and options into a single endpoint structure. Position modes matter: one-way mode allows a single position per symbol (net long or short), while hedge mode allows simultaneous long and short positions. Hedge mode is essential for basis trades and hedging strategies. Bybit's rate limit is 10 requests per second on order endpoints for standard accounts, upgradeable to 50/s for VIP tiers.
1exchange = ccxt.bybit({2 'apiKey': os.environ['BYBIT_API_KEY'],3 'secret': os.environ['BYBIT_API_SECRET'],4 'enableRateLimit': True,5})67# Set position mode to hedge mode8exchange.set_position_mode(hedged=True, symbol='BTC/USDT')910# Set leverage11exchange.set_leverage(5, 'BTC/USDT')1213# Open a long position14long_order = exchange.create_order(15 symbol='BTC/USDT',16 type='limit',17 side='buy',18 amount=0.01,19 price=62000,20 params={21 'positionIdx': 1, # 1 = long side in hedge mode22 'timeInForce': 'PostOnly', # Maker only23 }24)2526# Open a short hedge simultaneously27short_order = exchange.create_order(28 symbol='BTC/USDT',29 type='limit',30 side='sell',31 amount=0.005,32 price=63000,33 params={34 'positionIdx': 2, # 2 = short side in hedge mode35 }36)3738# Fetch positions39positions = exchange.fetch_positions(['BTC/USDT'])40for pos in positions:41 if float(pos['contracts']) > 0:42 print(f"{pos['side']}: {pos['contracts']} @ {pos['entryPrice']}")dYdX v4: On-Chain Order Book
dYdX v4 is fundamentally different from centralized exchanges. It runs on a custom Cosmos appchain where the order book is maintained by validators in an off-chain memory structure (ClobPair) that gets committed on-chain at block finality. Orders are placed by signing Cosmos SDK transactions with your wallet. There are no API keys: authentication is your wallet's private key. This decentralized architecture means no counterparty risk, no KYC requirements, and no withdrawal delays, but it introduces block-time latency (typically 1-2 seconds) for order placement.
1from dydx_v4_client import CompositeClient, Subaccount2from dydx_v4_client.node.market import Market34MNEMONIC = os.environ['DYDX_MNEMONIC']56client = CompositeClient.connect(network='mainnet')7subaccount = Subaccount.from_mnemonic(MNEMONIC, subaccount_number=0)89# Place a limit order10tx_hash = client.place_order(11 subaccount=subaccount,12 market=Market.BTC_USD,13 side='BUY',14 price=62000.0,15 size=0.01,16 order_type='LIMIT',17 time_in_force='GTT',18 good_til_block=client.get_latest_block() + 20,19 reduce_only=False,20)21print(f"TX: {tx_hash}")2223# Query open positions24positions = client.get_subaccount_positions(subaccount)25for pos in positions:26 print(f"{pos['market']}: {pos['side']} {pos['size']} @ {pos['entry_price']}")Rate Limiting and Error Handling
Every exchange will ban your IP or revoke your API key if you exceed rate limits. A production system needs a rate limiter that tracks request weight per time window, queues requests when approaching the limit, and backs off exponentially when receiving 429 or 418 status codes. The ccxt library handles basic rate limiting with enableRateLimit: True, but production systems need a more sophisticated approach.
1import asyncio2from collections import deque3from datetime import datetime, timedelta45class RateLimiter:6 def __init__(self, max_weight: int = 1200, window_seconds: int = 60):7 self.max_weight = max_weight8 self.window = timedelta(seconds=window_seconds)9 self.requests: deque = deque()1011 async def acquire(self, weight: int = 1):12 """Wait until we have capacity for this request weight."""13 while True:14 now = datetime.utcnow()15 # Purge expired entries16 while self.requests and self.requests[0][0] < now - self.window:17 self.requests.popleft()1819 current_weight = sum(w for _, w in self.requests)20 if current_weight + weight <= self.max_weight:21 self.requests.append((now, weight))22 return23 await asyncio.sleep(0.1)2425async def safe_api_call(exchange, method, *args, max_retries=3, **kwargs):26 """Execute an exchange API call with exponential backoff."""27 for attempt in range(max_retries):28 try:29 return await method(*args, **kwargs)30 except ccxt.RateLimitExceeded:31 wait = 2 ** attempt * 532 print(f"Rate limited. Waiting {wait}s...")33 await asyncio.sleep(wait)34 except ccxt.NetworkError as e:35 wait = 2 ** attempt36 print(f"Network error: {e}. Retry in {wait}s...")37 await asyncio.sleep(wait)38 except ccxt.ExchangeError as e:39 print(f"Exchange error: {e}")40 raise41 raise Exception(f"Max retries ({max_retries}) exceeded")| Order lifecycle | Place → Acknowledged → Partially filled → Filled / Cancelled. Always track state transitions via WebSocket user data stream, not REST polling. Missed fills mean phantom positions. |
| IP whitelisting | Restrict API key access to specific IPs. On Binance, required for withdrawal-enabled keys. Use your server's static IP, not a dynamic residential IP. |
| Slippage | Market orders execute at the best available price, which may differ from the last traded price. On thin books, a 0.1 BTC market order can slip 0.1-0.5% on mid-cap pairs. |
| Nonce / Timestamp | Every signed request includes a timestamp. Binance rejects requests with timestamps >5 seconds from server time. Keep your system clock synchronized with NTP. |
Never trust a single data source
1.What authentication method do most centralized exchange APIs use to verify request integrity?
2.How does dYdX v4 differ fundamentally from Binance and Bybit in its order book architecture?
3.What is the purpose of hedge mode on Bybit?
4.Why must a production trading system track order state via WebSocket rather than REST polling?
5.What happens if your signed API request has a timestamp more than 5 seconds from Binance's server time?
Put this lesson to work
Free on Thrive, no account needed.