WebSocket Streaming Guide
Details
Docs navigation
- Getting started: Quickstart, Authentication, Rate limits, Errors and retries
- Guides: Symbol formats, Timestamps and time zones, Pagination, Split and dividend adjustments, WebSocket streaming (you are here), Dataset downloads, Excel and Google Sheets, Changelog
- API reference: Stock bars, Stock trades and quotes, Snapshots and movers, Tickers, exchanges, calendar, Splits and dividends, Fundamentals and SEC filings, Options chain and Greeks, Options EOD, bars, OI, Forex, Crypto, Crypto derivatives, Futures bars and continuous, Settlements and COT, Indices, Economic data, Technical indicators
- SDKs: Python, JavaScript
REST is for history; a WebSocket is for what is happening now. This guide shows how to open a real time market data WebSocket to marketdata.co, authenticate, subscribe to trades, quotes or bars, read the messages and recover from a dropped connection. It is for anyone building a live dashboard, an alerting script or a trading bot.
Early access. Streaming is planned for v1 and is not live yet. Which streams you can open depends on your plan: crypto and FX streams start on Pro ($79/mo), real-time SIP stock trades and quotes on Business ($249/mo).
Details
Connect and subscribe
1. Open a connection to the right cluster
| Cluster | URL | Symbols |
|---|---|---|
| Stocks | wss://stream.marketdata.co/v1/stocks |
AAPL, SPY |
| Options | wss://stream.marketdata.co/v1/options |
AAPL261218C00230000 |
| Forex | wss://stream.marketdata.co/v1/forex |
EURUSD |
| Crypto | wss://stream.marketdata.co/v1/crypto |
BTC-USDT |
| Futures | wss://stream.marketdata.co/v1/futures |
ESZ6 |
2. Authenticate in the first message
{"action": "auth", "key": "YOUR_API_KEY"}
The server answers with {"type": "status", "status": "authenticated"}. If you send anything else first, or the key is wrong, you get an error message and the socket closes.
3. Subscribe to channels
{"action": "subscribe", "channel": "trades", "symbols": ["BTC-USDT", "ETH-USDT"], "exchange": "binance"}
| Channel | What arrives | Fields |
|---|---|---|
trades |
Every trade | Same as the trades REST endpoint for that asset class |
quotes |
Top-of-book changes | bid_price, bid_size, ask_price, ask_size (stocks); bid, ask, mid (FX) |
bars |
One message per closed 1-minute bar | Same as REST bars |
liquidations |
Forced liquidations on perpetuals (crypto cluster) | side, price, size, notional_usd |
Unsubscribe with "action": "unsubscribe" and the same body.
4. Read messages
Each message is a JSON array of events, so one frame can carry many trades in a busy second. Every event has a type and the same field names you get from REST.
[
{"type": "trade", "symbol": "BTC-USDT", "exchange": "binance", "trade_id": "6809266910",
"timestamp": "2026-11-01T00:00:00.447286Z", "price": 77582.02, "size": 0.00105,
"notional": 81.46, "aggressor_side": "sell"}
]
That event mirrors the first row of our free BTC-USDT trades sample (Source: Binance).
5. A complete Python client
Example (run pip install websockets first):
import asyncio
import json
import os
import websockets
URL = "wss://stream.marketdata.co/v1/crypto"
async def run():
async for ws in websockets.connect(URL, ping_interval=20):
try:
await ws.send(json.dumps({"action": "auth", "key": os.environ["MARKETDATA_API_KEY"]}))
await ws.send(json.dumps({"action": "subscribe", "channel": "trades",
"symbols": ["BTC-USDT"], "exchange": "binance"}))
async for frame in ws:
for event in json.loads(frame):
if event["type"] == "trade":
print(event["timestamp"], event["price"], event["size"])
elif event["type"] == "error":
print("error:", event["code"], event.get("message"))
except websockets.ConnectionClosed:
continue # the outer loop reconnects with backoff
asyncio.run(run())
websockets.connect used as an async iterator reconnects with exponential backoff on its own. On every reconnect you must authenticate and subscribe again.
Watch out
Notes and gotchas
- Subscriptions do not survive a reconnect. Keep your own list and replay it.
- You will miss events while disconnected. To fill the gap, call the REST endpoint for the window between your last
timestampand the reconnect. - The server sends a ping every 20 seconds. Most libraries answer automatically; if yours does not, the connection drops after about a minute.
- If your client reads too slowly, the server buffers for a while and then closes the socket with code
slow_consumer. Do heavy work on another task or thread, not inside the read loop. - Stock and options streams outside the regular session only carry data if your plan includes extended hours.
- Real-time US stock and options data is licensed per user. On personal plans, one key means one person and one live connection per cluster.
- Opening a connection counts as one REST request for rate limit purposes. Messages do not.
Keep reading
Next steps
Details
Was this page useful?
[Yes] [No]
Need a channel we don't list? Tell us on the custom data form.