Python SDK
fathom-charts handles authentication, the initial snapshot, resuming after a disconnect, duplicates, history pagination, exports and rate-limit retries for you, on asyncio. This page describes every option and method; the behaviour the four SDKs share is in SDKs.
Install
pip install fathom-charts==0.6.0Or uv add fathom-charts==0.6.0, in a virtual environment as in the Quickstart. Python 3.11 or later, asyncio only: in a notebook (Jupyter), await works at the top level of a cell. Its dependencies are websockets, httpx and zstandard. The package is typed (py.typed): mypy --strict checks your code against it. fathom_charts.__version__ gives the installed version.
Indicator types
fathom-charts-types https://api.fathomcharts.com/v1/indicators fathom_charts_types.pyThe command, installed with the package (so it is always the version you use), takes the catalog’s URL or a file saved from GET /v1/indicators. Each indicator gets <Name>Params and <Name>Data (TypedDict), named after its id (big-trades → BigTradesParams, BigTradesData), 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] for a footprint level); JSON arrays still arrive as lists.
An indicator that publishes several kinds of objects gets one type per kind, named after it: EffortZonesDataBar, EffortZonesDataEma, EffortZonesDataZone. EffortZonesData is their union. The id of an object tells its kind: its pattern (bar:<weekSunday>:<index>…) is in the docstring of each type.
Put fathom_charts_types.py next to your scripts (or on sys.path), and generate it again when the catalog changes. The command prints nothing when it succeeds (exit code 0). On failure, it prints one line (fathom-charts-types: …) and exits with code 1; with wrong arguments, it prints its usage and exits with code 2. --help prints its usage. fathom-charts-types is on the PATH once the virtual environment is activated (.venv\Scripts\Activate.ps1 in PowerShell); python -m fathom_charts.generate_types … runs the same command without activating it.
Real time: FathomChartsStream
import asyncio
import os
from fathom_charts import FathomChartsStream, Upsert
from fathom_charts_types import BigTradesData, BigTradesParams
async def main() -> None:
async with FathomChartsStream(url="wss://stream.fathomcharts.com/v1", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as stream:
params: BigTradesParams = {"minimum": 30}
async with stream.subscribe(
instrument="NQ.front", indicator="big-trades", params=params, mode="confirmed", data=BigTradesData
) as big_trades:
async for event in big_trades:
if isinstance(event, Upsert):
print(event.cursor, event.data["side"], event.data["volume"])
try:
asyncio.run(main())
except KeyboardInterrupt:
pass # Ctrl+C: the blocks above closed the subscription and the connection.data=BigTradesData, the generated data type of the indicator, makes subscribe() return a Subscription[BigTradesData], which gives event.data its type, as data does for the REST methods; it changes nothing at run time. Without it, subscribe() returns a Subscription[Any]. An indicator with several kinds of objects has a union for data type (EffortZonesData), which cannot be passed as an argument: annotate the variable instead, before the async with (zones: Subscription[EffortZonesData]). params takes any mapping: annotated with the generated BigTradesParams, they are checked too ({"minimum": "30"} is then a type error, not a refusal of the server). With os.environ[…], an unset variable raises KeyError before the SDK runs; an empty value, or one with spaces or control characters around it (a \r left by a .env file with Windows line endings), raises CONFIGURATION, without the key in the message.
Options
Durations are in seconds.
| Option | Purpose |
|---|---|
url | Required. The stream address: wss://stream.fathomcharts.com/v1. Anything but an absolute ws:// or wss:// URL raises CONFIGURATION. |
api_key | API key, sent in the Authorization: Bearer header. |
stream_token | Instead of api_key, in an application distributed to end users, which must not hold the key: an async def function returning a fresh single-use token that your backend gets from POST /v1/stream-tokens. It is called on every connection, reconnections included. Give exactly one of api_key and stream_token, otherwise the constructor raises CONFIGURATION. See below. |
web_socket | Optional: an async def function that opens the connection, to use another socket. See Your own WebSocket. |
reconnect | Optional: Reconnect(initial_delay=0.25, max_delay=30.0, quota_retry=120.0, quota_delay=5.0): first reconnection delay, backoff ceiling, how long a 4029 close code is retried, minimum delay between two attempts after a 4029. |
heartbeat_timeout | Silence after which the connection is considered lost, then reopened (close code 4000, heartbeat timeout; the state becomes reconnecting at once). The SDK checks every third of it, so it detects the silence between heartbeat_timeout and 4/3 of it (15 to 20 seconds by default). 15 by default: the server sends an hb every 5 seconds. |
high_water_mark | Number of events waiting to be read, all subscriptions together, above which the SDK stops reading the socket; the server then keeps only the latest version of each object in progress (intermediate versions of an object in progress may be skipped, final versions and removals never are). With a socket that cannot pause, the SDK itself replaces a queued provisional version by the newer one, and closes at max_buffered. While it waits, it sends ping messages (every third of heartbeat_timeout) so that the server keeps the connection; it reads again once the events waiting fall to half of high_water_mark. 10,000 by default. |
max_buffered | For a socket that cannot pause: number of waiting events above which the SDK closes the connection (close code 4000, reason client buffer full; the state becomes reconnecting at once, and stays so until the connection is open again), then reopens it from the last cursor received once the events waiting fall to half of high_water_mark (5,000 by default). Nothing waiting is lost, and the resume follows the rules of Connection lifecycle: no loss when it is served by the stream’s memory or by the history your rights cover, otherwise reset then a snapshot. A consumer that stays slower than the stream keeps closing and reopening the connection: process the events in a separate task (an asyncio.Queue read by a worker task, for example), so that the async for loop keeps up. 4 × high_water_mark by default. |
random | Optional, for tests: the source of the jitter of reconnections and subscription retries, a function returning a number in [0, 1). random.random by default. |
on_state_change | Called on every change of connection_state, with the new state. A plain function (def): the SDK does not await it, so an async def raises CONFIGURATION. It runs on the event loop: keep it short. When the state becomes reconnecting, stream.last_close already tells why the connection closed. The SDK reconnects silently, so this is where to show or log it (example below). |
on_notice | Called with each notice from the server (kind, id, effective_at, ends_at, message): a restart, a maintenance window announced or cancelled. A plain function, as on_state_change: an async def raises CONFIGURATION. See Updates and maintenance. |
async with FathomChartsStream(…) as stream closes the stream at the end of the block; await stream.close() does the same, and so does await stream.aclose(), for contextlib.aclosing(stream). stream.connection_state is idle, connecting, open, reconnecting or closed (ConnectionState). stream.last_close is the ConnectionClose (code, reason) of the last close of an open connection, None until one closes: the server’s close frame (4029 TOO_MANY_CONNECTIONS when every connection of your plan is in use, for example), 1005 for a close frame without a code, 1006 for a connection lost without one, or the SDK’s own close. code is an int, a CloseCode for the SDK’s own closes: 1000 with the reason idle (the last subscription closed), client closed (you closed the stream while the connection was still open) or failed (a final error ended every subscription); 4000 with heartbeat timeout or client buffer full, before it reconnects. It is set before on_state_change is called. Here the callback reads stream from main(): it is only called once stream exists.
import asyncio
import os
from fathom_charts import ConnectionState, FathomChartsStream
async def main() -> None:
def on_state_change(state: ConnectionState) -> None:
if state == "reconnecting" and stream.last_close is not None:
print("reconnecting after", stream.last_close.code, stream.last_close.reason)
async with FathomChartsStream(
url="wss://stream.fathomcharts.com/v1", api_key=os.environ["FATHOM_CHARTS_API_KEY"], on_state_change=on_state_change
) as stream:
async with stream.subscribe(instrument="NQ.front", indicator="big-trades") as sub:
async for event in sub:
print(event)
asyncio.run(main())stream.maintenance lists the maintenance windows announced on the connection and not over, by start. Each is a MaintenanceWindow:
| Field | Content |
|---|---|
id | The id of the window, as in the maintenance notice. |
starts_at | Start, Unix nanoseconds (decimal string): the effective_at of the notice. |
ends_at | End, Unix nanoseconds (decimal string). |
message | What the maintenance is about. |
Stream token
FathomChartsRest.stream_token() returns a dictionary: token, single-use, and expiresAt, its expiry in Unix nanoseconds as a string (60 seconds after it was created); stream_token wants the token alone. On your backend, or in a test:
import asyncio
import os
from fathom_charts import FathomChartsRest, FathomChartsStream
async def main() -> None:
async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as rest:
async def token() -> str:
return (await rest.stream_token())["token"]
async with FathomChartsStream(url="wss://stream.fathomcharts.com/v1", stream_token=token) as stream:
async with stream.subscribe(instrument="NQ.front", indicator="big-trades") as sub:
async for event in sub:
print(event)
asyncio.run(main())In an application distributed to end users, token() calls your backend instead. The SDK calls the function again, with the reconnection backoff, when it fails with a network failure (an OSError, TimeoutError and ConnectionError included, or an httpx.TransportError: no answer was received) or with a FathomChartsError NETWORK_ERROR, RATE_LIMITED, CAPACITY, HTTP_429 (a 429 answer without a problem document) or with a status of 500 or more. Any other error ends every subscription, a bug in the function included: a FathomChartsError as is (QUOTA_EXCEEDED, a 429 too, among them), any other error as CONFIGURATION (stream_token failed: …) with the original as __cause__. An httpx.HTTPStatusError (from raise_for_status()) is not retried, whatever its status: when your backend answers 502, raise FathomChartsError("HTTP_502", "…", status=502) to have it retried. A function that is not async, or that returns anything other than a non-empty token without spaces around it, ends them with CONFIGURATION too.
Your own WebSocket
web_socket is a WebSocketFactory: an async def function that takes the URL and the headers (Authorization: Bearer <key> with api_key, None with stream_token), opens the connection, and returns it open, as a WebSocketLike:
pausable: whether not callingrecv()stops reading the network (TCP backpressure up to the server), aswebsocketsdoes once its queue of frames is full. When it isFalse,max_bufferedapplies;async recv()returns the next message,async send(message)sends one,async close(code, reason)closes the connection;- once the connection is closed,
recv()andsend()must raisewebsockets.exceptions.ConnectionClosed: the SDK reads the code and reason of the close from its received close frame. Any other exception counts as a connection lost without a close (1006).
A websockets connection already behaves this way: wrap it to add pausable. Through a proxy, for example:
import asyncio
import os
from collections.abc import Mapping
from websockets.asyncio.client import ClientConnection, connect
from fathom_charts import FathomChartsStream
class ProxiedSocket:
pausable = True
def __init__(self, connection: ClientConnection) -> None:
self.connection = connection
async def recv(self) -> str | bytes:
return await self.connection.recv()
async def send(self, message: str) -> None:
await self.connection.send(message)
async def close(self, code: int, reason: str) -> None:
await self.connection.close(code, reason)
async def open_socket(url: str, headers: Mapping[str, str] | None) -> ProxiedSocket:
# max_size=None: a snapshot can be larger than the default limit of websockets.
return ProxiedSocket(await connect(url, additional_headers=headers, proxy="http://proxy.example.com:3128", max_size=None))
async def main() -> None:
async with FathomChartsStream(
url="wss://stream.fathomcharts.com/v1", api_key=os.environ["FATHOM_CHARTS_API_KEY"], web_socket=open_socket
) as stream:
async with stream.subscribe(instrument="NQ.front", indicator="big-trades") as sub:
async for event in sub:
print(event)
asyncio.run(main())A FathomChartsError the factory raises with the code UNAUTHORIZED, FORBIDDEN, CONFIGURATION or HTTP_4xx (other than HTTP_429) ends every subscription; any other exception is retried with backoff, silently: the state stays reconnecting.
When the connection cannot be opened
| Case | What happens |
|---|---|
| Network down, server unreachable, a wrong host name, a timeout | Retried forever with backoff: connection_state is reconnecting. Watch on_state_change, or bound the wait with asyncio.timeout(). |
| The server answers the handshake with 429 or 5xx | Retried with backoff. |
The server answers the handshake with another 4xx (a wrong path: HTTP_404) | Every subscription ends with HTTP_<status> (status set): another attempt would get the same answer. |
Close code 4029: every connection of your plan is in use | Each attempt opens a connection that the server then closes, so connection_state goes from open to reconnecting at each attempt. The SDK retries for at least quota_retry (the attempt in progress at its end finishes first), then ends every subscription with TOO_MANY_CONNECTIONS (close_code 4029): The plan's connection limit was still reached after 120 s of retries (4029): close another connection, then subscribe again. |
Close codes 1002, 1003, 1007, 1009: the server refused a message | Every subscription ends with an error whose code is the close reason (PROTOCOL_ERROR, BINARY_NOT_SUPPORTED, INVALID_UTF8 or MESSAGE_TOO_BIG), or PROTOCOL_ERROR when the close has no reason, with close_code set. |
Close codes 4001, 4003… | See Connection lifecycle. |
subscribe()
stream.subscribe(*, instrument=…, indicator=…, params=None, mode="live", from_="live", data=None) opens a subscription and returns a Subscription, to read with async for. Its keyword-only arguments are those of the subscribe message; from_ (from is a Python keyword) is From: "live", {"cursor": …, "engine": …} (CursorFrom) or {"time": …} (TimeFrom, the time in Unix nanoseconds as a str). data is the generated data type of the indicator (data=BigTradesData): it types the events for the type checker, and changes nothing at run time. The SDK picks the sub name itself. An empty instrument or indicator is sent as is, and the server refuses it (INVALID_PARAMETERS). subscribe() raises CONFIGURATION at once, and sends nothing, for arguments JSON cannot carry (a datetime, a NaN), a from_ time that is not a str (an int: convert it with str()), or a message over the 65,536 bytes (UTF-8) the server accepts (very large params): sent, it would close the connection of every subscription.
The events are frozen dataclasses: Subscribed, Snapshot (its items are Item), Upsert, Remove, Status, Reset, Notice and Retrying, each with its type ("upsert"…); StreamEvent is their union. Test them with isinstance or match. Their fields are those of Events, in snake case (tick_size_nanos, lag_ms, delay_ms). After an error with a transient code (UPSTREAM_ERROR, CAPACITY, INTERNAL, SOURCE_DOWN), the loop goes on: it receives Retrying (code, message, delay_ms), and the SDK subscribes again from the last cursor received. Any other error on the subscription ends the loop: async for raises a FathomChartsError carrying the received code.
async for event in big_trades:
match event:
case Upsert():
print(event.data["side"])
case Status():
print("status", event.state)
case _:
passSubscription
| Member | Purpose |
|---|---|
cursor | The cursor of the last event handed to you: your resume point. None until a cursor has arrived, also when you subscribed from_={"cursor": …}: it is set by the first event or hb that carries one. 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, and no event is waiting to be read. On a quiet stream, it stays on the last cursor received, and resuming from it loses nothing. A cursor that ends in .4294967295 is a position after every update of a trade: see Which cursor is for what. |
topic | The topic of the latest subscribed. |
engine | The engine of the latest subscribed, or the engine given in from_ until a subscribed arrives: the computation your state comes from. Save it with cursor to resume later. |
id | The sub name the SDK chose for this subscription (s1, s2…). |
request | The arguments of subscribe(), completed with the default values (SubscribeRequest). |
close() | Async: stops the subscription; the SDK sends unsubscribe, and a pending loop ends. aclose() does the same, for contextlib.aclosing(). |
Leaving the async with block of a subscription closes it. Leaving a bare async for loop with break does not, in Python: the subscription stays open, and so does the connection. Use async with, or await sub.close(). Reconnection, resuming and close codes: see Connection lifecycle; to resume after your process restarts, see Resume after a restart.
History: FathomChartsRest
import asyncio
import os
from fathom_charts import FathomChartsRest
async def main() -> None:
async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as rest:
usage = await rest.usage()
print(usage["remaining"]["computeUnits"])
asyncio.run(main())| Option | Purpose |
|---|---|
base_url | Required. The API address: https://api.fathomcharts.com. Anything but an absolute http:// or https:// URL raises CONFIGURATION. |
api_key | Required. API key, sent in the Authorization: Bearer header. |
rate_limit_retries | Number of retries of a request the server did not process, or of a read that failed (see Rate limit and retries). 3 by default. |
http_client | Optional: your own httpx.AsyncClient (proxy, timeouts…). The default client has no timeout, like fetch in the other SDKs: give httpx.AsyncClient(timeout=30), or bound a call with asyncio.timeout(). |
async with FathomChartsRest(…) as rest closes the client it created at the end of the block (not one given as http_client); await rest.aclose() does the same, and works with contextlib.aclosing(rest). There is no close(): closing the httpx client must be awaited, and aclose() is the asyncio name for that, as in httpx.
Methods
Queries are dictionaries with the fields of the API, as on the History page (instrument, indicator, params, from, to, mode, and depending on the method limit, cursor, untilCursor, snapshot): PageQuery and RangeQuery type them. cursor is the next of the previous page, not the cursor of an item; untilCursor is the cursor of an item or of a subscription (a stream cursor), where the query stops. Responses are TypedDicts with the fields of the API, in camel case as on the wire.
| Method | Returns |
|---|---|
await page(query, *, data=None) | One Page: instrument, tickSizeNanos, snapshot (PageSnapshot), items (Mutation), next, computeUnits. |
pages(query, *, data=None) | The pages one at a time, following next, as you read them (async for). |
history(query, *, data=None) | The results one at a time, across pages. With "snapshot": True, the first element is the state at from, a HistorySnapshot ({"t": "snapshot", "cursor", "items"}, its items plain dictionaries, not Item), then come the updates, each a Mutation (t is upsert or remove, with its cursor). |
await estimate(query) | The cost estimate (Estimate), charging nothing. |
await export(query, *, resume=None) | One export response, an ExportStream: body (the zstd-compressed file as is), content_type, filename, token (resumes the export with resume, an ExportResume: {"token", "after"}). |
export_ndjson(query, *, max_resumes=5, resume_delay=1.0) | The decompressed export, in chunks (bytes) of whole lines, with automatic resume. See Exports. |
await stream_token() | A StreamToken: token, single-use, and expiresAt, its expiry in Unix nanoseconds as a string (60 seconds after it was created). |
await usage() | Your usage this month and your limits (Usage). |
await instruments() | instruments: every instrument served (Instruments). |
await status() | The state of the computation, of each instrument, and the maintenance windows announced (ServiceStatus). |
await indicators() | The indicator catalog (Catalog). |
resume, max_resumes and resume_delay are keyword-only: export(query, resume={"token": …, "after": …}).
data, the generated data type of the indicator, types what page(), pages() and history() return, for mypy --strict and pyright alike; it changes nothing at run time. Without it, the data is Any. An indicator with several kinds of objects has a union for data type (EffortZonesData), which cannot be passed as an argument: annotate the iterator instead, with the AsyncGenerator the method returns.
from collections.abc import AsyncGenerator
from fathom_charts import Page
from fathom_charts_types import BigTradesData, EffortZonesData
async for page in rest.pages(query, data=BigTradesData):
for m in page["items"]:
if "data" in m:
print(m["data"]["side"], m["data"]["volume"])
zones: AsyncGenerator[Page[EffortZonesData], None] = rest.pages({**query, "indicator": "effort-zones", "params": {}})
async for zone_page in zones:
...The query of big-trades has its own params: effort-zones gets its own ({}, its defaults), not those of another indicator.
An ExportStream holds an open response: read its body to the end, or close it. async with does it for you:
async with await rest.export(query) as exported:
with open(exported.filename or "export.ndjson.zst", "wb") as file:
async for chunk in exported.body:
file.write(chunk)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. Close an async generator you leave early (contextlib.aclosing), as with any async generator: its request in progress ends at once, not when the garbage collector gets to it.
from contextlib import aclosing
async with aclosing(rest.history(query, data=BigTradesData)) as results:
async for result in results:
if result["t"] == "upsert" and "data" in result and result["data"]["volume"] >= 100:
print("first trade of 100 or more:", result["cursor"])
breakErrors
Every error the SDK raises, or ends a loop with, is a FathomChartsError. Its codes are listed in Errors; ERROR_CODES holds them all but ABORTED, which the Python SDK never raises: cancelling a task raises asyncio.CancelledError. CloseCode lists the WebSocket close codes, including CLIENT_RECONNECT (4000), the code the SDK closes with before reconnecting.
| Field | Content |
|---|---|
code | The stable error code, typed str (not ErrorCode): compare it with a string (error.code == "NOT_COVERED"). |
message | A human-readable explanation. It never contains your key or a header value. |
status | The HTTP status, over REST or for a refused handshake. |
close_code | The WebSocket close code, when the connection was closed. |
retry_after | The Retry-After header in seconds, when the response has one: given in seconds, or as an HTTP date (the seconds until then). |
problem | The full problem+json document of the response, with errors when the API lists invalid fields; None otherwise. |
__cause__ | The original error, when there is one (the error of httpx…). |
str(error) is <code>: <message> (NOT_COVERED: …), as an uncaught error prints it.
CONFIGURATION covers the options the SDK refuses itself: a missing or empty key, a key with spaces or control characters around it, both api_key and stream_token, a url or base_url of the wrong form, an async def given as on_state_change or on_notice, a query JSON cannot carry, a from_ time that is not a str, a subscribe message over 65,536 bytes, a stream_token that fails with an error the SDK does not retry (see Stream token).
Cursors
from fathom_charts import compare_cursors
compare_cursors("20720.111416.0", "20720.111417.0") # < 0A cursor is <utcDay>.<rank>.<k>: three integers from 0 to 4294967295, without leading zeros. Anything else raises INVALID_PARAMETERS.
Public types
Everything below is exported by fathom_charts.
| Type | What it is |
|---|---|
From, CursorFrom, TimeFrom, Mode | The from_ and mode of subscribe(). |
StreamEvent, Subscribed, Snapshot, Item, Upsert, Remove, Status, Reset, Notice, Retrying | The events of a subscription. |
SourceState, ResetReason, NoticeKind | The known values of Status.state, Reset.reason, Notice.kind. A value your version does not know arrives as a str all the same (see Events). |
Subscription, SubscribeRequest, ConnectionState, ConnectionClose, Reconnect, MaintenanceWindow | The stream’s objects and options. |
WebSocketFactory, WebSocketLike | What a web_socket factory is and returns. |
PageQuery, RangeQuery, ExportResume | REST queries. |
Page, PageSnapshot, Mutation, HistorySnapshot, Resolved, Estimate, ExportStream | History and export results. |
Usage, UsageUsed, UsageRemaining, Limits, Instrument, Instruments, ServiceStatus, EngineState, StatusInstrument, StatusMaintenance, PlanCode, StreamToken, Catalog, CatalogIndicator, CatalogParam, CatalogObject, CatalogField, CatalogExample | Account, status and catalog answers, and the dictionaries nested in them. |
FathomChartsError, ErrorCode, ERROR_CODES, ProblemFieldError, CloseCode | Errors. |
ServerMessage, ClientMessage and each message (AuthMessage, SubscribeMessage, UpsertMessage…), SnapshotItem (an object of a SnapshotMessage) | The WebSocket protocol, as on the wire, for your own client. |