GEVORDERD · DERIVATEN & ALGO

API Trading Basics

REST vs WebSocket, authentication, rate limits, and building your first automated order.

Automatisch handelen met algoritmen: voordelen, risico's en eerste stappen.

Why Trade via API?

An API (Application Programming Interface) allows you to interact with an exchange programmatically - placing orders, checking balances, and receiving market data through code instead of clicking buttons on a website.

Benefits of API trading:

  • Speed: Automated orders execute in milliseconds, far faster than manual clicking.
  • Consistency: Code doesn't get emotional, tired, or distracted.
  • Scalability: Monitor and trade multiple instruments simultaneously.
  • Backtesting integration: The same logic you backtest can be deployed live.

REST vs WebSocket

Exchanges typically offer two types of API connections:

TypeHow it worksBest for
REST APIRequest/response model. You send a request, get a response.Placing orders, checking balances, historical data
WebSocketPersistent connection. Data streams continuously.Real-time price feeds, order book updates, trade streams
  • REST is like asking a question and getting an answer. Each request is independent.
  • WebSocket is like opening a phone line - data flows continuously until you hang up.

Most trading bots use both: WebSocket for real-time data and REST for order execution.

Authentication & API Keys

To place orders via API, you need API keys - a pair of credentials (API key + secret) that identify and authorize your requests.

  • API Key: Your public identifier (like a username).
  • API Secret: Your private key (like a password). Never share this.
  • Permissions: Most exchanges let you set permissions per key (read-only, trade, withdraw). Always use the minimum permissions needed.
Security rules:
  • Never commit API keys to version control (Git).
  • Use environment variables or encrypted config files.
  • Enable IP whitelisting - restrict API access to your server's IP.
  • Never enable withdrawal permissions unless absolutely necessary.
  • Rotate keys periodically.

Rate Limits

Exchanges impose rate limits - maximum number of API requests per time window. Exceeding them results in temporary bans or throttling.

  • Typical limits: 10-20 requests per second for REST, varies for WebSocket.
  • Order-related endpoints often have stricter limits than data endpoints.
  • Your code must handle rate limit errors gracefully (back off and retry).
// Pseudocode: Simple rate limit handling function placeOrder(params) { try { response = api.post('/order', params); return response; } catch (error) { if (error.code === 429) { // Rate limited sleep(1000); // Wait 1 second return placeOrder(params); // Retry } throw error; } }

Anatomy of an API Order

A typical order request includes:

POST /api/v1/order { "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "price": "52000.00", "quantity": "0.1", "timeInForce": "GTC" }
  • symbol: The trading pair.
  • side: BUY or SELL.
  • type: LIMIT, MARKET, STOP_LIMIT, etc.
  • price: For limit orders, the price you want.
  • quantity: How much to buy/sell.
  • timeInForce: GTC (Good Till Cancelled), IOC (Immediate Or Cancel), FOK (Fill Or Kill).

Error Handling Is Critical

In automated trading, errors are inevitable. Your code must handle:

  • Network failures: Connection drops, timeouts. Did the order go through or not?
  • Insufficient balance: Your code tried to place an order larger than your available funds.
  • Invalid parameters: Wrong symbol, price precision, minimum order size.
  • Exchange maintenance: APIs go down for maintenance, sometimes without warning.
The "unknown state" problem: If you send an order and the connection drops before you get a response, you don't know if the order was placed or not. Your code must be able to query open orders and reconcile state. This is one of the hardest problems in automated trading.

Starting Safe: Paper Trading via API

Most major exchanges offer testnet or sandbox environments - API endpoints that behave like the real exchange but use fake money. Always develop and test on testnet first.

  • Testnet lets you verify your order logic without risking real capital.
  • Test edge cases: what happens if the market moves while your order is pending? What if you get partially filled?
  • Only move to production after extensive testnet validation.

Practice

Exercise 1

Write pseudocode for a simple bot that: (1) connects to a WebSocket price feed, (2) checks if the price drops below a threshold, (3) places a limit buy order via REST API, (4) handles rate limits and errors.

Exercise 2

List 5 things that could go wrong with an automated order and how you would handle each one in code.

Key Takeaways

  • APIs enable automated, fast, consistent trading.
  • REST for actions (orders, balances); WebSocket for real-time data.
  • API key security is non-negotiable - never expose secrets.
  • Rate limits and error handling are critical infrastructure, not afterthoughts.
  • Always develop on testnet before risking real capital.

Wat is algoritmisch handelen?

Algoritmisch handelen (algo trading) gebruikt computerprogramma's om trades automatisch uit te voeren op basis van vooraf gedefinieerde regels. Het elimineert emotie en kan sneller reageren dan mensen.

Voordelen en risico's

  • Voordelen: Snelheid, consistentie, geen emotie, backtesting mogelijk.
  • Risico's: Technische fouten, overfitting, marktveranderingen, flash crashes.

Belangrijkste punten

  • Algo's voeren regels uit zonder emotie.
  • Backtesting is essentieel maar geen garantie.
  • Risicobeheer blijft cruciaal, ook met algoritmen.
  • Begin eenvoudig en bouw geleidelijk complexiteit op.

Les afgerond

Je hebt afgerond: API Trading Basics.