Examples

Chart integration

Put the Fathom Zones and the Fathom Trades on a candlestick chart built with TradingView Lightweight Charts. The chart below is drawn by the code on this page, from 23 minutes of the NQ session of September 24, 2026.

What happened

The candles are the Fathom Zones range bars, the yellow line is their EMA, the boxes are the zones (blue for buying, coral for selling) and the dots are the large orders, sized by volume. Times are New York time; a zone’s time is when it appears, which is when its message arrives.

  • 13:12:17: a buying effort zone forms at 30762.00–30768.00.
  • 13:19:08 to 13:19:24: four large sell orders, of 159, 40, 252 and 87 contracts, hit the bid: 538 contracts in 16 seconds. Price goes through the buying zone, which ends.
  • 13:20:16: a selling effort zone forms at 30753.75–30762.50, where those sellers pushed price down.
  • 13:21 to 13:24: price comes back into the zone three times, up to 30761.00, and every bar closes back inside or below it, none above: the sellers defend the level.
  • 13:26:39: low at 30700.25, about 53 points below the zone in under three minutes.
  • 13:29:36: a buying effort zone forms just above the low, at 30716.25–30724.25, with large buy orders, and price rebounds to 30755.75.

The sample session

Download nq-2026-09-24.json (47 KB): NQZ6, from 13:08:00 to 13:31:30 New York time. For each indicator, it holds the objects that FathomChartsRest.history() yields for that range with snapshot: true: the state at the start of the range, then every change with its cursor. The snapshot holds the last bars before 13:08, so the chart starts a few minutes earlier. The Trading bot page replays the same file.

JSON
{
  "instrument": "NQZ6",
  "tickSizeNanos": "250000000",
  "from": "1790269680000000000",
  "to": "1790271090000000000",
  "subscriptions": {
    "effort-zones": {
      "params": { "rangeTicks": 40 },
      "mode": "live",
      "events": [
        { "t": "snapshot", "cursor": "20720.334600.4294967295", "items": [{ "id": "zone:2026-09-20:4375", "final": false, "ts": "1790269433958539505", "data": { "active": true, "high": 123172, "low": 123094, "side": "buy", "start": 4375 } }, "…"] },
        { "cursor": "20720.334627.0", "t": "upsert", "id": "bar:2026-09-20:4394", "final": true, "ts": "1790269680554218199", "data": { "close": 123174, "high": 123214, "low": 123174, "open": 123214, "start": "1790269671038696969" } }
      ]
    },
    "big-trades": { "params": { "maximum": 0, "minimum": 30, "priceMode": "last" }, "mode": "confirmed", "events": ["…"] }
  }
}

Prices are in ticks: Prices and timestamps explains how to convert them.

The snapshot cursor of the file is the position after the last trade before 13:08:00, where a history query gives the cursor of the last update published before from (see Cursors). The drawing does not use cursors.

Install

In an empty folder:

BASH
npm init -y
npm pkg set type=module
npm install @fathom-charts/sdk@0.6.0 lightweight-charts@5.2.1
npm install -D vite@8.3.4 typescript@7.0.2 @types/node@22
npx -p @fathom-charts/sdk@0.6.0 fathom-charts-types https://api.fathomcharts.com/v1/indicators fathom-charts-types.ts
curl -O https://fathomcharts.com/examples/nq-2026-09-24.json

These are the versions this page was tested with. The code needs Lightweight Charts v5: v4 has no addSeries() nor createSeriesMarkers(). In PowerShell, write curl.exe instead of curl.

The fifth command generates the indicator types, the last one downloads the sample. The files on this page sit next to each other, at the root of the folder. The code imports the generated types from ./fathom-charts-types.js, with the .js extension of the compiled file, although the file on disk is fathom-charts-types.ts: that is how TypeScript writes the imports of an ES module ("module": "nodenext"), and Vite and TypeScript both find the .ts file. The code runs in the browser: to check its types with npx tsc, this tsconfig.json adds the DOM and ES2023 (findLast):

JSON
{ "compilerOptions": { "module": "nodenext", "target": "es2023", "lib": ["es2023", "dom"], "types": ["node"], "strict": true, "noEmit": true, "skipLibCheck": true } }

The chart

sessionChart() creates the chart and returns a small object that you feed with the objects of both subscriptions: snapshot() replaces every object of a subscription, upsert() adds or replaces one, remove() deletes one. It redraws at most once per frame, so it takes a live stream as well as a whole session at once.

chart.ts
import {
  CandlestickSeries, LineSeries, createChart, createSeriesMarkers,
  type IPrimitivePaneView, type ISeriesPrimitive, type SeriesMarker, type Time,
} from 'lightweight-charts';
import type { BigTradesData, EffortZonesDataBar as Bar, EffortZonesDataEma as Ema, EffortZonesDataZone as Zone } from './fathom-charts-types.js';

type Indicator = 'effort-zones' | 'big-trades';
interface Item { id: string; data?: unknown }

const BUY = '#7c9bff';
const SELL = '#ff9989';
const clock = (ns: string) =>
  new Date(Number(BigInt(ns) / 1_000_000n)).toLocaleTimeString('en-US', { timeZone: 'America/New_York', hourCycle: 'h23' });

/**
 * A chart of Fathom Zones range bars, with their EMA, their zones and the Fathom Trades groups. Feed it the objects of both
 * subscriptions as they arrive: from the stream, from history, or from a saved session.
 */
export function sessionChart(container: HTMLElement, tickSizeNanos: string) {
  const tick = Number(tickSizeNanos) / 1e9;
  // The objects of each subscription, by id: what the snapshot gave, then each upsert and remove.
  const objects: Record<Indicator, Map<string, unknown>> = { 'effort-zones': new Map(), 'big-trades': new Map() };
  let bars = new Map<number, Bar>();
  let indices: number[] = [];
  let zones: Zone[] = [];

  // Range bars have no fixed duration: the horizontal axis is the bar index, labelled with the time of its first trade.
  const label = (time: Time) => {
    const bar = bars.get(time as number);
    return bar ? clock(bar.start) : '';
  };
  const chart = createChart(container, {
    autoSize: true,
    layout: { background: { color: '#080a10' }, textColor: '#a9b2cc', fontSize: 11 },
    grid: { vertLines: { color: '#151926' }, horzLines: { color: '#151926' } },
    rightPriceScale: { borderColor: '#222737' },
    timeScale: { borderColor: '#222737', tickMarkFormatter: label },
    localization: { timeFormatter: label, priceFormatter: (p: number) => p.toFixed(2) },
  });
  const candles = chart.addSeries(CandlestickSeries, {
    upColor: '#dfe6f8', downColor: '#6f7c9e', borderVisible: false, wickUpColor: '#dfe6f8', wickDownColor: '#6f7c9e',
  });
  const ema = chart.addSeries(LineSeries, {
    color: '#f2c48d', lineWidth: 1, priceLineVisible: false, lastValueVisible: false, crosshairMarkerVisible: false,
  });
  const markers = createSeriesMarkers(candles, []);

  // Each zone is a box over its bars: from bar `start` up to but not including bar `end`, or to the last bar while it is active.
  const boxes: ISeriesPrimitive<Time> = {
    paneViews: (): IPrimitivePaneView[] => [{
      zOrder: () => 'bottom',
      renderer: () => ({
        draw: (target) => target.useMediaCoordinateSpace(({ context: ctx }) => {
          const first = indices[0], last = indices[indices.length - 1];
          const x = (i: number) => chart.timeScale().timeToCoordinate(Math.min(Math.max(i, first), last) as Time);
          // Bar coordinates are their centres: a box runs from the left edge of its first bar to the right edge of its last.
          const half = chart.timeScale().options().barSpacing / 2;
          for (const z of zones) {
            const end = z.end === undefined ? last : z.end - 1;
            if (end < first) continue;
            const x1 = x(z.start), x2 = x(end);
            const y1 = candles.priceToCoordinate(z.high * tick), y2 = candles.priceToCoordinate(z.low * tick);
            if (x1 === null || x2 === null || y1 === null || y2 === null) continue;
            const color = z.side === 'buy' ? BUY : SELL;
            ctx.fillStyle = `${color}2e`;
            ctx.strokeStyle = color;
            ctx.fillRect(x1 - half, y1, x2 - x1 + 2 * half, y2 - y1);
            ctx.strokeRect(x1 - half, y1, x2 - x1 + 2 * half, y2 - y1);
          }
        }),
      }),
    }],
  };
  candles.attachPrimitive(boxes);

  let pending = 0;
  function draw() {
    pending = 0;
    // Fathom Zones publishes three kinds of objects, told apart by the id prefix: bar:, ema: and zone:<week>:<index>.
    bars = new Map();
    zones = [];
    const line: { time: Time; value: number }[] = [];
    for (const [id, data] of objects['effort-zones']) {
      const [kind, , index] = id.split(':');
      if (kind === 'bar') bars.set(Number(index), data as Bar);
      else if (kind === 'ema') line.push({ time: Number(index) as Time, value: (data as Ema).value * tick });
      else zones.push(data as Zone);
    }
    indices = [...bars.keys()].sort((a, b) => a - b);
    candles.setData(indices.map((i) => {
      const b = bars.get(i)!;
      return { time: i as Time, open: b.open * tick, high: b.high * tick, low: b.low * tick, close: b.close * tick };
    }));
    ema.setData(line.filter((p) => bars.has(p.time as number)).sort((a, b) => (a.time as number) - (b.time as number)));

    // A large order sits on the bar where it started, at its price; its size follows its volume.
    const list: SeriesMarker<Time>[] = [];
    for (const data of objects['big-trades'].values()) {
      const g = data as BigTradesData;
      const index = indices.findLast((i) => BigInt(bars.get(i)!.start) <= BigInt(g.start));
      if (index === undefined) continue;
      list.push({
        time: index as Time, position: 'atPriceMiddle', price: g.price * tick, shape: 'circle',
        color: g.side === 'buy' ? BUY : SELL, size: Math.sqrt(g.volume / 30), text: g.volume >= 100 ? String(g.volume) : undefined,
      });
    }
    markers.setMarkers(list.sort((a, b) => (a.time as number) - (b.time as number)));
  }
  // Updates come in bursts: one redraw per frame.
  const later = () => { pending ||= requestAnimationFrame(draw); };

  return {
    /** A snapshot replaces every object of its subscription. */
    snapshot(indicator: Indicator, items: Item[]) {
      objects[indicator] = new Map(items.map((item) => [item.id, item.data]));
      later();
    },
    upsert(indicator: Indicator, item: Item) {
      objects[indicator].set(item.id, item.data);
      later();
    },
    remove(indicator: Indicator, id: string) {
      objects[indicator].delete(id);
      later();
    },
    fit() {
      draw();
      chart.timeScale().fitContent();
    },
    destroy() {
      cancelAnimationFrame(pending);
      chart.remove();
    },
  };
}

A few choices worth knowing:

  • Bar index as time. A range bar closes after a fixed price range, not after a fixed duration, and several bars can open within the same second. The horizontal axis is therefore the bar index (the last segment of the bar: id), and its labels show the time of each bar’s first trade (start).
  • Zones are drawn in bars. A zone’s start and end are bar indices, and the zone covers bars start up to but not including end. A bar’s coordinate on the chart is its centre, so the box runs from the left edge of bar start to the right edge of bar end - 1. A zone still active has no end: its box runs to the last bar.
  • One type per kind of object. Fathom Zones publishes bars, EMA values and zones, told apart by the prefix of their id (bar:, ema:, zone:). The generated types name each kind (EffortZonesDataBar, EffortZonesDataEma, EffortZonesDataZone), and the code casts an object’s data once its prefix is known.
  • Each version replaces the previous one. An object in progress is sent again under the same id at each change (a zone active: true, then active: false with its end): the code keeps the objects in a Map by id, and an upsert replaces the entry.
  • Large orders on their starting bar. A group is placed on the last bar that opened before its start, at its price. In real time, a group that starts in the bar in progress, which is only published when it closes, first sits on the last published bar, then moves to its own bar when that bar closes.
  • Attribution. Lightweight Charts is licensed under Apache 2.0 and asks for a link to TradingView on pages that use it: the logo in the corner of the chart, shown by default (layout.attributionLogo), takes care of it. Also keep the contents of its NOTICE file with your code.

Load the sample

Save this code as main.ts, next to chart.ts and the sample file:

TS
import { sessionChart } from './chart.js';

type Event = { t: 'snapshot'; items: { id: string; data: unknown }[] } | { t: 'upsert' | 'remove'; id: string; data?: unknown };
interface Sample { tickSizeNanos: string; subscriptions: Record<'effort-zones' | 'big-trades', { events: Event[] }> }

const sample: Sample = await (await fetch('nq-2026-09-24.json')).json();
const chart = sessionChart(document.getElementById('chart')!, sample.tickSizeNanos);
for (const indicator of ['effort-zones', 'big-trades'] as const) {
  for (const e of sample.subscriptions[indicator].events) {
    if (e.t === 'snapshot') chart.snapshot(indicator, e.items);
    else if (e.t === 'upsert') chart.upsert(indicator, e);
    else chart.remove(indicator, e.id);
  }
}
chart.fit();

Then save this page as index.html. Its empty icon keeps the browser from requesting a /favicon.ico that the folder does not have, so the console stays free of errors:

HTML
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Chart</title>
    <link rel="icon" href="data:,">
  </head>
  <body>
    <div id="chart" style="height: 420px"></div>
    <script type="module" src="/main.ts"></script>
  </body>
</html>

Serve the folder with npx vite and open the address it prints. Vite compiles main.ts on the fly.

Go live

The same chart follows the real-time stream. It needs the Live plan: on the Sandbox, a key receives data delayed by 10 minutes. Both subscriptions also use parameters other than the NQ defaults (rangeTicks: 40, minimum: 30; the defaults are on each indicator page), so they count as two custom configurations. The Sandbox allows one, and one connection: there, the second subscription is refused with QUOTA_EXCEEDED and live.ts stops. To try the page on the Sandbox, keep one indicator, or leave its parameters at their defaults.

In a browser, the SDK opens the connection with a stream token that your server requests with its key. Next to the files of the sample, add:

  1. token-server.ts, the Node token server of Browser access. Run it in a second terminal where FATHOM_CHARTS_API_KEY is set (see Quickstart for PowerShell and cmd), with npx -y tsx@4.23.15 token-server.ts. It listens on port 3000.

  2. vite.config.ts, so that Vite forwards the /api requests of the page to that server:

    TS
    import { defineConfig } from 'vite';
    
    export default defineConfig({ server: { proxy: { '/api': 'http://localhost:3000' } } });
  3. live.ts, the code below.

  4. live.html, a copy of index.html that loads /live.ts instead of /main.ts.

Start npx vite again, so that it reads vite.config.ts, then open /live.html at the address it prints.

TS
import { FathomChartsError, FathomChartsStream } from '@fathom-charts/sdk';
import { sessionChart } from './chart.js';

const stream = new FathomChartsStream({
  url: 'wss://stream.fathomcharts.com/v1',
  streamToken: async () => {
    const response = await fetch('/api/fathom-charts-token', { method: 'POST' });
    // A 5xx or 429 from your server is retried like a network error; any other status ends the subscriptions.
    if (!response.ok) {
      const code = response.status === 429 ? 'RATE_LIMITED' : `HTTP_${response.status}`;
      throw new FathomChartsError(code, `token request failed: ${response.status}`, { status: response.status });
    }
    const { token } = (await response.json()) as { token: string };
    return token;
  },
});

let chart: ReturnType<typeof sessionChart> | undefined;

async function follow(indicator: 'effort-zones' | 'big-trades', params: Record<string, unknown>) {
  for await (const event of stream.subscribe({ instrument: 'NQ.front', indicator, params })) {
    if (event.type === 'subscribed') chart ??= sessionChart(document.getElementById('chart')!, event.tickSizeNanos);
    else if (event.type === 'snapshot') { chart!.snapshot(indicator, event.items); chart!.fit(); }
    else if (event.type === 'upsert') chart!.upsert(indicator, event);
    else if (event.type === 'remove') chart!.remove(indicator, event.id);
  }
}

await Promise.all([follow('effort-zones', { rangeTicks: 40 }), follow('big-trades', { minimum: 30 })]);

If the token server is down or fails, the Vite proxy or the server responds with a 5xx status: the SDK retries with a growing delay (connection state reconnecting) and the chart appears once the server is back. A 4xx status, such as a 401 from your session check, ends the subscriptions with the error thrown by streamToken (code HTTP_401, token request failed: 401), shown in the browser console, and the chart is not drawn (see Browser access).

  • After a reset, the SDK hands you a new snapshot: snapshot() replaces the objects, nothing else to do.
  • The Fathom Zones snapshot keeps the last 32 final objects, bars and EMA values included: the chart starts with a few bars. To open on more of the session, see below.

Open on the whole session

The snapshot of a live subscription only holds the latest objects. To draw the session from its start, then follow the market, start the subscriptions in the past: you receive the state at that time, everything since, then live data, with no gap and no duplicate (see Starting in the past). In live.ts, give the subscriptions of follow() a from:

TS
// Midnight UTC today, in Unix nanoseconds, as a string.
const midnight = new Date();
midnight.setUTCHours(0, 0, 0, 0);
const from = { time: (BigInt(midnight.getTime()) * 1_000_000n).toString() };

async function follow(indicator: 'effort-zones' | 'big-trades', params: Record<string, unknown>) {
  for await (const event of stream.subscribe({ instrument: 'NQ.front', indicator, params, from })) {
    // The same loop as above.
  }
}

This 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: from midnight UTC, as here, nothing is. An earlier from.time works the same way, and its days before today are charged.

The history REST API needs your key, so a page cannot call it: to load older days from history, have your server query them with snapshot: true up to midnight UTC today, the end of the completed days (to), and send them to the page. Feed them to the chart (snapshot(), then upsert() and remove()), then subscribe with from: { time: <that midnight> }. The stream’s first snapshot is the state at that midnight, already drawn: give its objects to upsert() instead of snapshot(), which would replace the older objects with the snapshot’s few latest ones. See Hand off to real time.

  • A large order arrives as soon as it reaches minimum and grows while it keeps filling (live mode): the dot grows with it. With mode: 'confirmed', it only appears once final.