Connection Guide

This guide explains how to establish a connection between your strategy and the Backtest Engine or Trading Gateway, configure market data subscriptions, and handle the event stream.

Connection Endpoints

Your strategy connects via two protocols on the Engine or Gateway:

RuntimeProtocolPortURL
Backtest EngineWebSocket8081ws://localhost:8081
Backtest EngineREST8080http://localhost:8080
Trading GatewayWebSocket8080ws://localhost:8080/v1/ws
Trading GatewayREST8080http://localhost:8080

In production, these endpoints are provided via environment variables or configuration.

Host and Port Configuration

Configure your strategy using environment variables:

# Backtest Engine
ENGINE_WS_URL=ws://engine.example.com:8081
ENGINE_REST_URL=http://engine.example.com:8080

# Trading Gateway
GATEWAY_URL=http://gateway.example.com:8080

Or use default localhost ports for local development.

Authentication

Authentication is handled at the runtime level, not in your strategy. The Engine or Gateway authenticates with the trading provider using credentials configured at startup.

Your strategy connects without additional auth headers. When connecting to the Trading Gateway, network-level security (VPC, service mesh) protects the endpoints.

Establishing a Connection

WebSocket Handshake

  1. Open a WebSocket connection to the Engine or Gateway
  2. Wait for the CONNECTED connection event
  3. Begin receiving market data events
import websockets
import json

async def connect():
    async with websockets.connect("ws://localhost:8081") as ws:
        # Wait for connection confirmation
        msg = await ws.recv()
        event = json.loads(msg)

        if event["type"] == "connection" and event["event"] == "CONNECTED":
            print("Connected to server")

        # Start receiving events
        async for message in ws:
            handle_event(json.loads(message))

Connection Events

The server sends connection status events:

EventDescription
CONNECTEDSuccessfully connected to provider
DISCONNECTINGConnection closing gracefully
RECONNECTINGAttempting to reconnect after failure

Event Subscription

Configuring Subscriptions

Event subscriptions are configured via environment variables when starting your strategy container, not via WebSocket messages.

# Subscribe to specific symbols and data types
SUBSCRIPTIONS=S:AAPL:candle,S:AAPL:quote,C:BTCUSD:candle

Subscription format: {symbol}:{event_type}

Event TypeDescription
candleOHLCV bar data at configured timeframe
quoteBid/ask/last price updates

Symbol Format

Symbols include an asset class prefix:

  • S:AAPL - Stock (Apple)
  • C:BTCUSD - Crypto (Bitcoin/USD)

Example Subscriptions

# Single instrument
SUBSCRIPTIONS=S:AAPL:candle

# Multiple instruments
SUBSCRIPTIONS=S:AAPL:candle,S:MSFT:candle,S:GOOGL:candle

# Multiple event types per instrument
SUBSCRIPTIONS=S:AAPL:candle,S:AAPL:quote

Handling Events

Message Format

All WebSocket messages use JSON with a "type" field for routing:

{"type": "candle", "bar": {...}, "timestamp": "2025-01-01T00:00:00Z"}
{"type": "quote", "quote": {...}, "timestamp": "2025-01-01T00:00:00Z"}
{"type": "order", "event": "ORDER_FILLED", "order": {...}}
{"type": "ping", "timestamp": "2025-01-01T00:00:00Z"}

Event Types

TypeDirectionDescription
candleServer → ClientOHLCV bar data
quoteServer → ClientBid/ask/last price
orderServer → ClientOrder state changes
positionServer → ClientPosition state changes
accountServer → ClientAccount state changes
tradeServer → ClientTrade execution
connectionServer → ClientConnection status
rate_limitServer → ClientRate limit warnings
errorServer → ClientError notifications
pingServer → ClientHeartbeat ping
pongClient → ServerHeartbeat response
event_ackClient → ServerEvent acknowledgment

Ping/Pong Heartbeat

The server sends periodic ping messages. Respond with pong to maintain the connection:

// Server sends
{"type": "ping", "timestamp": "2025-01-01T00:00:00Z"}

// Client responds
{"type": "pong"}

Event Acknowledgment

Backtest Mode (Required)

In backtest mode, time simulation is controlled by your strategy. After processing a batch of events, send an acknowledgment to advance time:

{
  "type": "event_ack",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "events_processed": ["evt_123", "evt_124"],
  "timestamp": 1700000000000
}
FieldTypeDescription
correlation_idstringUnique ID for this acknowledgment
events_processedstring[]List of event IDs that were processed
timestampnumberUnix timestamp (ms) when events were processed

Without acknowledgments, the backtest engine will not advance time.

Trading Gateway Mode (Optional)

When using the Trading Gateway (paper or live mode), acknowledgments are informational only. The market continues regardless of whether you acknowledge events. However, sending them helps with debugging and monitoring.

Error Handling

The server sends error events when problems occur:

{
  "type": "error",
  "code": "INVALID_ORDER",
  "message": "Insufficient buying power",
  "timestamp": "2025-01-01T00:00:00Z"
}

Handle errors gracefully and implement reconnection logic for connection failures.

Next Steps

  • Review the Concepts documentation for an overview of the unified interface