TradeLabs AILearn

WebSocket Market Data Streams

How WebSocket streams deliver live trades, quotes and order book updates. Learn subscriptions, heartbeats, reconnecting safely and handling gaps in Python.

Intermediate3 min readUpdated 3 Oct 2026
Markdown
Lesson 6 of 27

A WebSocket is a long lived connection between your program and a server that lets the server push data the moment it changes. For trading, this means live trades, quotes, order book changes and your own order updates arrive within milliseconds, without asking repeatedly. Most crypto exchanges and many brokers offer WebSocket feeds, and they power live charts, including the live charts on TradeLabs AI. Handling a stream correctly is harder than it looks: connections drop, messages arrive in bursts and gaps must be detected and repaired.

How a WebSocket feed works#

  1. Connect to the feed URL, often with authentication.
  2. Subscribe to channels, such as trades for BTCUSDT or level 2 for a stock.
  3. Receive messages continuously, usually as JSON.
  4. Respond to heartbeats or pings to keep the connection alive.
  5. Reconnect and resubscribe when the connection drops.

Common channel types#

ChannelContentsLesson
TradesEach executed trade: price, size, time, sideTick Data and OHLCV Data
Quotes (top of book)Best bid and ask with sizesBid-Ask Spread
Order bookDepth updates at many price levelsOrder Book Feeds: Snapshots and Incremental Updates
CandlesBars that update as they formHow to Read Candlesticks
User dataYour orders, fills and balance changesWorking With Exchange and Broker APIs

A minimal Python client#

This sketch uses the websockets library with asyncio. The URL and message format are placeholders; every venue documents its own.

import asyncio, json, websockets

URL = "wss://example-exchange.com/ws"

async def run():
    while True:
        try:
            async with websockets.connect(URL, ping_interval=20) as ws:
                await ws.send(json.dumps({"op": "subscribe", "channel": "trades", "symbol": "BTCUSDT"}))
                async for raw in ws:
                    msg = json.loads(raw)
                    handle(msg)
        except Exception as exc:
            print("disconnected:", exc)
            await asyncio.sleep(2)   # back off, then reconnect

def handle(msg):
    pass  # update bars, order book or signals here

asyncio.run(run())

The outer loop matters as much as the inner one: a stream that does not reconnect will eventually stop silently.

Detecting gaps#

When a connection drops, messages sent during the outage are lost. Many feeds include a sequence number or update ID on each message. If the next number is not the previous one plus one, you missed data. For trades, you may fetch the missing period from a REST endpoint. For order books, you usually discard the local book and rebuild it from a fresh snapshot. See Sequence Numbers, Dropped Packets and Out-of-Order Messages.

Handling bursts#

During fast markets, message rates can jump many times over. If processing each message takes longer than the gap between messages, a queue builds and your view of the market falls behind. Keep message handling light, move heavy work to another task or process and measure the delay between the exchange timestamp and your receive time. See Exchange vs Receive Timestamps and Latency Measurement and Message Queues.

Staleness and heartbeats#

A connection can stay open while data stops flowing. Track the time of the last message per symbol and alert or pause trading if it exceeds a threshold. Many venues send heartbeat messages for exactly this reason. See Monitoring Positions, P&L and Risk.

Common mistakes#

  1. No reconnect loop, so the bot silently stops receiving data.
  2. Ignoring sequence gaps, leaving an incorrect order book.
  3. Heavy processing in the receive loop, causing growing delays.
  4. Mixing exchange and local timestamps without noting which is which. See Timestamps, Time Zones and Daylight Saving.
  5. Subscribing to too much, hitting connection or message limits.

Frequently asked questions#

What is a WebSocket in trading?#

A persistent connection that lets a broker or exchange push live market data and order updates to your program as they happen.

Why does my WebSocket keep disconnecting?#

Servers close idle or long running connections, networks drop and venues restart services. Respond to pings, reconnect automatically and resubscribe.

How do I know if I missed data?#

Check sequence numbers or update IDs on each message; a jump means messages were lost and the affected data must be repaired or rebuilt.

Next, learn to store and query trading data in SQL for Trading Data.

Check your understanding

3 quick questions on this lesson. Get them all right to finish it.

Turn on JavaScript to take the quiz.

Finished this lesson?Sign in to save your progress across devices.
Next lessonSQL for Trading DataLearn the SQL queries traders use most: filtering bars, aggregating trades into candles, joining fills to orders, window functions for returns and daily P&L.

Mentioned in