# Real time (WebSocket)

A single WebSocket connection can carry several subscriptions. For each one, you first receive the current state (the snapshot), then every change, in order. After a disconnect, you resume exactly where you left off.

> The [SDKs](https://fathomcharts.com/docs/sdk.md) handle everything on this page for you: initial state, resuming, duplicates and reconnection. Read on if you are writing your own client, or to understand what happens under the hood.

## Connecting

```text
wss://stream.fathomcharts.com/v1
```

- **From a server**: add the `Authorization: Bearer <your key>` header when opening the connection. The `Bearer` scheme is required (a bare key is refused) and is case-insensitive.
- **From a browser**: open the connection without headers, then send a [stream token](https://fathomcharts.com/docs/authentication.md#browser-access) in an `auth` message, first, within 5 seconds.

The WebSocket connection always opens (`101` response) before authentication: a browser cannot read why an opening was refused. A refused key or token therefore closes the connection right after it opens, with code `4001` (see [Closing and reconnecting](#closing-and-reconnecting)).

Every message, in both directions, is a JSON object sent in a text frame, whose `t` field gives its type. A message you send is at most 64 KiB (65,536 bytes), and your client may send 20 messages per second on average (bursts of 100 allowed).

## Subscribing

```json
{
  "t": "subscribe",
  "sub": "bt",
  "instrument": "NQ.front",
  "indicator": "big-trades",
  "params": { "minimum": 30 },
  "mode": "live",
  "from": "live"
}
```

| Field        | Purpose                                                                                                                                                                                                                                                                                                   |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sub`        | Name you give the subscription (1 to 64 bytes in UTF-8: a letter without accent counts as one, an accented letter as two, an emoji as four), unique on the connection. Every message about it carries this name.                                                                                          |
| `instrument` | A specific contract (`NQZ6`) or the front-month contract (`NQ.front`). Full list: `GET /v1/instruments`.                                                                                                                                                                                                  |
| `indicator`  | The indicator’s id in the [catalog](https://fathomcharts.com/docs/indicators.md).                                                                                                                                                                                                                         |
| `params`     | The indicator’s parameters. Parameters you omit take the current [default values](https://fathomcharts.com/docs.md#default-values) of the instrument’s ticker, which are updated over time.                                                                                                               |
| `mode`       | `live` (default): objects in progress and completed. `confirmed`: completed objects only.                                                                                                                                                                                                                 |
| `from`       | `"live"` (default): from now on. `{"cursor": "…", "engine": "…"}`: [resume](#cursors-and-resuming) after a disconnect (`engine`, optional but recommended: the one of the subscription’s latest `subscribed`). `{"time": "…"}`: start from a [past point in time](#starting-in-the-past), in nanoseconds. |

Any other field is refused.

To stop: `{"t":"unsubscribe","sub":"bt"}`. No acknowledgement is sent: ignore any messages for that subscription still in flight. You can reuse the same `sub` right away: no message of the old subscription arrives after the `subscribed` of the new one. An `unsubscribe` whose `sub` names no active subscription (already closed by an `error`, or never opened) is ignored, without a response.

### Refusals and errors

The server checks the message, your rights and your quotas before sending `subscribed`: a refused subscription receives a single `error` message, with its `sub` if it could be read, and nothing else. The connection and your other subscriptions carry on unaffected.

One exception: a `subscribe` whose `sub` is already taken on the connection receives an `error` **without** `sub` (`sub <name> is already in use on this connection`). That `sub` designates the active subscription, which carries on unaffected: do not close it.

A `subscribe` or an `unsubscribe` the server cannot read, but whose `sub` it can read, receives an `INVALID_PARAMETERS` `error` **with** that `sub`. An `unsubscribe` with an unknown field is an example. If a subscription of that name is active, this error does not close it: it carries on unaffected.

```json
{"sub":"bt","t":"error","code":"INVALID_PARAMETERS","message":"params.minimum: must be >= 1"}
```

`INVALID_PARAMETERS` refusals carry a precise text, for example:

| `message`                                                                          | Cause                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message must be a JSON object`                                                    | The message is not a valid JSON object. This message has no `sub`.                                                                                                                                                                                                                                                                                                                                                                      |
| `` missing field `t` ``, `` unknown message type `x` ``                            | A missing `t` field or an unknown message type. This message has no `sub`.                                                                                                                                                                                                                                                                                                                                                              |
| `` missing field `sub` ``, `sub must be 1 to 64 bytes`                             | A missing, empty or too long `sub`. This message has no `sub`.                                                                                                                                                                                                                                                                                                                                                                          |
| `` unknown field `x` ``                                                            | An unknown field in the message (a typo in `mode` or `from`, for example).                                                                                                                                                                                                                                                                                                                                                              |
| `mode must be "live" or "confirmed"`                                               | Unknown `mode` value.                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `from must be "live", {"cursor":"…","engine":"…"} or {"time":"…"}`                 | A malformed `from`, or one holding both `cursor` and `time`.                                                                                                                                                                                                                                                                                                                                                                            |
| `from.engine must be a string`                                                     | `from.engine` is not a string.                                                                                                                                                                                                                                                                                                                                                                                                          |
| `from.time must be a string of Unix nanoseconds`                                   | `from.time` sent as a number rather than a string.                                                                                                                                                                                                                                                                                                                                                                                      |
| `from.cursor must be a string`                                                     | `from.cursor` is not a string.                                                                                                                                                                                                                                                                                                                                                                                                          |
| `from.cursor is not a cursor`                                                      | `from.cursor` is not a well-formed `<utcDay>.<rank>.<k>` cursor.                                                                                                                                                                                                                                                                                                                                                                        |
| `from.time must be Unix nanoseconds`                                               | `from.time` is not a number of nanoseconds (a value in seconds, milliseconds or microseconds, below 10¹⁸, for example).                                                                                                                                                                                                                                                                                                                 |
| `from.time is in the future`                                                       | `from.time` is later than now.                                                                                                                                                                                                                                                                                                                                                                                                          |
| `this stream is delayed by 600 s: from.time must be at least that far in the past` | Delayed data: `from.time` must be at least 10 minutes (the delay) in the past.                                                                                                                                                                                                                                                                                                                                                          |
| `sub <name> is already in use on this connection`                                  | The `sub` name is already taken on this connection. This message has no `sub`; the active subscription carries on.                                                                                                                                                                                                                                                                                                                      |
| `params must be an object`                                                         | `params` is not an object (`null` included). Left out, it takes the default values.                                                                                                                                                                                                                                                                                                                                                     |
| `params.<name>: …`                                                                 | Invalid indicator parameters: every faulty field, separated by `; `. Unknown fields come first, then the known fields (`params.colour: is not a parameter of this indicator; params.minimum: must be >= 1`). These are the same problems as over REST, where the field is written as a JSON Pointer (`/params/minimum must be >= 1`). Rules between fields are checked next (``params.maximum: must be 0 or at least `minimum` (50)``). |

The other refusals: an unknown instrument or indicator (`UNKNOWN_INSTRUMENT`, `UNKNOWN_INDICATOR`), a missing right (`FORBIDDEN`, for example a key restricted to other instruments, or `from.time` without rights to history or beyond their depth), a limit of your plan reached (`QUOTA_EXCEEDED`: number of subscriptions or [custom configurations](https://fathomcharts.com/docs/limits.md#how-limits-are-counted)).

An accepted subscription can still receive an `error`, which closes it:

- `NOT_COVERED`: the computation needs history the instrument does not have, for example a `from.time` before the start of the contract’s history (`the history of NQZ6 starts on <day>: <day> is before it`);
- `QUOTA_EXCEEDED`: your compute budget does not cover the part served from history. This applies to a `from: {"time": …}` subscription, and to a resume caught up from history;
- `CAPACITY`, `UPSTREAM_ERROR`, `INTERNAL`: an incident on our side, often brief (a restart during a deployment, for example); subscribe again after a short wait, with the same `sub` and `from` set to the last cursor received, so you miss nothing;
- `SOURCE_DOWN`: the instrument’s data cannot be served for now; subscribe again later, the same way. Not to be confused with the `source_down` `status`, which keeps the subscription open.

The [SDKs](https://fathomcharts.com/docs/sdk.md#events) do this for you: on `CAPACITY`, `UPSTREAM_ERROR`, `INTERNAL` or `SOURCE_DOWN`, they keep the subscription, send a `retrying` event and subscribe it again after a backoff (0.5 s, doubling up to 30 s). The other codes end the subscription.

A message the server does not understand (invalid JSON, unknown type, missing or unreadable `sub`) receives an `error` without `sub`. Every cause is listed on the [Errors](https://fathomcharts.com/docs/errors.md) page.

## What you receive

Every subscription follows the same sequence:

```text
subscribed
  → status warming            only if the computation is still being prepared
  → snapshot                  from "live" or {"time": …}
    or reset, then snapshot   resume not possible (cursor expired, or another computation: engine_change)
    or the missed messages    successful resume: no snapshot
  → status                    right after (from {"time": …}: once the replay is over)
  → upsert / remove, in order
    and status, only when the state changes
```

1. `subscribed`: the subscription is accepted. It gives the contract actually served (`instrument`, for example `NQZ6` for `NQ.front`), its tick size (`tickSizeNanos`, in billionths of a point) and the computation serving the stream (`engine`, to send back with your cursor when you resume). It carries no cursor: the first one comes with the snapshot, or with the first message of a resume;
2. a `warming` `status`, only if the requested computation is not ready yet, for a few seconds. Nothing is sent until it is exact;
3. `snapshot`: the starting state (see [Snapshot content](#snapshot-content)). On a successful resume there is no snapshot: you receive the missed messages directly;
4. `status`: the stream status (live, market closed…), right after the snapshot, a `reset` or a resume. With `from: {"time": …}`, it comes after the replayed messages, once the stream has caught up with live data;
5. then an `upsert` or a `remove` for every change, in order. A new `status` only arrives when the state changes: the same state is never sent twice in a row.

The connection’s `hb` messages can come in at any time: an `hb` can arrive before `subscribed`, and as long as the subscription has received no cursor (before its snapshot, during `warming`), it is not listed in it (`{"t":"hb","cursors":{}}` if it is the only one).

An example: the one-minute footprint (`timeframe: 60`, `groupTicks: 4`) on `NQZ6`, in `confirmed` mode, subscribed just before the US cash open on September 24, 2026. The snapshot (shortened here) holds the last 32 completed bars of the session; its cursor is that of the last update published on this stream, at the last trade before subscribing. Then each bar arrives when it closes (here, after the 13:30 to 13:32 bars, left out, the 13:33 UTC bar):

```text
{"sub":"fp","t":"subscribed","topic":"1eba40b8d9960be5f8e61ea65c64164e","instrument":"NQZ6","tickSizeNanos":"250000000","engine":"82cbdecf93748dd5"}
{"sub":"fp","t":"snapshot","cursor":"20720.111401.0","items":[…]}
{"sub":"fp","t":"status","state":"live","lagMs":0}
{"sub":"fp","cursor":"20720.124235.0","t":"upsert","id":"1790256780000000000","final":true,"ts":"1790256840033077853","data":{"open":122026,"high":122133,"low":122009,"close":122103,"levels":[[122008,14,3],[122012,44,31],[122016,31,37],[122020,16,32],[122024,48,24],[122028,26,24],[122032,40,28],[122036,24,75],[122040,35,46],[122044,14,32],[122048,12,14],[122052,12,9],[122056,20,9],[122060,36,38],[122064,61,58],[122068,29,68],[122072,28,37],[122076,19,20],[122080,30,46],[122084,32,29],[122088,39,42],[122092,87,67],[122096,154,125],[122100,151,163],[122104,149,192],[122108,66,99],[122112,50,81],[122116,22,38],[122120,27,42],[122124,39,72],[122128,10,25],[122132,0,8]],"poc":122104}}
```

Footprint only sends completed bars, even in `live` mode: each bar arrives once, when it closes. With an indicator that publishes in-progress objects (`big-trades`, for example), `live` mode would add the in-progress object (`final: false`) to the snapshot, then a new version on every trade.

A computation still being prepared starts with `warming`, then sends its snapshot as soon as it has caught up:

```text
{"sub":"lw","t":"subscribed","topic":"…","instrument":"NQZ6","tickSizeNanos":"250000000","engine":"82cbdecf93748dd5"}
{"sub":"lw","t":"status","state":"warming","lagMs":0}
{"sub":"lw","t":"snapshot","cursor":"20720.118342.0","items":[…]}
{"sub":"lw","t":"status","state":"live","lagMs":0}
```

With the market closed (weekend, daily break), the snapshot, which holds the objects of the finished session, is followed by `market_closed`, then only `hb` messages arrive until the market reopens:

```text
{"sub":"bt","t":"subscribed","topic":"368bf15c2d34a77407c10b4f46b79e04","instrument":"NQZ6","tickSizeNanos":"250000000","engine":"82cbdecf93748dd5"}
{"sub":"bt","t":"snapshot","cursor":"20721.1031950.0","items":[…]}
{"sub":"bt","t":"status","state":"market_closed","lagMs":0}
```

To keep your state in sync:

- on `snapshot`, **replace** your entire local state for this subscription with its `items`;
- on each `upsert`, **replace** object `id` with the one received, or add it. An `upsert` always contains the complete object: a footprint bar carries all its levels, not just the ones that changed;
- on each `remove`, delete object `id`. In `confirmed` mode, a `remove` can be about an object you never received (removed before it was completed): ignore it;
- a `final: false` object can still change; a `final: true` object will not change again, but can still be deleted by a `remove`.

### Snapshot content

The snapshot contains:

- the objects in progress (`final: false`);
- every object that can still change or be removed, with no limit on their number: all the `key-levels` levels, the `opening-range` range;
- then the last 32 completed objects of the current period, in the order they were completed. Only objects first published after the period’s first trade count: the last bar of the previous session, completed by that first trade, is not among them.

The period of the snapshot depends on the indicator. It is not always the period after which the indicator starts over:

| Indicator         | Snapshot period: the completed objects come from | The indicator starts over                                                                               |
| ----------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `big-trades`      | The session (18:00 to 17:00 New York time)       | Never: each group stands on its own                                                                     |
| `footprint`       | The session                                      | Never: each bar stands on its own                                                                       |
| `effort-zones`    | The trading week                                 | Every trading week. A zone still extended also ends at each session open                                |
| `liquidity-walls` | The trading week                                 | Every trading week                                                                                      |
| `flow-tracker`    | The trading week                                 | Every trading week                                                                                      |
| `imbalances`      | The trading week                                 | Every trading week. With `resetSession: true`, zones also end when the first bar of each session closes |
| `vwap-bands`      | The trading week                                 | Every session with `periodMode: "daily"` (the default); every trading week with `"bars"`                |
| `key-levels`      | The UTC day                                      | Never: its windows of sessions, weeks and months roll forward                                           |
| `session-profile` | The trading week                                 | Every session                                                                                           |
| `opening-range`   | The trading week                                 | Every session                                                                                           |

Right after the 18:00 open, the snapshot of `big-trades` and `footprint` therefore holds few completed objects. The same goes for the weekly snapshots right after the Sunday reopen.

The limit of 32 applies to all the object kinds of an indicator together: in `effort-zones`, bars, EMA values and completed zones share these 32 places, and the more numerous bars and EMA values can leave no room for any zone. Objects in progress and those that can still change do not count toward this limit.

In `confirmed` mode, the snapshot only holds completed objects (`final: true`).

Two snapshots at the same cursor are identical, whether they come from a live subscription, a `from: {"time": …}` or [history](https://fathomcharts.com/docs/history.md). To fill a chart with more completed objects (big trades, bars, VWAP points), use the history REST API with `"mode": "confirmed"`, then hand off to the stream (see [Hand off to real time](https://fathomcharts.com/docs/history.md#hand-off-to-real-time)).

## Message reference

Messages you send:

| Type (`t`)    | Fields                                                     | Purpose                                                                                                       |
| ------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `auth`        | `token`                                                    | Authenticates a connection opened from a browser, with a stream token. Must be the first message, within 5 s. |
| `subscribe`   | `sub`, `instrument`, `indicator`, `params`, `mode`, `from` | Opens a subscription. Any other field is refused.                                                             |
| `unsubscribe` | `sub`                                                      | Closes a subscription. No acknowledgement is sent.                                                            |
| `ping`        | —                                                          | The server responds with `pong`. Optional.                                                                    |

Messages you receive:

| Type (`t`)   | Fields                                                  | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `subscribed` | `sub`, `topic`, `instrument`, `tickSizeNanos`, `engine` | Subscription accepted. `topic` is an opaque id, the same for two subscriptions on the same contract, indicator and parameters, whatever their `mode`; you can ignore it. `instrument` is the contract served (`NQZ6` for `NQ.front`), `tickSizeNanos` its tick size in billionths, as a string. `engine` identifies the computation serving the stream: keep it with your cursor and send it back when you resume. No cursor: the first one comes with the snapshot, or with the first message of a resume. |
| `snapshot`   | `sub`, `cursor`, `items`                                | Starting state: the objects in progress, those that can still change, then the last 32 completed objects of the period; each with `id`, `final`, `ts` and `data`. `cursor`: that of the last update published on this stream.                                                                                                                                                                                                                                                                               |
| `upsert`     | `sub`, `cursor`, `id`, `final`, `ts`, `data`            | Creates object `id`, or replaces it entirely.                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `remove`     | `sub`, `cursor`, `id`, `final`, `ts`                    | Deletes object `id`. `final` is always `true`, and `ts` is the time of the trade that caused the removal.                                                                                                                                                                                                                                                                                                                                                                                                   |
| `status`     | `sub`, `state`, `lagMs`                                 | Stream state: live, warming up, source delayed or down, market closed. Sent after every snapshot, reset or resume (after the replay for a `from` in the past), then only when the state changes. `lagMs`: internal processing delay, almost always 0.                                                                                                                                                                                                                                                       |
| `reset`      | `sub`, `reason`                                         | Your local state is no longer valid: discard it, a new snapshot follows.                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `error`      | `sub`, `code`, `message`                                | A subscription was refused or stopped (with its `sub`), or a message was invalid (no `sub` when it cannot be read, or when it is already taken by another subscription, which carries on).                                                                                                                                                                                                                                                                                                                  |
| `hb`         | `cursors`                                               | Heartbeat every 5 s, with, for each subscription, the last cursor sent: everything before it has been sent to you. A subscription without a cursor yet (before its snapshot, during `warming`) is not listed; an `hb` can arrive before `subscribed`.                                                                                                                                                                                                                                                       |
| `notice`     | `kind`, `id`, `effectiveAt`, `endsAt`, `message`        | A server announcement to the whole connection. `kind: "reconnect"`: a restart, the connection will be closed within 20 s. `kind: "maintenance"`: a maintenance window `id`, from `effectiveAt` to `endsAt` (nanoseconds, as strings), described by `message`; sent when announced and on every new connection until it ends. `kind: "maintenance-cancelled"`: the window `id` is canceled.                                                                                                                  |
| `pong`       | —                                                       | Response to `ping`. It goes ahead of the queued messages.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

In messages, times (`ts`, etc.) are timestamps in nanoseconds since January 1, 1970 UTC, sent as strings so no precision is lost. Prices are in ticks; averages (such as a VWAP) can have decimals.

## Cursors and resuming

Every `snapshot`, `upsert` and `remove` carries a `cursor`, such as `20720.111434.0`: its position in the stream. Cursors never go backwards. They are the same for every client, live and in history.

A cursor reads `<utcDay>.<rank>.<k>`: the UTC day of the trade, its rank within that day, then the rank of the update for that trade. These are three unsigned 32-bit integers:

- to compare two cursors, compare their three numbers one by one (the SDKs provide `compareCursors` (TypeScript), `compare_cursors` (Python, Rust) or `Cursors.Compare` (C#)). Ranks count the trades of one instrument: never compare cursors of two instruments. Read them as a `number` or a `BigInt`, never as a signed 32-bit integer (`int32`), and never compare them as strings (`9` would sort after `10`);
- `k = 4294967295` (the largest value) marks the position after every update of that trade (see below);
- never build or alter a cursor: only use cursors the API sent you. An altered but well-formed cursor is not always detected, and the resume would then be wrong.

The cursor of a `snapshot` is that of the last update published on this stream before the snapshot, whatever its `k` (often `0`): on a quiet stream, it can be hours old. A stream that has published nothing yet since the start of its computation period (session or week) gives a cursor of the form `<utcDay>.<rank>.4294967295`. With `from: {"time": …}`, when nothing was published between midnight UTC and that time, the snapshot cursor is the position after the last trade of the previous UTC day, `<previous utcDay>.<rank>.4294967295`, even if updates were published earlier in the session. It can then differ from the last cursor of a [history query](https://fathomcharts.com/docs/history.md) ending at that time, but both resume at the same point: nothing was published between them.

**For each subscription, keep the last cursor you received, and the `engine` of its latest `subscribed`.** The `hb` heartbeat, sent every 5 seconds, repeats for each subscription the last cursor sent: everything before it has been sent to you. On a quiet stream, it repeats the same cursor. One exception: after a replay from history (a `from: {"time": …}` subscription, or a cursor resume caught up from history), the `hb` gives the end position of the replay, with `k = 4294967295`, until a new update follows.

```json
{"t":"hb","cursors":{"bt":"20720.112164.0","fp":"20720.124235.0"}}
```

After a disconnect, open a new connection and send the same `subscribe` with that cursor and that `engine`:

```json
{"t":"subscribe","sub":"bt","instrument":"NQ.front","indicator":"big-trades","params":{"minimum":30},"mode":"confirmed","from":{"cursor":"20720.112164.0","engine":"82cbdecf93748dd5"}}
```

- Resume from the stream’s memory: you receive `subscribed`, then everything you missed, then a `status`. **No snapshot**: keep your local state as it is. The stream keeps about the last 15 minutes of updates in memory (less in a very busy market, as that memory is also bounded in size): resuming works as long as everything published after your cursor is still there. On a quiet stream that published nothing since your cursor, it works whatever the cursor’s age, even hours later.
- Resume from history: if the updates after your cursor have left that memory (a long disconnect, or an interrupted `from: {"time": …}` replay), but your history rights cover the cursor’s UTC day (the Historical plan, or the last 7 days with the Live plan or the Sandbox), the resume is caught up from history. You receive `subscribed`, then every update strictly after the cursor (history, then the day’s trades), then live data, with a `status` once live data is reached. No snapshot and no `reset`. The part served from history is charged like a [`from: {"time": …}`](#starting-in-the-past) (the trades after the cursor’s trade; the current UTC day is free), and the subscription can then end with a `QUOTA_EXCEEDED` or `NOT_COVERED` `error`.
- Computation changed: if we updated how the indicator is computed since your cursor (your `engine` is no longer the current one), you receive `subscribed` (with the new `engine`), then a `reset` (reason `engine_change`) followed by a new snapshot and a `status`. Start over from that snapshot: messages computed the new way would not match your state. Without `engine` in `from`, the server cannot tell and resumes as usual.
- Resume not possible: you receive `subscribed`, then a `reset` (reason `cursor_expired`) followed by a new snapshot and a `status`. Start over from that snapshot. This happens in two cases:
  - the later updates are gone from memory, and your history rights do not cover the cursor’s day: it is beyond your plan’s depth;
  - the cursor is beyond the current position of the stream.

After resuming, you may receive a message you already processed. Ignore any `upsert` or `remove` whose cursor is less than or equal to the last one you processed.

## Starting in the past

With `from: {"time": "<time>"}`, you receive the state of the objects at that time, then everything that happened since, and the stream carries on live without a gap. It is the simplest way to fill a chart with recent history before following the market.

```json
{"t":"subscribe","sub":"bt","instrument":"NQ.front","indicator":"big-trades","params":{"minimum":30},"from":{"time":"1790256600000000000"}}
```

You receive `subscribed`, possibly a `warming` `status`, then the snapshot at that time, then the messages replayed since that time, then a `status` once the replay is over (`live` means the stream has caught up with live data), and finally live data, with no gap and no duplicate.

- `from.time` is a timestamp in nanoseconds since January 1, 1970 UTC, as a string, in the past. With delayed data, it must be at least 10 minutes (the delay) in the past: the stream then joins the delayed live stream.
- On an alias, the whole replay reads the contract the alias designates now, the one named in `subscribed`, even when `from.time` is before its last rollover. A [historical query](https://fathomcharts.com/docs/history.md#available-range) reads instead the contract the alias designated at `from`. Before the start of that contract’s history, the subscription receives a `NOT_COVERED` error (`the history of NQZ6 starts on <day>: <day> is before it`).
- This reads from history: it requires the Historical plan, or, with a `from.time` within the 7 × 24 hours before the `subscribe`, the Live plan or the Sandbox rights (a key without a plan). Beyond your plan’s depth, the subscription is rejected with `FORBIDDEN`.
- Only the part before midnight UTC today, served from history, counts against your compute budget, like a historical query (see [What drives the cost](https://fathomcharts.com/docs/history.md#what-drives-the-cost)). It is checked against what you have left and charged page by page, as it is sent: if it exceeds your budget, the subscription receives a `QUOTA_EXCEEDED` error and is closed. Only the trades from `from.time` on are charged, and the snapshot at that time is free. Two subscriptions, for example one in `live` mode and one in `confirmed` mode, are each charged. With the Live plan, a `from.time` within the last 7 days is not charged at all.
- The part of the current UTC day (up to 24 hours) is replayed from the day’s trades our servers keep, separately from the resume memory of about 15 minutes: it is neither charged nor counted in your usage.
- Estimate the cost beforehand, for free, with the [REST estimate](https://fathomcharts.com/docs/history.md#estimate-the-cost) from `from.time` to midnight UTC today. The estimate does not cover the current day (it is listed in `missingDays`), which is not charged.
- History is sent at the pace you read it.

## Stream status

A `status` message follows every snapshot, every `reset` and every resume, then every change of state. The same state is never sent twice in a row to a subscription. Only the latest one counts.

While our computation servers are unreachable, every subscription receives `source_delayed`, then `source_down` after 30 seconds, a new one included: it can then come before the snapshot, which follows once they are back.

```json
{"sub":"bt","t":"status","state":"live","lagMs":0}
```

| `state`          | Meaning                                                                                                                          |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `live`           | The stream is following the market. After a `from: {"time": …}`, the replay is over and the stream has caught up with live data. |
| `warming`        | The computation is getting ready, usually within a few seconds. Nothing is sent until it is exact.                               |
| `source_delayed` | The stream has fallen behind the market. Nothing is lost: the late messages arrive as soon as it catches up.                     |
| `source_down`    | Market data interrupted for more than 30 seconds. No data is ever made up; the stream will resume where it stopped.              |
| `market_closed`  | The market is closed (daily break, weekend).                                                                                     |

`lagMs` is the internal processing delay of our computation for the last batch of trades, in milliseconds. It is not a market data latency, and it does not count the Sandbox’s 10-minute delay. It is only sent with a `status`: it is a one-off value, almost always `0`, not a continuous measurement.

## Reset

A `reset` means your local state for this subscription is no longer valid. Discard it and forget your last cursor: a new snapshot follows and becomes your new starting point, then a `status`.

```json
{"sub":"bt","t":"reset","reason":"roll"}
```

| `reason`              | Cause                                                                                                                                                                                                                                                                                                                                                              |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `roll`                | The alias (`NQ.front`, `ES.front`) now follows a new contract (rollover). A new `subscribed`, naming the new contract, arrives before the snapshot.                                                                                                                                                                                                                |
| `cursor_expired`      | Your resume cursor is too old to be served, is beyond the current position of the stream, or the server could not bridge a gap on its side.                                                                                                                                                                                                                        |
| `entitlement_changed` | Your access switched from delayed to real time, or back (start or end of the Live plan). A new `subscribed` arrives before the snapshot.                                                                                                                                                                                                                           |
| `engine_change`       | We updated how this indicator is computed: objects may differ from the ones already received. A new `subscribed` (with the new `engine`) arrives before the snapshot. Start over from that snapshot. It is also the response to a resume whose `engine` is no longer the current one. See [Updates and maintenance](https://fathomcharts.com/docs/maintenance.md). |

## Keeping the connection alive

The server sends an `hb` every 5 seconds, even with no subscription, and sometimes before the `subscribed` of a subscription you just opened. **If you receive nothing for 15 seconds, treat the connection as lost** and reconnect.

The `hb` is sent in stream order: its cursor means everything before it has been sent. If your client reads slowly, an `hb` can therefore arrive late, behind the queued messages; the 15-second rule still holds, since those messages keep arriving meanwhile. Conversely, `pong` messages (the response to your `ping` message, like WebSocket pong frames) go ahead of the queued messages.

In the other direction, the server sends WebSocket pings every 5 seconds. Browsers and common WebSocket libraries respond to them automatically, as long as your program keeps reading the connection. If the server receives nothing from you for 30 seconds, it closes the connection (code `4008`, reason `PING_TIMEOUT`).

A connection lost without a close (a network drop, for example) is therefore closed by the server after 30 seconds, which frees its slot and its custom configurations in your plan’s limits at once. You usually do not wait that long: when a new connection finds every slot of your plan taken, the server first pings your open connections, and closes those that do not answer within 2 seconds (code `4008`) to admit the new one. A connection that answers keeps its slot. If our server itself stops without closing the connection, its slot is freed after at most 90 seconds.

## Backpressure

If your program reads messages more slowly than they arrive, the server queues them, up to a limit:

- beyond **256 KiB** queued, the server only sends the latest version of each object in progress. Since every `upsert` contains the complete object, your state stays exact. Completed objects and removals are never skipped;
- beyond **1 MiB**, the connection is closed (code `4008`, reason `SLOW_CONSUMER`). Reconnect and resume from your last cursor: you will receive what was missing.

To avoid this, read the connection continuously and process messages separately (a queue, a worker) rather than blocking the read loop. A slow client never slows down anyone else.

## Closing and reconnecting

Before a restart (an update of the service), the server sends `{"t":"notice","kind":"reconnect"}`, then closes the connection within 20 seconds (code `1012`). Keep reading until the connection closes, then reconnect and resume from your last cursors: you lose nothing. Planned maintenance is announced earlier, with a `notice` of kind `maintenance` giving its window: see [Updates and maintenance](https://fathomcharts.com/docs/maintenance.md#maintenance-notices).

| Code   | Name                                                 | Cause                                                                                                                                                                                                                                                                                                                                                                                                                                                      | What to do                                                                                 |
| ------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `4000` | `CLIENT_RECONNECT`                                   | Closed by the client, not by the server. The SDK closes its own connection with this code when it receives nothing for 15 seconds (`heartbeat timeout`), or when its consumer is too slow for its buffer (`client buffer full`).                                                                                                                                                                                                                           | Nothing to do: the SDK reconnects by itself and resumes from the last cursor.              |
| `4001` | `UNAUTHORIZED`                                       | At connection: an `Authorization` header without the `Bearer` scheme (a bare key, for example), an invalid, expired or revoked key, an invalid, expired or already used stream token, or an `auth` message missing or sent after 5 s.                                                                                                                                                                                                                      | Do not reconnect until the key, the header or the token is fixed.                          |
| `4003` | `FORBIDDEN` · `KEY_REVOKED` · `ENTITLEMENTS_CHANGED` | Insufficient rights. At connection: a valid key without the `stream` scope, an IP address that is not allowed or a suspended account (`FORBIDDEN`). During the connection: the key was revoked or expired (`KEY_REVOKED`), your plans no longer cover the open subscriptions (more subscriptions than the new plan allows, for example) or the account was suspended (`ENTITLEMENTS_CHANGED`), or the key’s rights are no longer sufficient (`FORBIDDEN`). | Do not reconnect with this key until its scopes, its restrictions or your plans are fixed. |
| `4008` | `SLOW_CONSUMER` · `PING_TIMEOUT`                     | `SLOW_CONSUMER`: your client stopped reading fast enough (over 1 MiB pending). `PING_TIMEOUT`: the server received nothing from your client for 30 s, not even the responses to its pings.                                                                                                                                                                                                                                                                 | Reconnect right away and resume from the last cursor you received.                         |
| `4029` | `TOO_MANY_CONNECTIONS`                               | You reached the maximum number of concurrent connections of your plan, across all your keys.                                                                                                                                                                                                                                                                                                                                                               | Close another connection, or group your subscriptions on a single one.                     |
| `1002` | `PROTOCOL_ERROR`                                     | Invalid WebSocket frame (wrong fragmentation, malformed control frame, unmasked client frame…).                                                                                                                                                                                                                                                                                                                                                            | Fix your client; do not reconnect in a loop.                                               |
| `1003` | `BINARY_NOT_SUPPORTED`                               | A binary frame was received: the protocol only accepts text messages (JSON).                                                                                                                                                                                                                                                                                                                                                                               | Send your messages as text; do not reconnect in a loop.                                    |
| `1007` | `INVALID_UTF8`                                       | A text message that is not valid UTF-8.                                                                                                                                                                                                                                                                                                                                                                                                                    | Fix the encoding of your messages; do not reconnect in a loop.                             |
| `1008` | `RATE_LIMITED`                                       | More than 20 messages per second on average from your client, control frames included (bursts of 100 allowed).                                                                                                                                                                                                                                                                                                                                             | Reconnect with exponential backoff and space out your messages.                            |
| `1009` | `MESSAGE_TOO_BIG`                                    | A message over 64 KiB (65,536 bytes), fragments included.                                                                                                                                                                                                                                                                                                                                                                                                  | Send smaller messages; do not reconnect in a loop.                                         |
| `1011` | `INTERNAL_ERROR`                                     | Internal error while opening the connection.                                                                                                                                                                                                                                                                                                                                                                                                               | Reconnect with exponential backoff.                                                        |
| `1012` | `SERVICE_RESTART`                                    | A restart of the service (deployment or maintenance), announced by a `notice` (`reconnect`).                                                                                                                                                                                                                                                                                                                                                               | Reconnect and resume from the last cursor you received.                                    |
| `1013` | `TRY_AGAIN_LATER` · `SESSION_EXPIRED`                | The service is temporarily at capacity (`TRY_AGAIN_LATER`), or the connection expired on the server after an incident on our side (`SESSION_EXPIRED`).                                                                                                                                                                                                                                                                                                     | Reconnect with exponential backoff.                                                        |

Reconnection rules:

- on `4001` or `4003`, do not reconnect: fix the key, its rights or your plans first. `4001` comes at connection; `4003` at connection (missing `stream` scope, IP address not allowed) or during it, when your rights change;
- on `1002`, `1003`, `1007` or `1009`, your client sends invalid messages: fix its code rather than reconnecting in a loop;
- on `4029`, close another connection before trying again;
- on `4008`, reconnect immediately;
- in every other case (network drop, `1008`, `1011`, `1012`, `1013`, 15 seconds without a message), reconnect with a delay that doubles after each failure, up to 30 seconds, plus random jitter so that clients do not all come back at once. Reset to the initial delay as soon as a subscription is accepted;
- on every reconnection, resend all your `subscribe` messages with `from: {"cursor": …, "engine": …}`. From a browser, request a new stream token.

The SDK applies these rules. When it drops a connection itself (15 seconds of silence, or a consumer too slow for its buffer), it closes it with code `4000` and reconnects. On `4001`, it ends the subscriptions with an error with code `UNAUTHORIZED`; on `4003`, with `KEY_REVOKED`, `ENTITLEMENTS_CHANGED` or `FORBIDDEN` depending on the close reason; on `1002`, `1003`, `1007` and `1009`, with the close reason as `code` (see [Connection lifecycle](https://fathomcharts.com/docs/sdk.md#connection-lifecycle)).

## Full example

A Node 22 client without the SDK: per-subscription state, cursor-based resume (with the `engine` of the state), duplicate filtering, maintenance notices, detection of a silent connection (15 seconds without a message), reconnection, and a new subscription after a temporary `error`. It opens the connection with the [`ws`](https://github.com/websockets/ws) package (`npm install ws @types/ws`): Node 22’s built-in `WebSocket` does accept headers, but its types do not declare them, and the code would not compile with `tsc --strict`.

```ts
import WebSocket from 'ws';

const URL = 'wss://stream.fathomcharts.com/v1';
const KEY = process.env.FATHOM_CHARTS_API_KEY!;

type Item = { id: string; final: boolean; ts: string; data: unknown };
type Sub = { request: Record<string, unknown>; cursor?: string; engine?: string; objects: Map<string, Item>; attempt: number };

const subs = new Map<string, Sub>([
  ['bt', {
    request: { instrument: 'NQ.front', indicator: 'big-trades', params: { minimum: 30 }, mode: 'live' },
    objects: new Map(),
    attempt: 0,
  }],
]);

// Do not reconnect: fix the key, its rights, or the client’s messages first.
const FATAL = new Set([4001, 4003, 1002, 1003, 1007, 1009]);
// An incident on our side, often brief: the subscription is closed, but its state and cursor stay valid.
// Any other error code is final.
const TEMPORARY = new Set(['CAPACITY', 'UPSTREAM_ERROR', 'INTERNAL', 'SOURCE_DOWN']);
const SILENCE_MS = 15_000;
let attempt = 0;

// Delay before attempt n: doubles from 0.5 s up to 30 s, with random jitter so that clients do not all come back at once.
function backoff(n: number): number {
  const ceiling = Math.min(30_000, 500 * 2 ** n);
  return ceiling / 2 + Math.random() * (ceiling / 2);
}

function subscribe(ws: WebSocket, sub: string, s: Sub) {
  // The engine of the state goes with its cursor: under another computation, the server responds with reset + snapshot.
  const from = s.cursor ? { cursor: s.cursor, engine: s.engine } : 'live';
  ws.send(JSON.stringify({ t: 'subscribe', sub, ...s.request, from }));
}

function connect() {
  // The `ws` package sends the Authorization header when the connection opens.
  const ws = new WebSocket(URL, { headers: { Authorization: `Bearer ${KEY}` } });
  let silence: ReturnType<typeof setTimeout> | undefined;
  let ended = false;

  // Ends this connection once (close, error or silence) and schedules the next one.
  const end = (code: number, reason: string) => {
    if (ended) return;
    ended = true;
    clearTimeout(silence);
    if (FATAL.has(code)) {
      console.error('closed', code, reason);
      return;
    }
    // 4029 (too many connections): retried with backoff here; in production, free another connection first.
    setTimeout(connect, code === 4008 ? 0 : backoff(attempt++));
  };

  // Any message (an hb at least every 5 s) proves the connection alive; 15 s of silence means it is lost.
  const alive = () => {
    clearTimeout(silence);
    silence = setTimeout(() => {
      ws.terminate();
      end(0, 'no message for 15 s');
    }, SILENCE_MS);
  };

  // A failed connection reports an error, then its close: the close handler reconnects.
  ws.onerror = () => {};

  ws.onopen = () => {
    alive();
    for (const [sub, s] of subs) subscribe(ws, sub, s);
  };

  ws.onmessage = (event) => {
    alive();
    const m = JSON.parse(String(event.data));
    if (m.t === 'hb') {
      for (const [sub, cursor] of Object.entries(m.cursors as Record<string, string>)) {
        const s = subs.get(sub);
        if (s && (s.cursor === undefined || compareCursors(cursor, s.cursor) > 0)) s.cursor = cursor;
      }
      return;
    }
    if (m.t === 'notice') {
      // reconnect: a close (1012) follows within 20 s; maintenance: a window announced (effectiveAt, endsAt, message).
      console.log('notice', m.kind, m.message ?? '');
      return;
    }
    if (m.t === 'error' && m.sub === undefined) {
      // An invalid message, or a `sub` already in use: no subscription is closed.
      console.error(m.code, m.message);
      return;
    }
    const s = m.sub === undefined ? undefined : subs.get(m.sub);
    if (!s) return;
    switch (m.t) {
      case 'subscribed':
        // No cursor here: the snapshot, or the first resumed message, carries the starting one.
        s.engine = m.engine;
        attempt = 0;
        break;
      case 'snapshot':
        s.objects = new Map(m.items.map((i: Item) => [i.id, i]));
        s.cursor = m.cursor;
        break;
      case 'upsert':
      case 'remove':
        // Equal-or-older cursors were already applied (duplicates after a resume).
        if (s.cursor !== undefined && compareCursors(m.cursor, s.cursor) <= 0) return;
        if (m.t === 'upsert') s.objects.set(m.id, { id: m.id, final: m.final, ts: m.ts, data: m.data });
        else s.objects.delete(m.id);
        s.cursor = m.cursor;
        if (m.t === 'upsert' && m.final) handle(m.sub, m.data);
        break;
      case 'status':
        // A quiet stream can go minutes without an upsert: the status shows that it works.
        console.log(m.sub, 'status', m.state);
        s.attempt = 0;
        break;
      case 'reset':
        // A snapshot follows and sets the new reference: drop local state and cursor.
        s.objects.clear();
        s.cursor = undefined;
        break;
      case 'error': {
        // The server has refused or closed this subscription.
        const sub: string = m.sub;
        console.error(sub, m.code, m.message);
        if (TEMPORARY.has(m.code)) {
          // Subscribe again later, from the last cursor and its engine: you miss nothing. After a reconnection,
          // the new connection has already subscribed it again.
          setTimeout(() => { if (!ended) subscribe(ws, sub, s); }, backoff(s.attempt++));
        } else {
          // Rights, quota, parameters or missing history: subscribing again would fail the same way.
          subs.delete(sub);
        }
        break;
      }
    }
  };

  ws.onclose = (event) => end(event.code, event.reason);
}

// Total order of cursors <utcDay>.<rank>.<k> (unsigned 32-bit): numeric comparison of the three fields.
function compareCursors(a: string, b: string): number {
  const x = a.split('.').map(BigInt), y = b.split('.').map(BigInt);
  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! < y[i]! ? -1 : 1;
  return 0;
}

function handle(sub: string, data: unknown) {
  console.log(sub, data);
}

connect();
```
