← Back to Learn
II IntermediateWeek 27 • Lesson 75Duration: 45 min

API API Development for Trading

Building the interface between your trading engine and everything else

Learning Objectives

  • Build REST APIs for trading system interactions
  • Implement authentication and rate limiting
  • Design API endpoints for monitoring and control

Explain Like I'm 5

An API lets other programs talk to your trading system. Want a dashboard showing real-time PnL? API. Want alerts on your phone? API. Want a second system to trigger trades? API. It's the interface between your engine and literally everything else. Without an API, your trading engine is a lonely box that nobody can interact with except through the terminal. Building good APIs is one of the most broadly useful skills in software engineering.

Think of It This Way

An API is like a restaurant menu. The kitchen (trading engine) can make many things, but customers (dashboards, apps, alerts) can only order what's on the menu (API endpoints). The menu standardizes communication — you don't walk into the kitchen and start cooking. You order from the menu, the kitchen prepares it, and the waiter (HTTP) delivers it.

1Trading API Endpoints

Essential endpoints for a trading system — the minimum viable API: Status and monitoring: - GET /api/status -> engine status, uptime, connection state - GET /api/portfolio -> current positions, PnL, exposure - GET /api/risk -> DD zone, risk level, daily/total limits used Historical data: - GET /api/trades?from=&to= -> trade history with filtering - GET /api/performance -> win rate, total R, drawdown curve - GET /api/signals -> recent signal decisions and outcomes Control (handle with extreme care): - POST /api/trading/start -> start live trading - POST /api/trading/stop -> stop (close all, cancel pending) - POST /api/risk/override -> manual risk level override Configuration: - GET /api/config -> current config - PUT /api/config/risk -> update risk parameters FastAPI is the standout framework for this — fast, auto-documented (free Swagger docs at /docs), async support, and Pydantic validation built in. Django REST framework works too but it's heavier.

2Security — This Controls Real Money

This is not a blog API where the worst case is someone reading your posts. This API controls REAL MONEY. Security is not optional: Authentication: NEVER expose trading APIs without auth. - API keys for server-to-server communication - JWT tokens for web dashboard sessions - OAuth for third-party access (if ever needed) - For personal use, a strong API key is sufficient Rate limiting: Prevent abuse and accidental loops. - Max 10 requests/second for data endpoints - Max 1 request/second for trade endpoints - Implement circuit breaker for external APIs - Rate limiting your OWN endpoints might seem unnecessary until you accidentally write an infinite polling loop HTTPS only: Encrypt all communication. No exceptions. Input validation: Reject malformed requests. - Validate parameter types and ranges - SQL injection prevention (use parameterized queries) - Never trust client input — even if the client is your own code Logging: Log every API call for audit trail. - Who called what, when, with what parameters - Critical for debugging and compliance One bug in the API could mean unauthorized trades or leaked credentials. This is arguably the most important section in this entire lesson.

3WebSocket vs REST for Live Data

REST is great for request/response patterns. But for real-time data streaming, WebSockets are the better tool: REST (HTTP): - Client asks -> server responds - Good for: fetching trade history, checking status, submitting orders - Bad for: live price updates (you'd have to poll constantly) - Every request has overhead (headers, connection setup) WebSocket: - Persistent connection — server pushes data to client - Good for: live PnL updates, price streaming, alert notifications - Much lower latency than polling REST every second - One connection handles many events The production pattern: - REST for everything that's request/response - WebSocket for the dashboard's live data feed - This gives you the best of both worlds Most trading dashboards use WebSocket for the live elements (equity curve updating in real time, current positions) and REST for historical queries and config changes.

REST Polling vs WebSocket: Requests per Minute for Live Dashboard

4API Design Mistakes That Will Haunt You

Common mistakes I've seen (and made): Mistake 1: No versioning. You change the response format, your dashboard breaks. Always version your API: /api/v1/trades, /api/v2/trades. Mistake 2: Trade execution without confirmation. POST /api/trade -> trade executed. No "are you sure?" step. Solution: use a two-step process — POST /api/trade/preview returns what would happen, then POST /api/trade/execute to confirm. Mistake 3: Returning too much data. GET /api/trades returns ALL 4,500 trades in one response. Your dashboard freezes. Solution: pagination. ?limit=50&offset=0. Mistake 4: No error handling. Server returns 500 with a Python traceback. Now the attacker knows your entire stack. Solution: return clean error objects: {error: "Invalid symbol", code: 400}. Mistake 5: Hardcoded credentials. API key in the source code, pushed to GitHub. Congratulations — you just leaked your broker credentials. Solution: environment variables or secrets manager. Always.

Hands-On Code

FastAPI Trading Server

python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional

app = FastAPI(title="V7 Trading Engine API")

class PortfolioResponse(BaseModel):
    positions: list
    total_pnl: float
    drawdown_pct: float
    dd_zone: str
    risk_level: float

@app.get("/api/status")
async def get_status():
    return {
        "engine": "V7 Gold Standard 43S",
        "status": "running",
        "connected": True,
        "open_positions": 3,
        "dd_zone": "NORMAL",
    }

@app.get("/api/portfolio", response_model=PortfolioResponse)
async def get_portfolio():
    return PortfolioResponse(
        positions=[
            {"symbol": "EURUSD", "direction": "LONG", "pnl_r": 0.5},
            {"symbol": "GOLD", "direction": "SHORT", "pnl_r": -0.3},
        ],
        total_pnl=0.2,
        drawdown_pct=1.2,
        dd_zone="NORMAL",
        risk_level=0.30,
    )

@app.get("/api/performance")
async def get_performance(days: int = 30):
    return {
        "period_days": days,
        "trades": 45,
        "win_rate": 0.592,
        "total_r": 14.5,
        "max_dd": 1.49,
    }

# Run: uvicorn main:app --reload

FastAPI gives you auto-generated docs (at /docs), request validation, and async support out of the box. Start with monitoring endpoints, add control endpoints carefully — and never forget authentication.

Knowledge Check

Q1.Your trading API has a POST /api/trade/execute endpoint with no authentication. What's the risk?

Assignment

Build a FastAPI server with at minimum: /api/status, /api/portfolio, /api/trades, /api/risk endpoints. Add API key authentication. Test with curl or a simple frontend.