Skip to main content

Create backtest

curl -X POST http://127.0.0.1:8000/backtests \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "symbols": ["AAPL", "MSFT"],
    "start_date": "2023-01-01T00:00:00Z",
    "end_date": "2023-12-31T23:59:59Z",
    "resolution": "day",
    "strategy": {
      "name": "buy_and_hold",
      "params": {}
    },
    "initial_capital": 1000000.0,
    "currency": "USD"
  }'
Create and start a new backtest run. The backtest executes asynchronously and returns immediately with a run_id and initial status.

Request body

symbols
string[]
required
List of ticker symbols to backtest (1-100 symbols)Example: ["AAPL", "MSFT", "GOOGL"]
start_date
datetime
required
Backtest start date and time in ISO 8601 formatExample: "2023-01-01T00:00:00Z"
end_date
datetime
required
Backtest end date and time in ISO 8601 formatExample: "2023-12-31T23:59:59Z"
resolution
string
default:"day"
Data resolution for the backtestOptions: tick, second, minute, hour, day
strategy
object
Strategy configuration
strategy.name
string
required
Strategy identifier (lowercase, alphanumeric and underscores only, 1-128 chars)Example: "buy_and_hold"
strategy.params
object
default:"{}"
Strategy-specific parameters as key-value pairsExample: {"window": 20, "threshold": 0.05}
execution
object
default:"{}"
Execution cost and latency modeling
execution.slippage_bps
number
Slippage in basis points (1 bp = 0.01%)Example: 5.0 (0.05% slippage)
execution.commission_bps
number
Commission in basis pointsExample: 2.5 (0.025% commission)
execution.latency_ms
integer
Execution latency in millisecondsExample: 100
initial_capital
number
default:"1000000.0"
Starting capital for the backtest (must be > 0 and ≤ 1 trillion)Example: 1000000.0
currency
string
default:"USD"
Currency code (3-5 uppercase letters)Example: "USD", "EUR", "GBP"
timezone
string
default:"UTC"
Timezone for date/time interpretation (max 64 chars)Example: "America/New_York", "Europe/London"

Response

run_id
string
Unique identifier for the backtest run
state
string
Current state of the backtestValues: queued, running, completed, failed
progress
number
Completion progress (0.0 to 1.0)
created_at
datetime
Timestamp when the backtest was created
started_at
datetime
Timestamp when the backtest started running (null if not started)
finished_at
datetime
Timestamp when the backtest finished (null if not finished)
error
string
Error message if state is failed (null otherwise)
{
  "run_id": "550e8400-e29b-41d4-a716-446655440000",
  "state": "queued",
  "progress": 0.0,
  "created_at": "2023-01-15T10:30:00.000Z",
  "started_at": null,
  "finished_at": null,
  "error": null
}

List backtests

curl http://127.0.0.1:8000/backtests?state=completed&limit=10 \
  -H "X-API-Key: your-api-key"
List backtest runs with optional filtering by state.

Query parameters

state
string
Filter by backtest stateOptions: queued, running, completed, failed
limit
integer
default:"50"
Maximum number of results to return (1-200)

Response

Returns an array of backtest status objects (same schema as create backtest response).
[
  {
    "run_id": "550e8400-e29b-41d4-a716-446655440000",
    "state": "completed",
    "progress": 1.0,
    "created_at": "2023-01-15T10:30:00.000Z",
    "started_at": "2023-01-15T10:30:05.000Z",
    "finished_at": "2023-01-15T10:32:00.000Z",
    "error": null
  },
  {
    "run_id": "660e8400-e29b-41d4-a716-446655440001",
    "state": "running",
    "progress": 0.45,
    "created_at": "2023-01-15T11:00:00.000Z",
    "started_at": "2023-01-15T11:00:02.000Z",
    "finished_at": null,
    "error": null
  }
]

Get backtest

curl http://127.0.0.1:8000/backtests/550e8400-e29b-41d4-a716-446655440000 \
  -H "X-API-Key: your-api-key"
Get the current status of a specific backtest run.

Path parameters

run_id
string
required
Unique identifier of the backtest run

Response

Returns a backtest status object (same schema as create backtest response).
{
  "run_id": "550e8400-e29b-41d4-a716-446655440000",
  "state": "running",
  "progress": 0.67,
  "created_at": "2023-01-15T10:30:00.000Z",
  "started_at": "2023-01-15T10:30:05.000Z",
  "finished_at": null,
  "error": null
}

Get results

curl http://127.0.0.1:8000/backtests/550e8400-e29b-41d4-a716-446655440000/results \
  -H "X-API-Key: your-api-key"
Get the full results of a completed backtest, including metrics, equity curve, trades, and logs.

Path parameters

run_id
string
required
Unique identifier of the backtest run

Response

run_id
string
Unique identifier for the backtest run
metrics_summary
object
Key performance metrics as key-value pairsCommon metrics:
  • total_return: Total return percentage
  • sharpe_ratio: Risk-adjusted return metric
  • max_drawdown: Maximum peak-to-trough decline
  • win_rate: Percentage of profitable trades
  • profit_factor: Gross profit divided by gross loss
equity_curve
array
Array of equity data points over timeEach point contains:
  • timestamp: Date/time of the data point
  • equity: Portfolio value at that time
  • cash: Cash balance
  • positions: Total value of positions
trades
array
Array of executed tradesEach trade contains:
  • symbol: Ticker symbol
  • timestamp: Execution time
  • side: buy or sell
  • quantity: Number of shares/units
  • price: Execution price
  • commission: Commission paid
exposures
array
Array of position exposure snapshots over time
logs
string[]
Array of log messages from the backtest execution
{
  "run_id": "550e8400-e29b-41d4-a716-446655440000",
  "metrics_summary": {
    "total_return": 15.2,
    "sharpe_ratio": 1.45,
    "max_drawdown": -8.3,
    "win_rate": 62.5,
    "profit_factor": 1.82,
    "num_trades": 48
  },
  "equity_curve": [
    {
      "timestamp": "2023-01-01T00:00:00Z",
      "equity": 1000000.0,
      "cash": 1000000.0,
      "positions": 0.0
    },
    {
      "timestamp": "2023-01-02T00:00:00Z",
      "equity": 1005000.0,
      "cash": 500000.0,
      "positions": 505000.0
    }
  ],
  "trades": [
    {
      "symbol": "AAPL",
      "timestamp": "2023-01-02T09:30:00Z",
      "side": "buy",
      "quantity": 1000,
      "price": 150.25,
      "commission": 37.56
    }
  ],
  "exposures": [],
  "logs": [
    "Backtest started",
    "Processing AAPL data",
    "Backtest completed successfully"
  ]
}

Stream backtest

const ws = new WebSocket(
  'ws://127.0.0.1:8000/backtests/550e8400-e29b-41d4-a716-446655440000/stream?api_key=your-api-key'
);

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log('Event:', message);
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('WebSocket closed');
};
Stream real-time events from a running backtest via WebSocket. Events include progress updates, log messages, metrics, and state changes.

Path parameters

run_id
string
required
Unique identifier of the backtest run

Query parameters

api_key
string
API key for WebSocket authentication (alternative to header-based auth)
last_event_id
integer
Resume from events after this ID (for reconnection)

Authentication

WebSocket connections support three authentication methods:
  1. Query parameter: ?api_key=your-api-key
  2. Authorization header: Authorization: Bearer your-api-key
  3. Custom header: X-API-Key: your-api-key

Event types

The WebSocket emits events with the following structure:
event_id
integer
Unique sequential ID for this event
run_id
string
Backtest run identifier
type
string
Event typeValues: log, progress, metric, state
timestamp
datetime
When the event occurred
payload
object
Event-specific data
  • log events: {"message": "..."}
  • progress events: {"progress": 0.45}
  • metric events: {"name": "sharpe_ratio", "value": 1.23}
  • state events: {"state": "running", "previous_state": "queued"}
{
  "event_id": 42,
  "run_id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "progress",
  "timestamp": "2023-01-15T10:31:00.000Z",
  "payload": {
    "progress": 0.45
  }
}

Connection lifecycle

  1. Client connects with authentication credentials
  2. Server validates API key and checks if run exists
  3. Server sends any events after last_event_id (backlog replay)
  4. Server subscribes client to live events
  5. Client receives events as they occur
  6. Connection closes when:
    • Client disconnects
    • Authentication fails (policy violation)
    • Run not found
    • Server error

Error handling

WebSocket connections close with specific codes:
  • 1008 Policy Violation - Authentication failed or run not found
  • 1000 Normal Closure - Clean disconnect

Build docs developers (and LLMs) love