# WebSocket stream

Quotes of US stocks, ETFs and option contracts over one WebSocket, pushed as they change.

One WebSocket pushes real-time quotes of US stocks and ETFs, and of US stock, ETF and index option contracts with their implied volatility and Greeks, as they change. Messages cost no credits.

The stream is open to a key whose account reads real-time market prices on a paid plan, a test key with real time included. Any other key is told why in an `error` message, then the stream closes. To add real time, write to hello@gloom.sh.

## Connect

```text
wss://api.gloom.sh/v1/datasets/stream
```

Send the key in the handshake, as `Authorization: Bearer gds_...` or `X-API-Key`. A browser cannot set either header, so connect from your server. The stream answers `ready` with your limits, then takes these messages, each a JSON object:

```json
{"type": "subscribe", "symbols": ["AAPL", "SPY"], "options": ["AAPL261218C00200000", "SPXW261218C06900000", {"underlying": "SPY", "expiry": "2026-12-18"}, {"underlying": "^SPX", "expiry": "2026-12-18"}]}
{"type": "unsubscribe", "symbols": ["SPY"], "options": [{"underlying": "SPY", "expiry": "2026-12-18"}]}
{"type": "ping"}
```

- `symbols`: US stocks and ETFs, such as `AAPL` or `BRK.B`.
- `options`: a contract by its OCC symbol, or every contract of an underlying's expiry as `{underlying, expiry}`: every strike, every root's contract at each, all the pages of `/v1/options/chains`. Contracts adjusted for a corporate action are not on the stream.
- Index options are: `^SPX` (roots SPX, SPXW and SPXO), `^XSP`, `^NDX` (NDX, NDXP), `^RUT` (RUT, RUTW) and `^VIX` (VIX, VIXW). Subscribe a contract by its own symbol (`SPXW261218C06900000`), or an expiry by the index, `{"underlying": "^SPX", "expiry": "2026-12-18"}`: its bare name (`SPX`) or a root (`SPXW`) reads as the index too, and the answer names it `^SPX`. On a date two roots share, such as a third Friday's SPX and SPXW, the expiry carries both roots' contract at each strike, each row naming its `root`.
- Each subscribe and unsubscribe is answered `subscribed` or `unsubscribed`, naming what it took, the count you hold and the whole chains among them. Up to 1,000 entries and 256 KB a message, 10 messages a second.

## Messages

```json
{"type": "quotes", "quotes": [{"symbol": "AAPL", "price": 231.42, "lastTradePrice": 231.42, "lastTradeTime": 1795448460123, "bid": 231.41, "bidSize": 3, "ask": 231.43, "askSize": 5, "volume": 18234511, "change": 1.12, "changePercent": 0.486, "previousClose": 230.3, "marketState": "REGULAR", "currency": "USD", "lastUpdated": 1795448460123, "asOf": "2026-11-23T15:41:00.123Z", "delayed": false, "stale": false}]}
{"type": "options", "options": [{"contractSymbol": "AAPL261218C00200000", "underlying": "AAPL", "expiry": "2026-12-18", "side": "call", "strike": 200, "root": "AAPL", "exerciseStyle": "american", "settlement": "physical", "multiplier": 100, "bid": 33.1, "ask": 33.45, "bidSize": 3, "askSize": 12, "bidExchange": "C", "askExchange": "X", "quoteCondition": "A", "lastPrice": 33.2, "lastSize": 2, "lastExchange": "C", "lastCondition": "I", "lastTradeTime": 1795448400120, "volume": 412, "openInterest": 15220, "openInterestAsOf": "2026-11-20", "impliedVolatility": 0.2731, "delta": 0.912, "gamma": 0.0061, "thetaPerDay": -0.0418, "vegaPerPoint": 0.0903, "rhoPerPoint": 0.142, "forward": null, "underlyingPrice": 231.42, "underlyingPriceTime": 1795448454000, "quoteTime": 1795448455000, "asOf": "2026-11-23T15:40:56.000Z", "delayed": false}]}
{"type": "heartbeat", "at": 1795448475000}
```

- `quotes` carries every stock update: last trade, bid and ask with their sizes, day volume, and the times in milliseconds. Stocks update as they trade and quote, in a frame at most every 100 ms.
- `options` carries a contract when one of its values changed: bid and ask with their sizes and exchanges, last trade with its size, exchange, condition and time in milliseconds, volume, open interest, `impliedVolatility` and the Greeks, the underlying price the chain is valued at, with its `root`, `exerciseStyle`, `settlement` and `multiplier`: the same fields, values, codes and nulls as `/v1/options/chains`. An index option row's `underlying` is the index (`^SPX`), its `underlyingPrice` the index level, which can be 15 minutes behind, and its `forward` the put-call parity forward of its root and expiry, read off the real-time quotes. Each chain is read about every 10 seconds, and a new subscription gets its rows at once, in messages of at most 250 rows: a whole chain's rows can take several.
- `heartbeat` comes every 15 seconds, with a WebSocket ping your client library answers by itself. A stream silent for longer has dropped: reconnect.
- `delayed: true` marks a value no real-time source had just then. `stale: true` marks a quote served from an older read while no fresh one was at hand.
- `error` names a `code` and keeps the stream open: `symbol_invalid`, `symbol_limit` and `chain_limit` list what was not subscribed in `rejected`, `not_found` a contract no chain lists (it is unsubscribed), `unavailable` a read that failed (the stream keeps trying), `invalid_message` and `rate_limited` a message it dropped.

## Limits

An account holds 500 symbols over 5 streams at once: a stock, a contract and a whole chain each count one, and at most 20 of them are whole chains. Past a limit, the subscribe gets `symbol_limit` or `chain_limit` for what did not fit, and a sixth stream is closed with `4029`. For more, write to hello@gloom.sh.

A stream counts until it closes. One whose client went away without a close is closed once it has answered no ping for about 40 seconds, and one whose server stopped no longer counts after 45 seconds: either way, its slot is free within a minute.

## Reconnect

A stream closes when the server restarts, with `1012`, and can drop like any connection. Reconnect and send your subscriptions again; nothing carries over. Stop only on a close that says the key cannot stream.

| Close code | Means | Then |
| --- | --- | --- |
| `1012` | The server is restarting | Reconnect at once |
| `1001` | Your client answered no ping for about 40 seconds (`ping_timeout`) | Reconnect |
| `1009` | A message over 256 KB (`message_too_large`) | Send smaller messages, then reconnect |
| `4001` | No key, or an invalid one (`missing_key`, `invalid_key`, `wrong_key`) | Fix the key |
| `4002` | No real-time access (`dataset_not_included`), or no plan | Do not retry |
| `4003` | The key or account is disabled | Do not retry |
| `4029`, `1013` | Too many streams open, or the stream could not open just now | Wait `retryAfter` seconds, then reconnect |
| Any other | The connection dropped | Reconnect, waiting a little longer each time |

Every minute the stream checks the key again, as a call would be: once it can no longer stream, it closes with one of the codes above.

```python
import asyncio, json, os, random
import websockets

SUBSCRIBE = {"type": "subscribe", "symbols": ["AAPL", "SPY"],
             "options": ["AAPL261218C00200000", {"underlying": "SPY", "expiry": "2026-12-18"}]}

async def stream():
    delay = 1
    while True:
        retry_after = None
        try:
            async with websockets.connect("wss://api.gloom.sh/v1/datasets/stream",
                    additional_headers={"Authorization": f"Bearer {os.environ['GLOOM_DATASETS_KEY']}"}) as ws:
                await ws.send(json.dumps(SUBSCRIBE))
                async for raw in ws:
                    message = json.loads(raw)
                    if message["type"] == "ready":
                        delay = 1
                    elif message["type"] == "quotes":
                        for quote in message["quotes"]:
                            print(quote["symbol"], quote["bid"], quote["ask"], quote["lastTradePrice"])
                    elif message["type"] == "options":
                        for row in message["options"]:
                            print(row["contractSymbol"], row["bid"], row["ask"], row["delta"])
                    elif message["type"] == "error":
                        retry_after = message.get("retryAfter")
                        print(message["code"], message["message"])
        except websockets.ConnectionClosed as closed:
            code = closed.rcvd.code if closed.rcvd else None
            if code in (4001, 4002, 4003):
                raise SystemExit(f"The key cannot stream: {closed.rcvd.reason}")
            if code == 1012:
                delay = 1
        except OSError:
            pass
        await asyncio.sleep(retry_after or delay * random.uniform(0.5, 1))
        delay = min(delay * 2, 30)

asyncio.run(stream())
```

The same in TypeScript, for Bun, or Node with the `ws` package:

```ts
const subscribe = { type: "subscribe", symbols: ["AAPL", "SPY"], options: ["AAPL261218C00200000"] }
let delay = 1_000

function connect() {
  const ws = new WebSocket("wss://api.gloom.sh/v1/datasets/stream", {
    headers: { Authorization: `Bearer ${process.env.GLOOM_DATASETS_KEY}` },
  })
  let retryAfter = 0
  ws.onopen = () => ws.send(JSON.stringify(subscribe))
  ws.onmessage = (event) => {
    const message = JSON.parse(String(event.data))
    if (message.type === "ready") delay = 1_000
    if (message.type === "quotes") for (const quote of message.quotes) console.log(quote.symbol, quote.bid, quote.ask)
    if (message.type === "options") for (const row of message.options) console.log(row.contractSymbol, row.delta)
    if (message.type === "error") retryAfter = (message.retryAfter ?? 0) * 1_000
  }
  ws.onclose = (event) => {
    if ([4001, 4002, 4003].includes(event.code)) return console.error("The key cannot stream:", event.reason)
    const wait = event.code === 1012 ? Math.random() * 1_000 : Math.max(retryAfter, delay * (0.5 + Math.random() / 2))
    delay = Math.min(delay * 2, 30_000)
    setTimeout(connect, wait)
  }
}

connect()
```

- [Previous Bulk delivery](https://gloom.sh/datasets/docs/bulk)
- [Next Paging](https://gloom.sh/datasets/docs/paging)
