Resources/Both venues·Realtime data

Prediction Market WebSocket API: Reconstruct Live Books Safely

A socket connection is easy. Maintaining a correct book through seeds, deltas, reconnects and venue-specific cadence is the actual engineering work.

By DepthFeed··10 min read

A prediction market WebSocket client needs a complete initial book, deterministic update ordering, source and receive timestamps, heartbeat handling and a recovery path after any gap. Polymarket can be captured from event-driven CLOB updates; Kalshi data may arrive through a different venue mechanism. A normalized downstream frame is useful only when it preserves those source differences instead of pretending every venue has the same transport.

Streaming checklist

Design for reconnects before consuming the first frame

Inspect the message contract, then implement seed, delta, sequence, staleness and resubscription handling. A connected socket is not proof of a correct local book.

{"op":"subscribe","channels":["book:polymarket:btc:<market_id>","price:btc"]}
Seed
replace local state
Delta
mutate known state
Gap
discard and recover

The minimum correct state machine

  • Resolve the stable market and outcome identifiers before subscribing.
  • Load or receive a complete book seed before applying incremental changes.
  • Apply updates in the documented source order and reject stale state.
  • Track heartbeat or last-message time independently for every connection.
  • On a sequence gap or uncertain reconnect, discard the local book and reseed.
  • Publish source time, receive time and a clear snapshot-versus-delta flag downstream.

Snapshot and delta are not interchangeable

A snapshot replaces state; a delta mutates it. Treating one as the other produces a book that can look plausible while retaining deleted levels or dropping unchanged size. Write explicit tests for level insertion, size replacement, deletion and crossed-book rejection.

Downstream consumers should not need to guess whether they received a complete ladder. Include a message type or serve normalized complete-book frames when simplicity is worth the additional bandwidth.

Venue-aware normalization

DepthFeed captures Polymarket from the CLOB stream and records normalized observations. Kalshi sports and crypto books follow documented venue-specific collection paths, including adaptive public REST where applicable. The downstream schema can remain consistent while metadata identifies how and when each source was observed.

For paid plans, DepthFeed's WebSocket serves normalized live book channels with plan-specific connection and subscription limits. Historical REST queries use the same price-size shape, which makes it possible to reuse parsing and fill logic across live monitoring and replay.

Production failure tests

FailureExpected behaviorUnsafe behavior
Connection dropsReconnect, reseed, resume from known stateContinue mutating the stale local book
Duplicate updateIdempotent handling or source-order checkDouble the resting size
Out-of-order updateReject or rebuildApply by arrival order without evidence
Slow consumerBackpressure, coalescing or disconnect policyUnbounded memory growth
No recent updateExpose freshness by marketReport the last price as live

A practical WebSocket message contract

Every downstream message should identify venue, market, outcome or token, message type, source timestamp when supplied, receive timestamp, and whether the payload is a full ladder or a delta. If the service emits complete normalized books, price and size arrays must be aligned and side ordering must be documented.

Add a schema version before the first public consumer depends on the stream. Version changes should be additive where possible, announced in advance and testable against recorded fixtures. A live client should reject an unknown breaking version rather than deserialize it into plausible but wrong fields.

Backpressure and slow consumers

A prediction-market stream can burst when many levels change or several markets move together. Bound every per-connection queue. Decide whether to coalesce complete-book frames, drop an explicitly disposable update type, or disconnect a consumer that cannot keep up. Never allow one slow subscriber to grow memory without limit.

Complete-book frames can often be coalesced safely because only the newest complete state is required for monitoring. Ordered deltas generally cannot be dropped without invalidating reconstruction. The stream contract should make that distinction clear so operators can choose throughput without corrupting state.

Reconnect, replay and gap semantics

A reconnect is not evidence that no updates were missed. If the source or provider offers a resume cursor, validate its retention and failure behavior. Otherwise, request a new snapshot and declare the period between last trusted state and reseed as unknown.

Historical storage closes a different gap: it allows deterministic replay after the fact. Persist the state or raw events required to reproduce each observation, then test the live parser against the same fixtures used by the historical loader. Shared fixtures prevent live and backtest code from interpreting the same ladder differently.

WebSocket monitoring metrics

MetricWhy it mattersAlert example
Connection stateDetects total feed lossDisconnected beyond retry budget
Last receive ageExposes stale marketsNo frame inside the market-specific threshold
Source-to-receive deltaSurfaces transport or processing changesPercentile shift from measured baseline
Reseed countShows gaps or unstable connectionsRepeated reseeds for one channel
Queue depthDetects slow consumersSustained growth near the bound
Invalid book countCatches parser or source anomaliesCrossed, unsorted or mismatched ladders
Messages by typeMakes silent schema changes visibleUnknown or missing expected type

Security and operational controls

  • Authenticate before accepting subscriptions and enforce plan limits server-side.
  • Authorize every requested market or wildcard rather than trusting client-side controls.
  • Rate-limit connect, subscribe and unsubscribe operations separately from data delivery.
  • Rotate API keys without requiring a code change and never place secrets in a browser bundle.
  • Use heartbeat and idle timeouts to clean up dead connections and abandoned subscriptions.
  • Log connection identifiers and subscription changes without logging credentials.
  • Test graceful degradation when an upstream venue is unavailable or rate-limited.

Reference client implementation order

Build the client as a small state machine rather than a collection of callbacks. Connect and authenticate, resolve the subscription acknowledgement, receive a complete seed, validate it, then enter the update loop. Only publish a local book after the seed and every applied mutation pass invariants.

On each frame, validate the schema version, channel and identifier before touching state. Record the receive time immediately. Apply the message according to its declared type, then verify price bounds, side ordering and price-size lengths. If any required invariant fails, stop publishing that market and reseed it.

On shutdown or disconnect, persist the last trusted cursor only if the provider explicitly supports replay from it. Otherwise discard the mutable state. The next session starts from a new complete seed. This conservative rule is cheaper than debugging a quietly corrupted ladder downstream.

DepthFeed live subscription contractshell
wscat -c "wss://api.depthfeed.com/v3/stream?api_key=df_your_key"

> {"op":"subscribe","channels":["book:polymarket:btc:<market_id>","price:btc"]}
< {"op":"subscribed","channels":["book:polymarket:btc:<market_id>","price:btc"],"active":2}

# After any disconnect: reconnect with exponential backoff,
# re-send subscriptions, and wait for a new complete book.

Interpret latency claims correctly

A latency number is incomplete without start point, end point, percentile, sample period, geography, message type and market set. Source-event to provider-receive, provider-receive to client-receive and end-to-end venue-to-screen latency are different measurements. A median also says nothing about the tail a risk monitor may care about.

Measure from your own infrastructure with synchronized clocks and report at least a median and a high percentile. Segment by venue and channel because an event-driven source and a polled source have different timing semantics. When the upstream does not provide a trustworthy event timestamp, label the measurement as observation or delivery latency rather than implying exchange-origin timing.

Key takeaways

  • 01A complete seed must exist before deltas can form a trustworthy book.
  • 02Reconnect uncertainty should trigger a reseed, not optimistic continuation.
  • 03Source time and receive time answer different latency questions.
  • 04Normalization should preserve venue-specific capture metadata.
  • 05The safest live and historical APIs share one explicit ladder shape.

Use one normalized live frame while keeping source method and timestamps auditable. Free Explorer tier, no card.

View WebSocket channelsView pricing

Questions, answered.

Polymarket publishes live CLOB market-data interfaces. Use the current official documentation for channel and message details, and reseed after any update gap.

Start backtesting Polymarket & Kalshi on real depth.

Free to start, no card. Upgrade when your strategy is ready for the full book.

Start free