SDKs

TypeScript SDK

@fathom-charts/sdk handles authentication, the initial snapshot, resuming after a disconnect, duplicates, history pagination, exports and rate-limit retries for you. This page describes every option and method; the behaviour the four SDKs share is in SDKs.

Install

terminal
npm init -y
npm pkg set type=module
npm install @fathom-charts/sdk@0.6.0 ws
  • ESM only: the package ships no CommonJS build. Declare "type": "module" in your package.json (the second command above), or use .mjs / .mts files: it is the recommended setup, and the examples need it for their top-level await. Node 22.15 can also load the package with require() from CommonJS code.
  • Node 22.15 or later, and browsers. 22.15 is the version exportNdjson() needs (zstd decompression from node:zlib); npm warns on an older Node.
  • ws is only needed in Node: it opens the connection with the Authorization header. In a browser, the SDK uses the native WebSocket with a stream token.
  • Browser bundlers (Vite, webpack, esbuild, Next.js…) leave ws out of a browser build without any setting: the package declares the module that imports ws under the browser condition of its imports field, which points them to a module without it. In that build, an apiKey without a webSocket factory ends every subscription with CONFIGURATION: a page authenticates with streamToken.

To run the examples, which are TypeScript files, use npx -y tsx src/big-trades.ts. To check their types, install typescript and @types/node (npm install -D typescript @types/node) and use the tsconfig.json of the Quickstart.

Indicator types

The SDK is generic: an indicator’s data is typed by the types you generate from the catalog (GET /v1/indicators, no authentication).

terminal
npx -p @fathom-charts/sdk@0.6.0 fathom-charts-types https://api.fathomcharts.com/v1/indicators src/fathom-charts-types.ts

Give the generator the same version as your @fathom-charts/sdk package (@0.6.0 here). The -p option also makes sure npx runs the generator of @fathom-charts/sdk, never a package of another publisher with the same command name.

  • What it generates: for each indicator, <Name>Params and <Name>Data, named after its id (big-trades → BigTradesParams, BigTradesData), plus IndicatorParams, IndicatorData and IndicatorId. The catalog descriptions become JSDoc comments; a footprint level is typed [number, number, number, number?] (the 4th element is optional).
  • Indicators with several kinds of objects (Fathom Zones, Fathom Opening): one type per kind, named after it, whose JSDoc gives the kind, its id pattern and its description (EffortZonesDataBar, EffortZonesDataEma, EffortZonesDataZone), and <Name>Data, their union. The id prefix tells the kind of an object: see the type guard below.
  • Input and output: the catalog URL or a file saved from GET /v1/indicators, then the file to write. The output folder is created if it does not exist, and an existing file is overwritten. Generate the file again when the catalog changes (its engineFingerprint changes with the computation).
  • Exit codes: nothing printed and code 0 when it succeeds. When it fails, one line, fathom-charts-types: <message>, and code 1; with wrong arguments, its usage and code 2. --help prints its usage.

The SDK itself takes params as Record<string, unknown>: it does not check them; the server does. To have the compiler check them too, use the generated types: params: { minimum: 30 } satisfies BigTradesParams.

To narrow the data of an object to its kind, test the prefix of its id in a type guard:

src/effort-zones.ts
import type { EffortZonesData, EffortZonesDataBar, EffortZonesDataZone } from './fathom-charts-types.js';

// The id tells the kind: bar:<weekSunday>:<index>, ema:<weekSunday>:<index>, zone:<weekSunday>:<startIndex>.
const isBar = (id: string, data: EffortZonesData): data is EffortZonesDataBar => id.startsWith('bar:');
const isZone = (id: string, data: EffortZonesData): data is EffortZonesDataZone => id.startsWith('zone:');

export function describe(id: string, data: EffortZonesData): string {
  if (isBar(id, data)) return `bar ${data.open} → ${data.close}`;
  if (isZone(id, data)) return `${data.side} zone ${data.low}–${data.high}${data.active ? ', active' : ''}`;
  return `EMA ${data.value}`;
}

After both guards, TypeScript knows the data is the remaining kind, EffortZonesDataEma. A test on a field only one kind has, such as 'close' in data for a bar, narrows the same way.

Real time: FathomChartsStream

src/big-trades.ts
import { FathomChartsStream } from '@fathom-charts/sdk';
import type { BigTradesData } from './fathom-charts-types.js';

const stream = new FathomChartsStream({
  url: 'wss://stream.fathomcharts.com/v1',
  apiKey: process.env.FATHOM_CHARTS_API_KEY!,
  onStateChange: (state) => console.log('connection', state),
});

const sub = stream.subscribe<BigTradesData>({
  instrument: 'NQ.front',
  indicator: 'big-trades',
  params: { minimum: 30 },
  mode: 'confirmed',
});

for await (const event of sub) {
  if (event.type === 'upsert') console.log(event.cursor, event.data.side, event.data.volume);
}

Options

OptionPurpose
urlRequired. The stream address: wss://stream.fathomcharts.com/v1. Anything other than an absolute ws:// or wss:// URL makes the constructor throw CONFIGURATION.
apiKeyAPI key, sent in the Authorization: Bearer header. Server-side only; requires the ws package unless you provide webSocket. A key with spaces or control characters around it (a .env file with Windows line endings leaves a \r) makes the constructor throw CONFIGURATION; the message never contains the key.
streamTokenIn a browser, instead of apiKey: a () => Promise<string> function that asks your server for a stream token and returns the token itself (with rest.streamToken(), its token field). It is called on every connection, reconnections included. Give exactly one of apiKey and streamToken, otherwise the constructor throws CONFIGURATION. See below for what happens when it fails.
webSocketOptional: a WebSocketFactory, a function (url, headers) that returns a WebSocketLike or a promise of one and opens the connection, to use an implementation other than ws or the browser’s WebSocket. headers holds the Authorization header with apiKey, undefined with streamToken. WebSocketLike is the part of the WebSocket API the SDK uses (readyState, send, close, the on… handlers, and pause, resume, terminate when the implementation has them, as ws does): a browser WebSocket and a ws socket both fit. A factory that imports ws itself needs its types under strict: npm install -D @types/ws.
reconnectOptional: initialDelayMs (first reconnection delay, 250 ms by default), maxDelayMs (backoff ceiling, 30 s), quotaRetryMs (how long a 4029 close code is retried, 120 s), quotaDelayMs (minimum delay between two attempts after a 4029, 5 s).
heartbeatTimeoutMsSilence after which the connection is considered lost, then reopened. 15,000 ms by default: the server sends an hb every 5 seconds.
highWaterMarkNumber of events waiting to be read, all subscriptions together, above which the SDK pauses reading the socket (with ws) and keeps only the latest version of each object in progress: intermediate versions of an object in progress may then be skipped, final versions and removals never are. While paused, the SDK sends ping messages (every third of heartbeatTimeoutMs, 5 s by default) so that the server keeps the connection; it reads again once the events waiting fall to half of highWaterMark. 10,000 by default.
maxBufferedWhen the socket cannot be paused (browsers, or Node’s built-in WebSocket): number of waiting events above which the SDK closes the connection (close code 4000, reason client buffer full; the state becomes reconnecting at once), then reopens it from the last cursor received once the events waiting fall to half of highWaterMark (5,000 by default). Nothing waiting is lost, and the resume follows the rules below: 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. 4 × highWaterMark by default.
randomOptional, for tests: the source of the jitter of reconnections and subscription retries, a function returning a number at least 0 and below 1. Math.random by default.
onStateChangeCalled on every change of connectionState. When the state becomes reconnecting, stream.lastClose already tells why the connection closed.
onNoticeCalled with each notice message from the server ({ kind, id?, effectiveAt?, endsAt?, message? }): a restart (reconnect, the SDK reconnects on its own), a maintenance window announced (maintenance) or cancelled (maintenance-cancelled). See Updates and maintenance.

streamToken is called before every connection. The SDK calls it again later, with backoff, when it fails with:

  • a network failure: the TypeError thrown by fetch itself (fetch failed, Failed to fetch…), or an error named TimeoutError (what AbortSignal.timeout() gives);
  • a FathomChartsError with code NETWORK_ERROR, RATE_LIMITED, CAPACITY or HTTP_429, or with a details.status of 500 or more.

Any other error ends every subscription: a FathomChartsError as is, any other error as CONFIGURATION (streamToken failed: …, with your error as cause). A bug in your function is not retried, even when it is a TypeError (Cannot read properties of undefined…): only the TypeError of fetch counts as a network failure. When your token server fails for a passing reason, throw a FathomChartsError with its status (see Errors): a plain Error on a 502 ends every subscription. A function that does not return a promise, or whose promise gives anything but a non-empty string without spaces around it, also ends them with CONFIGURATION.

When the connection cannot be opened

While the SDK retries, the loop receives nothing. Watch onStateChange (and stream.lastClose), so that a stream that cannot connect is not mistaken for a quiet market:

CaseWhat happens
Network down, server unreachable, wrong host nameRetried with backoff, without end: connectionState stays reconnecting. Bound the wait with your own timer if you need to.
streamToken fails with an error the SDK retries (above)Retried with backoff, without end, as above.
streamToken fails otherwise, or gives no usable tokenEvery subscription ends with that error, or CONFIGURATION.
Handshake refused with HTTP 429 or 5xxRetried with backoff.
Handshake refused with another HTTP 4xx (404 for a wrong url path)Every subscription ends with HTTP_<status>. Only with ws: a browser’s WebSocket and Node’s built-in one hide the status, and the SDK keeps retrying.
Every connection of your plan in use (close code 4029)Retried at least reconnect.quotaDelayMs apart for reconnect.quotaRetryMs, then every subscription ends with TOO_MANY_CONNECTIONS.
Key refused or revoked, rights missing (close codes 4001, 4003)Every subscription ends at once, without reconnecting: see CloseCode.

subscribe()

stream.subscribe<D>(options) opens a subscription and returns a Subscription object, to read with for await. Its options (SubscribeOptions) are those of the subscribe message: instrument, indicator, params ({} by default), mode (live by default) and from ("live" by default, { cursor, engine } or { time }). The SDK picks the sub name itself. The type D is the indicator’s data type (BigTradesData…).

Times are strings of Unix nanoseconds, never a number (it loses precision) nor a bigint (JSON has none): subscribe() throws CONFIGURATION at once for either, and nothing is sent. To build one from the clock:

src/last-hour.ts
import { FathomChartsStream } from '@fathom-charts/sdk';

const stream = new FathomChartsStream({ url: 'wss://stream.fathomcharts.com/v1', apiKey: process.env.FATHOM_CHARTS_API_KEY! });
// Unix nanoseconds, as a string: an hour ago.
const anHourAgo = (BigInt(Date.now() - 3_600_000) * 1_000_000n).toString();
const sub = stream.subscribe({ instrument: 'NQ.front', indicator: 'big-trades', from: { time: anHourAgo } });

for await (const event of sub) {
  if (event.type === 'snapshot') console.log('state an hour ago:', event.items.length, 'objects');
  if (event.type === 'upsert') console.log(event.cursor, event.data);
}

Starting in the past reads history: it needs the Historical plan, or, within the last 7 days, the Live plan or the Sandbox rights; beyond your plan’s depth, the subscription ends with FORBIDDEN. Only the part before midnight UTC today is charged, like a history query: the current UTC day is not.

subscribe() also throws CONFIGURATION, and sends nothing, when its message would be over the 65,536 bytes the server accepts (very large params): sent, it would close the connection of every subscription.

The loop receives events whose type field is the name of the server message (subscribed, snapshot, upsert, remove, status, reset, notice), and retrying (code, message, delayMs): see Events. After an error with a transient code (UPSTREAM_ERROR, CAPACITY, INTERNAL, SOURCE_DOWN), the loop goes on: it receives retrying, and the SDK subscribes again from the last cursor received. Any other error on the subscription ends the loop: for await throws a FathomChartsError carrying the received code.

Subscription

MemberPurpose
cursorThe cursor of the last event handed to you: your resume point. undefined until a cursor has arrived, also when you subscribed from: { cursor }: it is set by the first event or hb that carries one. An hb repeats the last cursor sent: it moves cursor forward only after a replay from history, to the end of the replay, when no event is waiting to be read. On a quiet stream, cursor stays on the last event.
topicThe topic of the latest subscribed (read-only).
engineThe engine of the latest subscribed (read-only): the computation your state comes from. Save it with cursor after a snapshot, upsert or remove to resume later.
idThe sub name the SDK chose for this subscription (s1, s2…).
requestThe options of subscribe(), completed with the default values (params, mode, from).
close()Stops the subscription: the SDK sends unsubscribe, and a pending loop ends.

Leaving the loop (break, return or an exception in its body) calls close().

Connection lifecycle

The connection opens on the first subscribe() and closes (1000, idle) when the last subscription closes; stream.close() closes everything, and a subscribe() after it throws CLOSED. connectionState is idle, connecting, open, reconnecting or closed (see Connection lifecycle). lastClose is the ConnectionClose ({ code, reason }) of the last close of an open connection, undefined until one closes: the server’s close frame (4029 TOO_MANY_CONNECTIONS when every connection of your plan is in use, for example), 1006 for a connection lost without one, or the SDK’s own close; it is set before onStateChange is called:

src/connection.ts
import { FathomChartsStream } from '@fathom-charts/sdk';

const stream = new FathomChartsStream({
  url: 'wss://stream.fathomcharts.com/v1',
  apiKey: process.env.FATHOM_CHARTS_API_KEY!,
  onStateChange: (state) => {
    if (state === 'reconnecting') console.log('reconnecting after', stream.lastClose?.code, stream.lastClose?.reason);
  },
});

Reconnection, resuming and close codes: see Connection lifecycle. When the SDK itself drops the connection (15 seconds without a message, or maxBuffered reached) before reconnecting, it uses close code 4000 (CloseCode.CLIENT_RECONNECT), and the state becomes reconnecting at once. A connection refused before it opens with an HTTP 4xx other than 429 (404 for a wrong url path) ends every subscription with HTTP_<status>: this needs ws, since a browser’s WebSocket does not give the status, and the SDK then retries with backoff. To resume after your process restarts, save sub.cursor and sub.engine and subscribe again with from: { cursor, engine }: see Resume after a restart.

Maintenance windows

stream.maintenance lists the maintenance windows announced on the connection and not over, by start: { id, startsAt, endsAt, message } (times in nanoseconds, as strings). Every new connection receives the windows already announced. See Updates and maintenance.

History: FathomChartsRest

src/rest.ts
import { FathomChartsRest } from '@fathom-charts/sdk';

const rest = new FathomChartsRest({ baseUrl: 'https://api.fathomcharts.com', apiKey: process.env.FATHOM_CHARTS_API_KEY! });
OptionPurpose
baseUrlRequired. The API address: https://api.fathomcharts.com. Anything other than an absolute http:// or https:// URL makes the constructor throw CONFIGURATION.
apiKeyRequired. API key, sent in the Authorization: Bearer header. Server-side only. The same checks as for the stream apply: missing, empty, or with spaces or control characters around it, the constructor throws CONFIGURATION.
fetchOptional: a fetch implementation to use instead of the platform’s.
rateLimitRetriesNumber of retries of a request the server did not process, or of a read that failed (see below). 3 by default.

Methods

Every method that reads history takes the query described on the History page (instrument, indicator, params, from, to, mode, and depending on the method limit, cursor, untilCursor, snapshot). 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. from and to are strings of Unix nanoseconds, as on the stream: a number (it loses precision) or a bigint makes the method throw CONFIGURATION, and nothing is sent. Every method takes an optional AbortSignal last (exportNdjson(): its signal option).

MethodReturns
page(query, signal?)One Page: { instrument, tickSizeNanos, snapshot?, items, next, computeUnits }.
pages(query, signal?)The pages one at a time, following next, as you read them.
history(query, signal?)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 }, then come the updates, each a Mutation (t is upsert or remove, with its cursor). The return type follows: a HistorySnapshot<D> or Mutation<D> with snapshot: true, Mutation<D> otherwise.
estimate(query, signal?)The cost estimate (Estimate), charging nothing. Takes the same query as page().
export(query, signal?)One export response: { body, contentType, filename, token }. body is the zstd-compressed file as is. To resume an interrupted export, call it again with the same query and resume: rest.export({ ...query, resume: { token, after } }), where after is the cursor of the last complete line received (an ExportResume).
exportNdjson(query, options?)The decompressed export, in chunks (Uint8Array) of whole lines, with automatic resume. See Exports.
streamToken(signal?)A browser stream token, { token, expiresAt }: expiresAt is its expiry, in Unix nanoseconds as a string (60 seconds after it was created).
usage(signal?)Your usage this month and your limits.
instruments(signal?){ instruments }: every instrument served, with symbol, alias, tickSizeNanos, status and updatedAt.
status(signal?){ engine: { state }, instruments, maintenance }: the state of the computation (up or down), of each instrument, and the maintenance windows announced.
indicators(signal?)The indicator catalog: { version, engineFingerprint, indicators }.

History elements keep the protocol’s field t (snapshot, upsert, remove), as the API sends them, while the events of a stream loop are told apart by type: test element.t in a history() loop and event.type in a subscription loop.

The options of exportNdjson(): signal, maxResumes (consecutive resumes without a new line before giving up, 5 by default) and resumeDelayMs (delay before the first resume, 1 s by default, doubled on each consecutive resume up to 30 s). If the very first request fails (network error or 5xx before the X-Export-Token header), exportNdjson() never sends it again: a new export would be charged again. It throws the error, and you decide. A resume refused with CURSOR_EXPIRED means the computation changed since the export started: the lines already received cannot be continued, start the export again.

Rate limit and retries

rateLimitRetries bounds the retries described in Rate limit and retries. An AbortSignal ends a call, and the wait for a retry, right away (ABORTED, with the signal’s reason as cause). It also ends a read in progress: after the abort, exportNdjson() delivers no more chunks and throws ABORTED, and reading the body of export() fails with ABORTED.

Types

The package exports the types of everything above, to import with import type { … } from '@fathom-charts/sdk'. The ones you meet most:

TypeWhat it is
SubscriptionThe class subscribe() returns (see Subscription).
StreamOptions, SubscribeOptionsThe options of new FathomChartsStream() and of subscribe().
StreamEvent<D>An event of a subscription loop, told apart by type.
From, ModeThe from and mode of a subscription.
Item<D>An object of a snapshot: { id, final, ts, data }.
Notice, NoticeKind, MaintenanceWindowA server notice (onNotice, notice events), its kind, and an entry of stream.maintenance.
ConnectionState, ConnectionClose, SourceState, ResetReasonThe values of connectionState, of lastClose, of status.state and of reset.reason.
WebSocketFactory, WebSocketLikeThe webSocket option, and the socket it returns.
RestOptions, RangeQuery, PageQueryThe options of new FathomChartsRest(); the query of export() and exportNdjson(), and that of page(), pages(), history() and estimate().
Page<D>, PageSnapshot<D>, Mutation<D>, HistorySnapshot<D>, ResolvedA page, its snapshot, one update, the snapshot element of history(), and the { instrument, tickSizeNanos } a page and an estimate resolve.
Estimate, Usage, Limits, Instrument, ServiceStatus, Catalog, StreamTokenWhat estimate(), usage(), instruments(), status(), indicators() and streamToken() return.
PlanCodeThe code of a plan (usage().plan).
CatalogIndicator, CatalogParam, CatalogObject, CatalogFieldAn indicator of the catalog, one of its parameters, the object it produces, and a field of that object.
ExportStream, ExportResume, ExportOptionsWhat export() returns, its resume, and the options of exportNdjson().
ErrorCode, ProblemFieldErrorA code of FathomChartsError, and one invalid field of its details.problem.errors.

The protocol’s messages are exported too (ServerMessage, ClientMessage, SubscribedMessage, HeartbeatMessage, PongMessage…), for code that reads the WebSocket without the SDK.

A history query typed as PageQuery keeps mode to its two values:

TS
import type { PageQuery } from '@fathom-charts/sdk';

const query: PageQuery = { instrument: 'NQZ6', indicator: 'big-trades', from: '1790256600000000000', to: '1790258100000000000', mode: 'confirmed' };

Errors

Every error the SDK throws, or ends a loop with, is a FathomChartsError; the error it stems from, if any, is its cause. Its fields:

FieldContent
codeThe stable error code: an API code (see Errors), an SDK code (below), or HTTP_<status> (HTTP_502, for example) for an HTTP error response without a problem+json document, or a stream connection refused with an HTTP 4xx.
messageA human-readable explanation. Over REST: the detail of the response, followed by each invalid field (<detail>: <path> <message>; …).
details.statusThe HTTP status, over REST.
details.closeCodeThe WebSocket close code, when the connection was closed.
details.retryAfterThe value of the Retry-After header, in seconds, when the response has one.
details.problemThe full problem+json document of the response, with errors when the API lists invalid fields; undefined when the response is not a problem+json document.
causeThe original error, when there is one: the signal’s reason, the error of fetch…

The constructor is public, so that your own functions can throw errors the SDK understands, such as a streamToken function reporting the status of your token server: new FathomChartsError(code, message, details?, options?). code is an ErrorCode or any string; details takes status, closeCode, retryAfter and problem, all optional; options.cause is the error it stems from.

src/token.ts
import { FathomChartsError } from '@fathom-charts/sdk';

export async function streamToken(): Promise<string> {
  const res = await fetch('/api/stream-token', { method: 'POST' });
  if (!res.ok) throw new FathomChartsError(`HTTP_${res.status}`, `token server answered ${res.status}`, { status: res.status });
  return (await res.json()).token;
}

The codes, the API’s and the SDK’s own, are listed in SDK errors and exported as ERROR_CODES. CONFIGURATION also covers, in TypeScript:

  • an invalid url or baseUrl, and an API key with spaces or control characters around it;
  • a time given as a number or a bigint (from, to, from.time), or any value JSON cannot carry, in a query or a subscription;
  • a subscription message over 65,536 bytes;
  • a streamToken function that is not async, gives no usable token, or fails for a reason that is not passing (see Options);
  • the ws package missing for an API key (or an API key in a browser build, without a webSocket factory), no WebSocket implementation, and zstd decompression missing for exportNdjson().

CloseCode

CloseCode names the WebSocket close codes, to compare with stream.lastClose?.code or error.details.closeCode:

MemberCodeWhat the SDK does
NORMAL1000Its own close: idle when the last subscription closes, client closed after stream.close(), failed after an error that ends every subscription.
PROTOCOL_ERROR, BINARY_NOT_SUPPORTED, INVALID_UTF8, MESSAGE_TOO_BIG1002, 1003, 1007, 1009The server refused a message, and would refuse it again: every subscription ends with an error whose code is the close reason, or PROTOCOL_ERROR without one.
RATE_LIMITED1008The client sent too many messages (see Limits): reconnects with backoff.
INTERNAL_ERROR1011Reconnects with backoff.
SERVICE_RESTART1012The server restarts (see Updates and maintenance): reconnects with backoff and resumes from the last cursors.
TRY_AGAIN_LATER1013Reconnects with backoff, at least 1 second later.
CLIENT_RECONNECT4000Its own close before it reconnects: no message for heartbeatTimeoutMs (heartbeat timeout) or maxBuffered reached (client buffer full).
UNAUTHORIZED4001Every subscription ends with UNAUTHORIZED, without reconnecting.
FORBIDDEN4003Every subscription ends with KEY_REVOKED, ENTITLEMENTS_CHANGED or FORBIDDEN, depending on the close reason, without reconnecting.
SLOW_CONSUMER4008Reconnects at once and resumes from the last cursors; with backoff when it happens again before the subscriptions are accepted.
TOO_MANY_CONNECTIONS4029Retries at least reconnect.quotaDelayMs apart for reconnect.quotaRetryMs, then every subscription ends with TOO_MANY_CONNECTIONS.

On 1006 (a connection lost without a close frame) and any other code, the SDK reconnects with backoff.

Cursors

compareCursors(a, b) compares two cursors <utcDay>.<rank>.<k> number by number and returns a negative number, zero or a positive number. Each of the three numbers is an unsigned 32-bit integer. A malformed cursor (numbers with leading zeros, a number above 4294967295, a missing field…) throws INVALID_PARAMETERS.

src/cursors.ts
import { compareCursors } from '@fathom-charts/sdk';

compareCursors('20720.111416.0', '20720.111417.0'); // < 0