# 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.

Source: https://learn.tradelabsai.com/programming/websocket-market-data-streams/  
Track: Programming and Data · Level: Intermediate · Updated: 2026-10-03  
Publisher: TradeLabs AI (https://tradelabsai.com). Education, not financial advice.  
Cite as: TradeLabs Learn, "WebSocket Market Data Streams", https://learn.tradelabsai.com/programming/websocket-market-data-streams/

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](https://tradelabsai.com). 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

| Channel | Contents | Lesson |
|---|---|---|
| Trades | Each executed trade: price, size, time, side | [Tick Data and OHLCV Data](https://learn.tradelabsai.com/programming/tick-data-and-ohlcv-data/) |
| Quotes (top of book) | Best bid and ask with sizes | [Bid-Ask Spread](https://learn.tradelabsai.com/markets/bid-ask-spread/) |
| Order book | Depth updates at many price levels | [Order Book Feeds: Snapshots and Incremental Updates](https://learn.tradelabsai.com/programming/order-book-feeds/) |
| Candles | Bars that update as they form | [How to Read Candlesticks](https://learn.tradelabsai.com/candlesticks/how-to-read-candlesticks/) |
| User data | Your orders, fills and balance changes | [Working With Exchange and Broker APIs](https://learn.tradelabsai.com/programming/trading-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.

```python
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](https://learn.tradelabsai.com/programming/sequence-numbers/).

**Example: Rebuilding an order book after a gap**
A bot keeps a local order book from depth updates. It receives update 10,452 followed by 10,455, so updates 10,453 and 10,454 were lost. Applying 10,455 to a book missing two changes could leave stale price levels that no longer exist, making the bot believe there is liquidity at a price where there is none. The correct response: stop using the book, request a new snapshot through REST, buffer incoming updates, then apply only buffered updates with IDs after the snapshot's ID. See [Order Book Feeds: Snapshots and Incremental Updates](https://learn.tradelabsai.com/programming/order-book-feeds/).

## 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](https://learn.tradelabsai.com/programming/latency-measurement/) and [Message Queues](https://learn.tradelabsai.com/infrastructure/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](https://learn.tradelabsai.com/algo-trading/live-monitoring/).

## 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](https://learn.tradelabsai.com/programming/timestamps-and-time-zones/).
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](https://learn.tradelabsai.com/programming/sql-for-trading-data/).

## Continue learning

- Next lesson: [SQL for Trading Data](https://learn.tradelabsai.com/programming/sql-for-trading-data/)
- Previous lesson: [Working With Exchange and Broker APIs](https://learn.tradelabsai.com/programming/trading-apis/)
- Related: [Working With Exchange and Broker APIs](https://learn.tradelabsai.com/programming/trading-apis/): How trading APIs let programs get prices, place orders and read positions. Learn REST, WebSocket and FIX, authentication, rate limits and safe API key handling.
- Related: [Real-Time, Delayed and Historical Data](https://learn.tradelabsai.com/programming/real-time-data/): What real time market data really means, how it differs from delayed and snapshot data, where it comes from, what it costs and how to judge its quality.
- Related: [Order Book Feeds: Snapshots and Incremental Updates](https://learn.tradelabsai.com/programming/order-book-feeds/): How exchanges publish order book data as snapshots and incremental updates, and how to build and maintain an accurate local order book in code without errors.
- Related: [Sequence Numbers, Dropped Packets and Out-of-Order Messages](https://learn.tradelabsai.com/programming/sequence-numbers/): Sequence numbers let trading systems detect lost, duplicated or out of order messages. Learn how gap detection, recovery and duplicate handling work in practice.
- Related: [Monitoring Positions, P&L and Risk](https://learn.tradelabsai.com/algo-trading/live-monitoring/): Running algorithms need constant monitoring. Learn the key health, trading and risk metrics to track, how to design useful alerts and how to avoid alert fatigue.
