Skip to main content

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

Watch the series
Exchange Security for Traders: Protect Your Account From the Common Attacks

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.

python-HMAC authentication pattern
1import hmac
2import hashlib
3import time
4import requests
5from urllib.parse import urlencode
6
7API_KEY = os.environ['BINANCE_API_KEY']
8API_SECRET = os.environ['BINANCE_API_SECRET']
9
10def 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.sha256
18 ).hexdigest()
19 params['signature'] = signature
20 return params
21
22def 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.

python-Binance order placement via ccxt
1import ccxt
2import os
3
4exchange = 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 API
9})
10
11# Place a limit buy order
12order = exchange.create_order(
13 symbol='BTC/USDT',
14 type='limit',
15 side='buy',
16 amount=0.01, # 0.01 BTC
17 price=62000, # Limit price
18 params={
19 'timeInForce': 'GTC', # Good-til-cancelled
20 }
21)
22print(f"Order ID: {order['id']}, Status: {order['status']}")
23
24# 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)
35
36# Modify an existing order
37modified = 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)
45
46# Cancel an order
47exchange.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.

python-Binance WebSocket with ccxt.pro
1import ccxt.pro as ccxtpro
2import asyncio
3
4async 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 })
10
11 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 None
15 best_ask = book['asks'][0][0] if book['asks'] else None
16 spread = best_ask - best_bid if best_bid and best_ask else 0
17 print(f"Bid: {best_bid} | Ask: {best_ask} | Spread: {spread:.2f}")
18
19 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']}")
24
25 await asyncio.gather(watch_book(), watch_fills())
26
27asyncio.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.

python-Bybit v5 integration
1exchange = ccxt.bybit({
2 'apiKey': os.environ['BYBIT_API_KEY'],
3 'secret': os.environ['BYBIT_API_SECRET'],
4 'enableRateLimit': True,
5})
6
7# Set position mode to hedge mode
8exchange.set_position_mode(hedged=True, symbol='BTC/USDT')
9
10# Set leverage
11exchange.set_leverage(5, 'BTC/USDT')
12
13# Open a long position
14long_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 mode
22 'timeInForce': 'PostOnly', # Maker only
23 }
24)
25
26# Open a short hedge simultaneously
27short_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 mode
35 }
36)
37
38# Fetch positions
39positions = 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.

python-dYdX v4 order via Python SDK
1from dydx_v4_client import CompositeClient, Subaccount
2from dydx_v4_client.node.market import Market
3
4MNEMONIC = os.environ['DYDX_MNEMONIC']
5
6client = CompositeClient.connect(network='mainnet')
7subaccount = Subaccount.from_mnemonic(MNEMONIC, subaccount_number=0)
8
9# Place a limit order
10tx_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}")
22
23# Query open positions
24positions = 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.

python-Production rate limiter with retry
1import asyncio
2from collections import deque
3from datetime import datetime, timedelta
4
5class RateLimiter:
6 def __init__(self, max_weight: int = 1200, window_seconds: int = 60):
7 self.max_weight = max_weight
8 self.window = timedelta(seconds=window_seconds)
9 self.requests: deque = deque()
10
11 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 entries
16 while self.requests and self.requests[0][0] < now - self.window:
17 self.requests.popleft()
18
19 current_weight = sum(w for _, w in self.requests)
20 if current_weight + weight <= self.max_weight:
21 self.requests.append((now, weight))
22 return
23 await asyncio.sleep(0.1)
24
25async 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 * 5
32 print(f"Rate limited. Waiting {wait}s...")
33 await asyncio.sleep(wait)
34 except ccxt.NetworkError as e:
35 wait = 2 ** attempt
36 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 raise
41 raise Exception(f"Max retries ({max_retries}) exceeded")
Order lifecyclePlace → Acknowledged → Partially filled → Filled / Cancelled. Always track state transitions via WebSocket user data stream, not REST polling. Missed fills mean phantom positions.
IP whitelistingRestrict API key access to specific IPs. On Binance, required for withdrawal-enabled keys. Use your server's static IP, not a dynamic residential IP.
SlippageMarket 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 / TimestampEvery 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

WebSocket connections drop. REST endpoints timeout. Exchanges have unannounced maintenance windows. A production system must handle all of these gracefully: reconnect WebSockets with exponential backoff, fall back from WebSocket to REST polling during outages, and halt trading when data integrity cannot be confirmed. The most expensive bug in algo trading is acting on stale data.
Module Quiz

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?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.