Metadata-Version: 2.5
Name: fathom-charts
Version: 0.6.2
Summary: Fathom Charts client: real-time order-flow indicator streams (WebSocket) and history (REST), for Python 3.11+ (asyncio).
Project-URL: Homepage, https://fathomcharts.com/docs/sdk/python
Project-URL: Documentation, https://fathomcharts.com/docs/sdk/python
Author-email: Adrien Insights <support@fathomcharts.com>
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Keywords: fathom-charts,footprint,indicators,market-data,order-flow,trading,websocket
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.28
Requires-Dist: websockets>=15
Requires-Dist: zstandard>=0.23
Description-Content-Type: text/markdown

# fathom-charts

Python client for [Fathom Charts][fathom-charts]: real-time order-flow indicator streams (WebSocket) and history (REST), for Python 3.11+ (asyncio).

The SDK handles authentication, the initial snapshot, resuming after a disconnect, duplicates, history pagination and rate-limit retries.

Documentation: [fathomcharts.com/docs/sdk/python](https://fathomcharts.com/docs/sdk/python)

## Install

```bash
pip install fathom-charts
# or
uv add fathom-charts
```

Generate the types of each indicator's parameters and data from the catalog (`GET /v1/indicators`, no authentication):

```bash
fathom-charts-types https://api.fathomcharts.com/v1/indicators fathom_charts_types.py
```

The command is installed with the package, so it is always the version you use; it also takes a file saved from `GET /v1/indicators`. Each indicator gets `<Name>Params` and `<Name>Data` (`TypedDict`), named after its id (`big-trades` → `BigTradesParams`), with the catalog's descriptions as docstrings; `IndicatorParams`, `IndicatorData` and `IndicatorId` cover them all. A tuple whose last elements are optional is the union of its allowed lengths (`tuple[int, int, int] | tuple[int, int, int, int]`); JSON arrays still arrive as lists. An indicator with several object kinds gets one type per kind, named after it (`EffortZonesDataBar`, `EffortZonesDataEma`, `EffortZonesDataZone`), and `<Name>Data` is their union: the `id` of an object tells its kind (its pattern is in each type's docstring). It is silent when it succeeds (exit code 0); on failure it prints one line (`fathom-charts-types: …`) and exits with 1; with wrong arguments it prints its usage and exits with 2; `--help` prints the usage.

## Real time

```python
import asyncio
import os

from fathom_charts import FathomChartsStream, Upsert
from fathom_charts_types import BigTradesData


async def main() -> None:
    async with FathomChartsStream(url="wss://stream.fathomcharts.com/v1", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as stream:
        async with stream.subscribe(
            instrument="NQ.front",
            indicator="big-trades",
            params={"minimum": 30},
            mode="confirmed",
            data=BigTradesData,
        ) as big_trades:
            async for event in big_trades:
                if isinstance(event, Upsert):
                    print(event.data["side"], event.data["volume"], event.data["price"])


asyncio.run(main())
```

The events are frozen dataclasses: `Subscribed`, `Snapshot` (its `items` are `Item`), `Upsert`, `Remove`, `Status`, `Reset`, `Notice` and `Retrying`, each with its `type` (`'upsert'`…), to test with `isinstance` or `match`. Heartbeats and pongs are handled by the SDK; notices (a restart, a maintenance window announced or cancelled) reach every subscription and `on_notice`; an `error` on the subscription with a transient code (`UPSTREAM_ERROR`, `CAPACITY`, `INTERNAL`, `SOURCE_DOWN`) gives `Retrying` (`code`, `message`, `delay_ms`) and the SDK subscribes again from the last cursor received, after a backoff (0.5 s, doubling up to 30 s); any other `error` is raised by the loop as a `FathomChartsError`. Leaving the `async with` block of a subscription unsubscribes (leaving an `async for` loop alone does not, in Python: use `async with`, or `await sub.close()`); the connection closes when no subscription is left. See [Real time][websocket].

An application distributed to end users must not hold the API key: give `stream_token` instead of `api_key`, an async function returning a fresh single-use token that your backend gets from `POST /v1/stream-tokens`, called for every connection. `FathomChartsRest.stream_token()` returns a dict (`token`; `expiresAt`, its expiry in Unix nanoseconds as a string, 60 s after it was created): return its token.

```python
async def token() -> str:
    return (await rest.stream_token())["token"]  # or a call to your backend
```

When `stream_token` fails with a network failure (`OSError`, `TimeoutError` included, or `httpx.TransportError`) or a `FathomChartsError` with code `NETWORK_ERROR`, `RATE_LIMITED`, `CAPACITY`, `HTTP_429` or a status of 500 or more, the SDK calls it again later, like a lost connection; any other error (`QUOTA_EXCEEDED`, an `httpx.HTTPStatusError`, a bug in the function) ends every subscription (a `FathomChartsError` as is, any other error as `CONFIGURATION` with it as `__cause__`), as does a function that is not async or returns no usable token.

## History

```python
# Inside an async function (asyncio.run(main())), as every REST example.
from fathom_charts import FathomChartsRest

async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as rest:
    async for m in rest.history(
        {
            "instrument": "NQZ6",
            "indicator": "big-trades",
            "params": {"minimum": 30},
            "from": "1790256600000000000",
            "to": "1790258100000000000",
        }
    ):
        if m["t"] == "upsert" and m["final"] and "data" in m:
            print(m["cursor"], m["data"]["side"], m["data"]["volume"])
```

Queries are dictionaries with the fields of the API (`instrument`, `indicator`, `params`, `from`, `to`, `mode`, `limit`, `cursor`, `untilCursor`, `snapshot`); with `"snapshot": True`, `history()` yields the state at `from` first, as a `{"t": "snapshot", "cursor": …, "items": […]}` element. `page()` and `pages()` give the pages themselves, `estimate()` the cost of a query without running it. On error, the SDK raises a `FathomChartsError` carrying the error `code`. See [History][history].

## Export to a file

`export_ndjson()` decompresses an export as NDJSON (one mutation per line), in chunks of whole lines, and resumes it by itself after a cut, without gap or duplicate:

```python
from contextlib import aclosing

from fathom_charts import RangeQuery

query: RangeQuery = {
    "instrument": "NQZ6",
    "indicator": "big-trades",
    "params": {"minimum": 30},
    "from": "1790256600000000000",
    "to": "1790258100000000000",
}
async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as rest:
    with open("big-trades.ndjson", "wb") as file:
        async with aclosing(rest.export_ndjson(query)) as chunks:
            async for chunk in chunks:
                file.write(chunk)
```

`max_resumes` (default 5) bounds the consecutive resumptions without a new line, `resume_delay` (1 s, doubled up to 30 s) spaces them. `export()` gives the zstd-compressed file as sent (`body`, `content_type`, `filename`, and the `token` that resumes it).

## Connection, resume and flow control

`FathomChartsStream` multiplexes its subscriptions on one connection and reopens it after a cut (backoff with jitter), resuming each subscription after its last cursor received, with the engine build its state comes from; events already received are never delivered twice. During an update of the service the stream pauses and resumes by itself; when the computation of an indicator changed, the subscription receives `reset` (`engine_change`), `subscribed` and a new snapshot. See [Updates and maintenance][maintenance].

Durations are in seconds.

- A resume within the server's memory of recent messages continues where it stopped. An older one (a long cut, or a long `from_={"time": …}` replay interrupted) is caught up from history when your offer includes it and its depth reaches the cursor's UTC day: the rest of the replay follows, then real time, without `reset` nor snapshot (the historical part is charged like the `from_={"time": …}`). Otherwise the subscription receives `reset` (`cursor_expired`) followed by a fresh snapshot.
- `high_water_mark` (default 10 000 queued events): above it, the SDK stops reading the socket; the server then keeps only the latest version of each object in progress. With a socket that cannot pause, the SDK itself replaces a queued provisional version by the newer one, and closes at `max_buffered`. While paused, the SDK sends `ping` messages so that the server keeps the connection; it reads again once the events waiting fall to half of `high_water_mark`.
- `max_buffered` (default 4 × `high_water_mark`): a socket given by a `web_socket` factory that cannot be paused (`pausable` false) stops being read there: the SDK closes the connection (close code 4000, `CloseCode.CLIENT_RECONNECT`, `client buffer full`; the state becomes `reconnecting` at once) and reopens it from the last queued cursor once the events waiting fall to half of `high_water_mark`. Nothing queued is lost, and the resume rules above apply. A consumer that stays slower than the stream keeps closing and reopening the connection: process the events in a separate task.
- `heartbeat_timeout` (default 15 s): without any message for this long (the server sends `hb` every 5 s), the connection is dropped (close code 4000, `heartbeat timeout`) and reopened. The SDK checks every third of it: the silence is detected between `heartbeat_timeout` and 4/3 of it.
- `reconnect=Reconnect(...)`: `initial_delay` (0.25 s), `max_delay` (30 s), `quota_retry` (how long close code 4029 is retried, at least, 120 s), `quota_delay` (5 s). During 4029 retries the state goes from `open` to `reconnecting` at each attempt; then every subscription ends with `TOO_MANY_CONNECTIONS`.
- `random`: source of the jitter of reconnections and subscription retries, in [0, 1) (default `random.random`; for tests).
- `on_notice` receives the server notices (`reconnect`; `maintenance` with `id`, `effective_at`, `ends_at`, `message`; `maintenance-cancelled` with `id`), also given to every subscription as `Notice` events; `stream.maintenance` lists the maintenance windows announced and not over (`MaintenanceWindow(id, starts_at, ends_at, message)`, times in Unix ns); `on_state_change` the connection state (`idle`, `connecting`, `open`, `reconnecting`, `closed`), also readable as `stream.connection_state`; `stream.last_close` (`ConnectionClose(code, reason)`) tells how the connection last closed, set before `on_state_change` is called (`code` is an `int`, a `CloseCode` for the SDK's own closes: `1000` `idle`, `client closed` or `failed`, `4000` `heartbeat timeout` or `client buffer full`). Both callbacks are plain functions: an `async def` raises `CONFIGURATION`. `await stream.close()` closes everything; `aclose()` does the same, for `contextlib.aclosing`.

A `Subscription` is an async iterator of events, with:

- `id`: its `sub` on the connection (`s1`, `s2`…), as in the protocol messages;
- `request`: the subscription as requested, defaults filled in (`params={}`, `mode='live'`, `from_='live'`);
- `cursor`: cursor of the last event handed to your loop, the resume point; `None` until a cursor arrives, also after `from_={"cursor": …}`. `hb` messages repeat the last cursor sent: `cursor` moves forward with an `hb` only when it carries a later cursor, after a replay from history; on a quiet stream it stays on the last cursor received, and resuming from it loses nothing;
- `topic`: topic key from the latest `subscribed`;
- `engine`: engine build from the latest `subscribed`; save it with `cursor` and resume a later process with `from_={"cursor": cursor, "engine": engine}`;
- `close()`: unsubscribes (as leaving its `async with` block does).

A server that cannot be reached (network down, a wrong host name) is retried forever with backoff: watch `on_state_change` (`reconnecting`) or bound the wait with `asyncio.timeout()`. A handshake refused with an HTTP 4xx other than 429 (a wrong path) ends every subscription with `HTTP_<status>`.

`CloseCode` lists the gateway's WebSocket close codes, and `CLIENT_RECONNECT` (4000) the SDK closes with before reconnecting; `compare_cursors(a, b)` orders two cursors (negative, zero, positive).

## Errors

Every error the SDK raises, or ends an iteration with, is a `FathomChartsError` (`ERROR_CODES` lists the codes):

- `code`: the API's code (`INVALID_PARAMETERS`, `FORBIDDEN`, `QUOTA_EXCEEDED`…), or one of the SDK's own: `CONFIGURATION` (invalid options: missing or empty `api_key`, or with spaces or control characters around it, both `api_key` and `stream_token`, a `url` that is not `ws://`/`wss://`, a `base_url` that is not `http://`/`https://`, a query JSON cannot carry, a `from_` time that is not a `str`, a subscribe message over 65,536 bytes, an `async def` callback, a failing `stream_token`…), `CLOSED`, `KEY_REVOKED`, `ENTITLEMENTS_CHANGED`, `TOO_MANY_CONNECTIONS`, `PROTOCOL_ERROR`, `BINARY_NOT_SUPPORTED`, `INVALID_UTF8`, `MESSAGE_TOO_BIG`, `NETWORK_ERROR` (the API could not be reached, or the connection was lost during an answer), or `HTTP_<status>` for an HTTP error answer that is not a problem document (or a refused WebSocket handshake);
- `status`, `close_code`, `retry_after` when known (`retry_after` in seconds, also when the header is an HTTP date);
- `problem`: the RFC 9457 problem document of an HTTP error, with its `errors` (invalid fields); `None` when the answer is not a problem document;
- `__cause__`: the original error (the error of httpx…), when there is one.

A call is stopped by cancelling its task (`asyncio.timeout()`, `Task.cancel()`), a wait for a retry included: the `asyncio.CancelledError` goes through untouched, as asyncio requires. The default HTTP client has no timeout (as `fetch` in the TypeScript SDK): bound a call with `asyncio.timeout()`, or give `http_client=httpx.AsyncClient(timeout=…)`.

`fathom_charts.__version__` is the version of the installed package.

## License

Proprietary: you may use this package and include it in your own applications only to access the Fathom Charts service. See [LICENSE](./LICENSE).

[fathom-charts]: https://fathomcharts.com
[websocket]: https://fathomcharts.com/docs/websocket
[history]: https://fathomcharts.com/docs/history
[maintenance]: https://fathomcharts.com/docs/maintenance
