Event Types

This reference documents all WebSocket event types in the Trading API, including market data events, order/position updates, and client messages.

Event Message Structure

All events are delivered via WebSocket with a consistent structure:

{
  "type": "event_type",
  "timestamp": "2025-01-15T10:30:00Z",
  ...event-specific fields
}

The type field identifies the event category. Each event type has specific additional fields documented below.

Format Conventions

A handful of encoding rules apply uniformly across every event payload.

Prices and monetary values

Prices, quantities, balances, and P&L are serialized as JSON strings (e.g., "150.25", "1.0846"). The Gateway represents these as arbitrary-precision Decimal values internally; sending them as strings preserves every digit across the wire. Parse them into a decimal type (Python decimal.Decimal, Java BigDecimal, Rust rust_decimal::Decimal, Go shopspring/decimal.Decimal) rather than float or number — JSON float parsers will silently round values like 0.1 + 0.2, and accumulated rounding across fills and P&L updates can drift by pennies over a trading session.

Timestamps

Most timestamps are ISO-8601 UTC strings with optional fractional seconds:

"2025-01-15T10:30:00Z"
"2025-01-15T10:30:00.125Z"

The one exception is event_ack.timestamp, which is a Unix millisecond integer (e.g., 1700000000000). The Gateway uses this format for backtest-engine time advancement, where an integer is cheaper to compare than a parsed date. Every other timestamp — on events, on quotes, on orders — is the ISO-8601 form.

Market Data Events

Candle Event

Delivers OHLCV bar data for subscribed instruments.

Type: candle

FieldTypeDescription
typestringAlways "candle"
barBarThe bar data
timestampdatetimeEvent timestamp (when event was emitted)

Bar Schema

FieldTypeDescription
symbolstringSymbol in canonical format (e.g., "EUR/USD", "AAPL")
providerstringData source provider (e.g., "alpaca", "binance")
timeframeTimeframeBar timeframe
timestampdatetimeBar start timestamp
openstringOpening price
highstringHighest price during the period
lowstringLowest price during the period
closestringClosing price
volumestringTrading volume during the period

Timeframe Enum

ValueDescription
1m1 minute
2m2 minutes
5m5 minutes
10m10 minutes
15m15 minutes
30m30 minutes
1h1 hour
2h2 hours
4h4 hours
12h12 hours
1d1 day
1w1 week

Example

{
  "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": "1500000"
  },
  "timestamp": "2025-01-15T11:00:00Z"
}

Quote Event

Delivers real-time bid/ask quotes.

Type: quote

FieldTypeDescription
typestringAlways "quote"
quoteQuoteThe quote data
timestampdatetimeEvent timestamp

Quote Schema

FieldTypeDescription
symbolstringSymbol in canonical format
providerstringData source provider
bidstringBest bid price (highest buy offer)
bid_sizestring?Quantity available at bid price
askstringBest ask price (lowest sell offer)
ask_sizestring?Quantity available at ask price
laststringLast traded price
volumestring?Trading volume (if available)
timestampdatetimeQuote timestamp

Example

{
  "type": "quote",
  "quote": {
    "symbol": "EUR/USD",
    "provider": "alpaca",
    "bid": "1.0845",
    "bid_size": "100000",
    "ask": "1.0847",
    "ask_size": "100000",
    "last": "1.0846",
    "timestamp": "2025-01-15T10:30:00.123Z"
  },
  "timestamp": "2025-01-15T10:30:00.125Z"
}

Order Events

Delivers order state changes.

Type: order

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

OrderEventType Enum

ValueDescription
ORDER_CREATEDOrder has been created and submitted
ORDER_MODIFIEDOrder has been modified (price, quantity, etc.)
ORDER_CANCELLEDOrder has been cancelled
ORDER_REJECTEDOrder was rejected by the provider
ORDER_FILLEDOrder has been completely filled
ORDER_PARTIALLY_FILLEDOrder has been partially filled
ORDER_EXPIREDOrder has expired based on time_in_force
BRACKET_ORDER_CREATEDBracket order (with SL/TP) has been created
BRACKET_ORDER_MODIFIEDBracket order has been modified

Example

{
  "type": "order",
  "event": "ORDER_FILLED",
  "order": {
    "id": "ord_abc123",
    "symbol": "AAPL",
    "side": "BUY",
    "order_type": "LIMIT",
    "quantity": "100",
    "filled_quantity": "100",
    "remaining_quantity": "0",
    "average_fill_price": "150.25",
    "status": "FILLED",
    "time_in_force": "GTC",
    "limit_price": "150.50",
    "created_at": "2025-01-15T10:30:00Z",
    "updated_at": "2025-01-15T10:30:05Z"
  },
  "timestamp": "2025-01-15T10:30:05Z"
}

Position Events

Delivers position state changes.

Type: position

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

PositionEventType Enum

ValueDescription
POSITION_OPENEDNew position has been opened
POSITION_MODIFIEDPosition has been modified (partial close, averaging)
POSITION_CLOSEDPosition has been fully closed

Example

{
  "type": "position",
  "event": "POSITION_OPENED",
  "position": {
    "id": "pos_xyz789",
    "symbol": "BTC/USD",
    "side": "LONG",
    "quantity": "0.5",
    "average_entry_price": "42000.00",
    "current_price": "42100.00",
    "unrealized_pnl": "50.00",
    "realized_pnl": "0.00",
    "margin_mode": "ISOLATED",
    "leverage": "10",
    "liquidation_price": "38000.00",
    "opened_at": "2025-01-15T10:30:00Z",
    "updated_at": "2025-01-15T10:30:00Z"
  },
  "timestamp": "2025-01-15T10:30:00Z"
}

margin_mode, leverage, and liquidation_price are optional. They are populated for leveraged positions (typically crypto and futures) and omitted for cash equities. See Position Types for the full schema and the MarginMode enum.

Account Events

Delivers account state changes.

Type: account

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

AccountEventType Enum

ValueDescription
BALANCE_UPDATEDAccount balance has changed
MARGIN_WARNINGMargin utilization approaching limit
MARGIN_CALLMargin call triggered - reduce positions or add funds

Example

{
  "type": "account",
  "event": "BALANCE_UPDATED",
  "account": {
    "balance": "10000.00",
    "equity": "10250.00",
    "margin_used": "1500.00",
    "margin_available": "8500.00",
    "unrealized_pnl": "250.00",
    "currency": "USD"
  },
  "timestamp": "2025-01-15T10:30:05Z"
}

Trade Events

Delivers individual trade/fill records.

Type: trade

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

TradeEventType Enum

ValueDescription
TRADE_FILLEDA trade has been executed

Trade Schema

FieldTypeDescription
idstringUnique trade identifier
order_idstringOrder ID this trade belongs to
symbolstringSymbol traded
sideSideTrade side (BUY or SELL)
quantitystringFill quantity in base units
pricestringFill price
commissionstringCommission/fee amount
commission_currencystringCurrency of the commission
is_makerboolean?Whether this was a maker trade
timestampdatetimeTrade execution timestamp

Example

{
  "type": "trade",
  "event": "TRADE_FILLED",
  "trade": {
    "id": "trd_123456",
    "order_id": "ord_abc123",
    "symbol": "AAPL",
    "side": "BUY",
    "quantity": "60",
    "price": "150.00",
    "commission": "0.50",
    "commission_currency": "USD",
    "is_maker": false,
    "timestamp": "2025-01-15T10:30:05Z"
  },
  "timestamp": "2025-01-15T10:30:05Z"
}

Connection Events

Delivers state changes for the strategy's link to the Gateway and for the Gateway's link to its upstream broker.

Type: connection

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

ConnectionEventType Enum

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

Example

{
  "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

Notifies about rate limiting status.

Type: rate_limit

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

RateLimitEventType Enum

ValueDescription
RATE_LIMIT_WARNINGApproaching rate limit threshold
RATE_LIMIT_HITRate limit exceeded, requests will be delayed

Example

{
  "type": "rate_limit",
  "event": "RATE_LIMIT_WARNING",
  "requests_remaining": 10,
  "reset_at": "2025-01-15T10:31:00Z",
  "timestamp": "2025-01-15T10:30:50Z"
}

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.

Type: data_staleness

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

DataStalenessEventType Enum

ValueDescription
STALEUpstream data freshness fell below the configured threshold
FRESHUpstream data freshness has recovered

Example

{
  "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

Delivers error notifications.

Type: error

FieldTypeDescription
typestringAlways "error"
codeWsErrorCodeError code
messagestringHuman-readable error message
detailsobject?Additional error context
timestampdatetimeEvent timestamp

WsErrorCode Enum

ValueDescription
INVALID_MESSAGEReceived message could not be parsed
INTERNAL_ERRORServer encountered an internal 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

Example

{
  "type": "error",
  "code": "INVALID_MESSAGE",
  "message": "Failed to parse order request: missing required field 'symbol'",
  "details": {
    "field": "symbol"
  },
  "timestamp": "2025-01-15T10:30:00Z"
}

Client Messages

Messages sent from your strategy to the server.

Ping/Pong (Heartbeat)

The server sends ping messages to check connection health. Your client must respond with pong.

Server sends:

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

Client responds:

{
  "type": "pong"
}

Event Acknowledgment

Strategies acknowledge received events by sending an event_ack frame.

Type: event_ack

FieldTypeDescription
typestringAlways "event_ack"
correlation_idstringCaller-chosen ID (typically a UUID) useful for correlating ACKs in logs
events_processedstring[]Informational — strings the strategy chose to record. The Gateway auto-correlates ACKs with outstanding events; it does not match entries in this array to any specific event. Common choices: the id values from orders/trades/positions the strategy handled, a strategy-generated correlation ID, or an empty array.
timestampintegerUnix timestamp (milliseconds) when the strategy finished processing

Mode-dependent behavior:

  • Simulation mode (backtest engine) — acknowledgment is required. After emitting an event, the engine stops advancing simulated time until it sees any event_ack frame from the strategy. The frame's arrival is what matters; the Gateway drains its full set of outstanding events on each ACK (auto-correlation). A strategy that never sends an event_ack stalls the backtest indefinitely.
  • Live or paper trading — acknowledgment is informational-only. The Gateway does not gate on ACKs. Strategies may send event_ack for telemetry or skip it entirely.

Example

{
  "type": "event_ack",
  "correlation_id": "550e8400-e29b-41d4-a716-446655440000",
  "events_processed": ["evt_123", "evt_124"],
  "timestamp": 1700000000000
}

Related Types