WebSocket Messages

The Trading API uses WebSocket connections for real-time event streaming. This reference documents all message types exchanged between your strategy and the Trading API.

Message Format

All messages use JSON with an internally-tagged format. The type field identifies the message type:

{"type": "ping", "timestamp": "2025-01-15T10:30:00Z"}
{"type": "order", "event": "ORDER_FILLED", "order": {...}}

Client to Server Messages

Your strategy sends these messages to the Trading API.

Pong

Response to a server ping heartbeat. Send this to keep the connection alive.

{
  "type": "pong"
}

EventAck

Acknowledge processed events. Required for backtest mode (Tektii Engine — controls time simulation), optional when using the Trading Gateway (paper or live).

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

Server to Client Messages

The Trading API sends these messages to your strategy.

Ping

Server heartbeat. Respond with a pong message to keep the connection alive.

{
  "type": "ping",
  "timestamp": "2025-01-15T10:30:00Z"
}

Order Events

Order state changes. Sent when orders are created, modified, filled, cancelled, or rejected.

FieldTypeDescription
typestringAlways "order"
eventOrderEventTypeType of order event
orderOrderCurrent state of the order
timestampdatetimeEvent timestamp
parent_order_idstring?Parent order ID for bracket/OCO child orders

OrderEventType values:

ValueDescription
ORDER_CREATEDNew order submitted
ORDER_MODIFIEDOrder parameters changed
ORDER_CANCELLEDOrder cancelled by user or system
ORDER_REJECTEDOrder rejected by provider
ORDER_FILLEDOrder completely filled
ORDER_PARTIALLY_FILLEDSome quantity filled
ORDER_EXPIREDOrder expired based on time_in_force
BRACKET_ORDER_CREATEDBracket order (with SL/TP) created
BRACKET_ORDER_MODIFIEDBracket order modified
{
  "type": "order",
  "event": "ORDER_FILLED",
  "order": {
    "id": "ord_abc123",
    "symbol": "AAPL",
    "side": "BUY",
    "order_type": "MARKET",
    "quantity": "100",
    "filled_quantity": "100",
    "remaining_quantity": "0",
    "average_fill_price": "150.25",
    "status": "FILLED",
    "time_in_force": "GTC",
    "created_at": "2025-01-15T10:30:00Z",
    "updated_at": "2025-01-15T10:30:01Z"
  },
  "timestamp": "2025-01-15T10:30:01Z"
}

Position Events

Position state changes. Sent when positions are opened, modified, or closed.

FieldTypeDescription
typestringAlways "position"
eventPositionEventTypeType of position event
positionPositionCurrent state of the position
timestampdatetimeEvent timestamp

PositionEventType values:

ValueDescription
POSITION_OPENEDNew position opened
POSITION_MODIFIEDPosition quantity or P&L changed
POSITION_CLOSEDPosition fully closed
{
  "type": "position",
  "event": "POSITION_OPENED",
  "position": {
    "id": "pos_xyz789",
    "symbol": "AAPL",
    "side": "LONG",
    "quantity": "100",
    "average_entry_price": "150.25",
    "current_price": "150.50",
    "unrealized_pnl": "25.00",
    "realized_pnl": "0",
    "opened_at": "2025-01-15T10:30:01Z",
    "updated_at": "2025-01-15T10:30:01Z"
  },
  "timestamp": "2025-01-15T10:30:01Z"
}

Account Events

Account balance and margin changes.

FieldTypeDescription
typestringAlways "account"
eventAccountEventTypeType of account event
accountAccountCurrent account state
timestampdatetimeEvent timestamp

AccountEventType values:

ValueDescription
BALANCE_UPDATEDCash balance changed (deposit, withdrawal, trade)
MARGIN_WARNINGApproaching margin limit
MARGIN_CALLMargin limit exceeded, liquidation may occur
{
  "type": "account",
  "event": "BALANCE_UPDATED",
  "account": {
    "balance": "10000.00",
    "equity": "10500.00",
    "margin_used": "2000.00",
    "margin_available": "8500.00",
    "unrealized_pnl": "500.00",
    "currency": "USD"
  },
  "timestamp": "2025-01-15T10:30:01Z"
}

Candle Events

OHLCV bar/candlestick data for market analysis.

FieldTypeDescription
typestringAlways "candle"
barBarThe bar data (includes symbol, provider, timeframe, OHLCV)
timestampdatetimeEvent timestamp (when event was emitted)
{
  "type": "candle",
  "bar": {
    "symbol": "AAPL",
    "provider": "alpaca",
    "timeframe": "1h",
    "timestamp": "2025-01-15T10:00:00Z",
    "open": "150.00",
    "high": "151.50",
    "low": "149.75",
    "close": "151.25",
    "volume": "1234567"
  },
  "timestamp": "2025-01-15T11:00:00Z"
}

Quote Events

Real-time bid/ask price updates.

FieldTypeDescription
typestringAlways "quote"
quoteQuoteThe quote data (includes symbol, provider, bid/ask/last)
timestampdatetimeEvent timestamp (when event was emitted)
{
  "type": "quote",
  "quote": {
    "symbol": "AAPL",
    "provider": "alpaca",
    "bid": "150.20",
    "bid_size": "100",
    "ask": "150.25",
    "ask_size": "200",
    "last": "150.22",
    "timestamp": "2025-01-15T10:30:00.123Z"
  },
  "timestamp": "2025-01-15T10:30:00.123Z"
}

Trade Events

Individual trade/fill execution notifications.

FieldTypeDescription
typestringAlways "trade"
eventTradeEventTypeType of trade event
tradeTradeThe executed trade
timestampdatetimeEvent timestamp

TradeEventType values:

ValueDescription
TRADE_FILLEDTrade execution completed
{
  "type": "trade",
  "event": "TRADE_FILLED",
  "trade": {
    "id": "trd_def456",
    "order_id": "ord_abc123",
    "symbol": "AAPL",
    "side": "BUY",
    "quantity": "100",
    "price": "150.25",
    "commission": "0.50",
    "commission_currency": "USD",
    "is_maker": false,
    "timestamp": "2025-01-15T10:30:01Z"
  },
  "timestamp": "2025-01-15T10:30:01Z"
}

Connection Events

Connection state changes with the Gateway or its upstream broker.

FieldTypeDescription
typestringAlways "connection"
eventConnectionEventTypeType of connection event
brokerstring?Upstream broker/provider identifier (e.g. "alpaca-paper"). Present on BROKER_* variants.
errorstring?Error message when the event indicates a failure or unexpected disconnect
gap_duration_msinteger?Outage duration in milliseconds. Present on BROKER_RECONNECTED.
timestampdatetimeEvent timestamp (ISO 8601 UTC)

ConnectionEventType values:

ValueDescription
CONNECTEDStrategy successfully connected to the Gateway
DISCONNECTINGGateway connection is being closed
RECONNECTINGAttempting to reconnect after connection loss
BROKER_DISCONNECTEDUpstream broker link dropped
BROKER_RECONNECTEDUpstream broker link restored after an outage; gap_duration_ms reports the gap
BROKER_CONNECTION_FAILEDInitial broker connect failed, or a reconnect attempt failed terminally
{
  "type": "connection",
  "event": "CONNECTED",
  "timestamp": "2025-01-15T10:30:00Z"
}
{
  "type": "connection",
  "event": "BROKER_RECONNECTED",
  "broker": "alpaca-paper",
  "gap_duration_ms": 4200,
  "timestamp": "2025-01-15T10:31:04Z"
}

Rate Limit Events

Notifications about API rate limits.

FieldTypeDescription
typestringAlways "rate_limit"
eventRateLimitEventTypeType of rate limit event
requests_remainingintegerRequests remaining in current window
reset_atdatetimeWhen the rate limit window resets
timestampdatetimeEvent timestamp

RateLimitEventType values:

ValueDescription
RATE_LIMIT_WARNINGApproaching rate limit
RATE_LIMIT_HITRate limit exceeded, requests will be rejected
{
  "type": "rate_limit",
  "event": "RATE_LIMIT_WARNING",
  "requests_remaining": 10,
  "reset_at": "2025-01-15T10:31:00Z",
  "timestamp": "2025-01-15T10:30:55Z"
}

Data Staleness Events

Emitted when the Gateway detects that upstream market-data freshness for one or more symbols has crossed a threshold. Useful for pausing or resuming trading logic that depends on live quotes.

FieldTypeDescription
typestringAlways "data_staleness"
eventDataStalenessEventTypeSTALE when data goes stale, FRESH when it recovers
symbolsstring[]Affected symbols
stale_sincedatetime?Timestamp (ISO 8601 UTC) when data first went stale. Present on STALE.
brokerstring?Upstream broker/provider identifier, when the staleness is scoped to a specific provider
timestampdatetimeEvent timestamp (ISO 8601 UTC)

DataStalenessEventType values:

ValueDescription
STALEUpstream data freshness fell below the configured threshold
FRESHUpstream data freshness has recovered
{
  "type": "data_staleness",
  "event": "STALE",
  "symbols": ["AAPL", "MSFT"],
  "stale_since": "2025-01-15T10:30:00Z",
  "broker": "alpaca-paper",
  "timestamp": "2025-01-15T10:30:05Z"
}
{
  "type": "data_staleness",
  "event": "FRESH",
  "symbols": ["AAPL", "MSFT"],
  "broker": "alpaca-paper",
  "timestamp": "2025-01-15T10:31:12Z"
}

Error Events

Error notifications from the server.

FieldTypeDescription
typestringAlways "error"
codeWsErrorCodeError code
messagestringHuman-readable error message
detailsany?Additional error details
timestampdatetimeEvent timestamp

WsErrorCode values:

ValueDescription
INVALID_MESSAGEMalformed message received
INTERNAL_ERRORInternal server error
POSITION_UNPROTECTEDA position is open without its configured bracket protection (stop-loss or take-profit) attached
LIQUIDATIONPosition was forcibly liquidated by the broker or risk engine
OCO_DOUBLE_EXITBoth legs of an OCO group fired before the cancel for the second leg reached the broker
{
  "type": "error",
  "code": "INVALID_MESSAGE",
  "message": "Failed to parse message: unexpected token at position 15",
  "timestamp": "2025-01-15T10:30:00Z"
}

Event Subscription

Event subscriptions are configured at startup via environment variables, not through WebSocket messages. Configure the SUBSCRIPTIONS environment variable to specify which events your strategy receives.

Related Documentation