Examples

Trading bot

A Node.js bot that reads two subscriptions, Fathom Zones and Fathom Trades, and takes a trade when price rejects a zone that large orders helped form. The same code replays a saved session or history, or follows the real-time stream.

This page shows how to wire indicators into automated decisions, not a strategy to trade. The rule is deliberately simple and is shown on a single stretch of session, picked because the indicators read it well: it is not a backtest and proves nothing about future results. Any order your code sends is your decision and your risk.

The rule

  • A backed zone. An effort zone counts when large orders on its side add up to at least 200 contracts, counting the orders that ended in the 120 seconds before it appears: the push that formed it was driven by large players.
  • A rejection. On each final range bar after the bar that created the zone, if the bar went into a backed zone, touching its edge is enough, and closed back outside it, on the side the zone defends (below a selling zone, above a buying zone), the bot enters at the close of that bar.
  • The exit. Stop 2 ticks beyond the far edge of the zone, target at twice the risk. The bot exits at the close of the bar that reached the stop or the target; when one bar reaches both, it assumes the stop.
  • One trade at a time, one trade per zone. While a position is open, the bot looks at no zone: a zone rejected meanwhile is not used up, and can still trigger later. A zone that is no longer active is forgotten.

Every input comes from the indicators: the zones and the range bars from Fathom Zones, the large orders from Fathom Trades. The bot computes nothing on the trades themselves.

Install

In an empty folder:

BASH
npm init -y
npm pkg set type=module
npm install @fathom-charts/sdk@0.6.0 ws
npm install -D tsx@4.23.15 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. In PowerShell, write curl.exe instead of curl. The fifth command generates the indicator types, the last one downloads the sample session. 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 tsx and tsc both find the .ts file. tsx runs them without checking types; to check them with npx tsc, add this tsconfig.json, the same as on Chart integration:

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

The strategy

The strategy knows nothing about the network: it receives the objects of both subscriptions and calls onEntry and onExit. load() takes a snapshot, update() an upsert, remove() a remove. Prices are in ticks, as the indicators publish them.

strategy.ts
import type { BigTradesData, EffortZonesData, EffortZonesDataBar as Bar, EffortZonesDataZone as Zone } from './fathom-charts-types.js';

type Side = 'buy' | 'sell';

/** An object of either subscription, as the stream and the history deliver it. */
export type Update =
  | { indicator: 'effort-zones'; id: string; ts: string; data: EffortZonesData }
  | { indicator: 'big-trades'; id: string; ts: string; data: BigTradesData };

/** Prices in ticks, times in Unix nanoseconds. */
export interface Entry { side: Side; price: number; stop: number; target: number; zone: string; ts: string }
export interface Exit { reason: 'stop' | 'target'; price: number; ticks: number; ts: string }

export const RULES = {
  /** Large-order volume on the zone's side, in contracts, in the 120 seconds before the zone appears. */
  pressure: 200,
  pressureWindowNs: 120_000_000_000n,
  /** Stop beyond the far edge of the zone, in ticks. */
  stopTicks: 2,
  /** Target, as a multiple of the risk. */
  reward: 2,
};

/** Fades the first rejection of an effort zone that large orders helped form. One trade at a time, one per zone. */
export class ZoneRetest {
  private zones = new Map<string, { zone: Zone; createdNs: bigint }>();
  private groups = new Map<string, BigTradesData>();
  private traded = new Set<string>();
  private position?: Entry;

  constructor(private readonly onEntry: (e: Entry) => void, private readonly onExit: (e: Exit) => void) {}

  /** A snapshot replaces everything known from that subscription. Past bars place no order. */
  load(indicator: Update['indicator'], items: { id: string; ts: string; data: unknown }[]) {
    if (indicator === 'big-trades') this.groups.clear();
    else this.zones.clear();
    for (const item of items) this.update({ indicator, ...item } as Update, false);
  }

  update(u: Update, live = true) {
    if (u.indicator === 'big-trades') {
      this.groups.set(u.id, u.data);
      return;
    }
    const [kind, , index] = u.id.split(':');
    if (kind === 'zone') {
      const zone = u.data as Zone;
      if (!zone.active) this.zones.delete(u.id);
      else if (!this.zones.has(u.id)) this.zones.set(u.id, { zone, createdNs: BigInt(u.ts) });
    } else if (kind === 'bar' && live) {
      this.onBar(u.data as Bar, Number(index), u.ts);
    }
  }

  remove(indicator: Update['indicator'], id: string) {
    if (indicator === 'big-trades') this.groups.delete(id);
    else this.zones.delete(id);
  }

  private onBar(bar: Bar, index: number, ts: string) {
    this.prune(BigInt(ts));
    const p = this.position;
    if (p) {
      const sell = p.side === 'sell';
      // The bar does not say which came first: the stop is assumed.
      const stopped = sell ? bar.high >= p.stop : bar.low <= p.stop;
      const reached = sell ? bar.low <= p.target : bar.high >= p.target;
      if (stopped || reached) {
        const price = stopped ? p.stop : p.target;
        this.position = undefined;
        this.onExit({ reason: stopped ? 'stop' : 'target', price, ticks: sell ? p.price - price : price - p.price, ts });
      }
      return;
    }
    for (const [id, { zone, createdNs }] of this.zones) {
      if (this.traded.has(id) || index <= zone.start || this.pressure(zone.side, createdNs) < RULES.pressure) continue;
      const sell = zone.side === 'sell';
      // Price came back into the zone and the bar closed back outside it, on the side the zone defends.
      const rejected = sell ? bar.high >= zone.low && bar.close < zone.low : bar.low <= zone.high && bar.close > zone.high;
      if (!rejected) continue;
      this.traded.add(id);
      const stop = sell ? Math.ceil(zone.high) + RULES.stopTicks : Math.floor(zone.low) - RULES.stopTicks;
      const risk = Math.abs(stop - bar.close);
      const target = sell ? bar.close - RULES.reward * risk : bar.close + RULES.reward * risk;
      this.position = { side: zone.side, price: bar.close, stop, target, zone: id, ts };
      this.onEntry(this.position);
      return;
    }
  }

  /** Volume of the large orders on `side` that ended in the window before `ns`. */
  private pressure(side: Side, ns: bigint) {
    let volume = 0;
    for (const g of this.groups.values()) {
      const end = BigInt(g.end);
      if (g.side === side && end <= ns && ns - end <= RULES.pressureWindowNs) volume += g.volume;
    }
    return volume;
  }

  /** Keeps the large orders an active zone can still count. */
  private prune(now: bigint) {
    let oldest = now;
    for (const { createdNs } of this.zones.values()) if (createdNs < oldest) oldest = createdNs;
    for (const [id, g] of this.groups) if (oldest - BigInt(g.end) > RULES.pressureWindowNs) this.groups.delete(id);
  }
}

Fathom Zones publishes its bars, its EMA values and its zones in the same subscription: the bot tells them apart by the id prefix (bar:, ema:, zone:), reads the bar index from its last segment, and casts the data to the generated type of that kind (EffortZonesDataBar, EffortZonesDataZone). A zone in progress is sent again under the same id at each change: the bot keeps it while it is active and forgets it once it is final. A bar of the snapshot is already in the past: load() keeps the zones it describes but places no order on it.

Replay a session

The sample session nq-2026-09-24.json (47 KB, described on Chart integration), downloaded by the last install command, sits next to the code. replay() hands the events of a session to the strategy in the order the trades produced them: both snapshots first, then every change sorted by cursor. Cursors of the same instrument compare across indicators.

replay.ts
import { compareCursors, type HistorySnapshot, type Mutation } from '@fathom-charts/sdk';
import { ZoneRetest, type Update } from './strategy.js';

type Indicator = Update['indicator'];

/** A session: per indicator, what `history()` yields with `snapshot: true` (the snapshot first, then every change). */
export interface Sample {
  instrument: string;
  tickSizeNanos: string;
  subscriptions: Record<Indicator, { events: (HistorySnapshot | Mutation)[] }>;
}

/** Runs the strategy over a session and prints its trades. */
export function replay(sample: Sample) {
  const tick = Number(sample.tickSizeNanos) / 1e9;
  const price = (ticks: number) => (ticks * tick).toFixed(2);
  const clock = (ns: string) => new Date(Number(BigInt(ns) / 1_000_000n)).toLocaleTimeString('en-US', { timeZone: 'America/New_York', hourCycle: 'h23' });

  const strategy = new ZoneRetest(
    (e) => console.log(`${clock(e.ts)} ${e.side.toUpperCase()} ${price(e.price)}, stop ${price(e.stop)}, target ${price(e.target)} (${e.zone})`),
    (e) => console.log(`${clock(e.ts)} ${e.reason} at ${price(e.price)}: ${e.ticks > 0 ? '+' : ''}${e.ticks} ticks`),
  );

  // The state at the start of the range, then every change in cursor order: the order of the trades that produced them.
  const mutations: [Indicator, Mutation][] = [];
  for (const indicator of ['effort-zones', 'big-trades'] as const) {
    for (const e of sample.subscriptions[indicator].events) {
      if (e.t === 'snapshot') strategy.load(indicator, e.items);
      else mutations.push([indicator, e]);
    }
  }
  mutations.sort(([, a], [, b]) => compareCursors(a.cursor, b.cursor));
  for (const [indicator, m] of mutations) {
    if (m.t === 'remove') strategy.remove(indicator, m.id);
    else strategy.update({ indicator, id: m.id, ts: m.ts, data: m.data } as Update);
  }
}

replay-file.ts runs it on the downloaded file:

replay-file.ts
import { readFileSync } from 'node:fs';
import { replay, type Sample } from './replay.js';

const sample: Sample = JSON.parse(readFileSync(process.argv[2] ?? 'nq-2026-09-24.json', 'utf8'));
replay(sample);
BASH
npx -y tsx replay-file.ts
TEXT
13:21:38 SELL 30743.75, stop 30763.00, target 30705.25 (zone:2026-09-20:4431)
13:27:05 target at 30705.25: +154 ticks

At 13:19, four large sell orders (538 contracts in 16 seconds) break a buying zone. The selling zone they leave at 30753.75–30762.50 is backed. At 13:21:38, a bar reaches 30753.75 and closes at 30743.75: the bot sells. Price comes back up to 30761.00, below the stop, then falls: the target is reached during the bar that closes at 13:27:05. The times are those of bar closes, when the bot learns of them: the bar does not say when inside it price touched the target. The six other zones in this stretch never trigger: none of them is backed, with at most 153 contracts of large orders on its side before it appears.

Replay history

To run the bot over another period, take the events from history instead of the file: the pages of a query with snapshot: true hold the same elements as the events of the sample, the ones history() yields, and the tick size of the contract. replay-history.ts rebuilds the sample stretch that way and prints the same two lines.

Plan and cost. September 24, 2026 is beyond the 7 days of the Sandbox: this script needs the Historical plan. It sends two queries, each charged 17,561 compute units (the trades of the range), 35,122 in all. Estimate a longer period first, for free.

replay-history.ts
import { FathomChartsRest, type HistorySnapshot, type Mutation, type PageQuery } from '@fathom-charts/sdk';
import { replay } from './replay.js';

const rest = new FathomChartsRest({ baseUrl: 'https://api.fathomcharts.com', apiKey: process.env.FATHOM_CHARTS_API_KEY! });

// The same stretch as the sample file: NQZ6, September 24, 2026, 13:08:00 to 13:31:30 New York time.
const range = { instrument: 'NQZ6', from: '1790269680000000000', to: '1790271090000000000', snapshot: true };

/**
 * One indicator over the range, read page by page: what `history()` yields (the snapshot first, then every change), and the
 * tick size of the contract the pages resolve.
 */
async function session(query: PageQuery) {
  const events: (HistorySnapshot | Mutation)[] = [];
  let tickSizeNanos = '';
  for await (const page of rest.pages(query)) {
    tickSizeNanos = page.tickSizeNanos;
    if (page.snapshot) events.push({ t: 'snapshot', ...page.snapshot });
    events.push(...page.items);
  }
  return { tickSizeNanos, events };
}

const zones = await session({ ...range, indicator: 'effort-zones', params: { rangeTicks: 40 } });
const trades = await session({ ...range, indicator: 'big-trades', params: { minimum: 30 }, mode: 'confirmed' });
replay({ instrument: range.instrument, tickSizeNanos: zones.tickSizeNanos, subscriptions: { 'effort-zones': zones, 'big-trades': trades } });
BASH
npx -y tsx replay-history.ts

For another period, change range, within completed UTC days: REST history stops at midnight UTC, and a range that touches the current UTC day is rejected with 402 NOT_COVERED. To continue up to now, see From history to real time.

Go live

live.ts opens both subscriptions on one connection and hands their events to the same strategy.

live.ts
import { FathomChartsStream, type SubscribeOptions } from '@fathom-charts/sdk';
import { ZoneRetest, type Update } from './strategy.js';

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

let tick = 0;
const price = (ticks: number) => (ticks * tick).toFixed(2);

const strategy = new ZoneRetest(
  (e) => {
    console.log(`${e.side.toUpperCase()} ${price(e.price)}, stop ${price(e.stop)}, target ${price(e.target)}`);
    // Send the order to your broker here: your code, your account, your risk.
  },
  (e) => console.log(`${e.reason} at ${price(e.price)}: ${e.ticks > 0 ? '+' : ''}${e.ticks} ticks`),
);

async function follow(indicator: Update['indicator'], options: Omit<SubscribeOptions, 'instrument' | 'indicator'>) {
  for await (const event of stream.subscribe({ instrument: 'NQ.front', indicator, ...options })) {
    switch (event.type) {
      case 'subscribed': tick = Number(event.tickSizeNanos) / 1e9; break;
      case 'snapshot': strategy.load(indicator, event.items); break;
      case 'upsert': strategy.update({ indicator, id: event.id, ts: event.ts, data: event.data } as Update); break;
      case 'remove': strategy.remove(indicator, event.id); break;
      case 'status': console.log(indicator, event.state); break;
      // A snapshot follows a reset: load() then replaces the state.
    }
  }
}

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

Run it in a terminal where FATHOM_CHARTS_API_KEY is set (see Quickstart for PowerShell and cmd):

BASH
npx -y tsx live.ts

It needs the Live plan. Both subscriptions 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, the rights of a key without a plan, allows one, and one connection: there, the second subscription is refused with QUOTA_EXCEEDED and live.ts stops, and it cannot run at the same time as the chart of Chart integration.

Besides entries and exits, it prints the connection state and the status of each subscription: warming while the computation gets ready, then live, or market_closed while the market is closed (see Stream status). Once both are live, the stream is live, even if nothing else is printed until the first trade: the rule is rare.

  • Large orders in confirmed mode. The bot only needs final groups: it receives each one once, when it is complete.
  • Fathom Zones in live mode. A zone is published in progress as soon as it is created, so the bot can act on it before it ends. Bars are always published once, final, at their close.
  • Two subscriptions, two orders. Each subscription delivers its events in cursor order, but, unlike replay(), which sorts both by cursor, nothing orders the events of one subscription against those of the other. A large order arrives once final, sometimes after the zone it backs. The strategy adds up the large orders at each bar, so one that arrives before the bar that tests the zone closes still counts.
  • The start. The Fathom Trades snapshot holds at most the last 32 groups. When the bot starts, an active zone formed before them may lack some of its large orders, and be skipped where the replay would take it. Start in the past to fill it (below).
  • Reconnections. The SDK resumes from the last cursor on its own. After a reset, a new snapshot follows and load() replaces the state.
  • Without a plan, a key receives the stream delayed by 10 minutes, with the limits of the Sandbox: one custom configuration, so leave one indicator at its defaults to try the bot with it. Trading needs the real-time stream of the Live plan.
  • Orders. Sending the order to your broker, its sizing and its confirmation are yours to write, where live.ts says so.

From history to real time

To continue a replay up to now, subscribe from where history stops: replay-history.ts ends at midnight UTC at the latest, and from: { time: <that midnight> } replays the current UTC day, then follows the market with no gap (see Starting in the past). The bot must not trade the past: until the status that follows the snapshot and its replay, it updates its state without placing orders (the second argument of update()). In live.ts:

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() };
// The subscriptions still replaying the past: they place no order.
const replaying = new Set<Update['indicator']>();

async function follow(indicator: Update['indicator'], options: Omit<SubscribeOptions, 'instrument' | 'indicator'>) {
  for await (const event of stream.subscribe({ instrument: 'NQ.front', indicator, from, ...options })) {
    switch (event.type) {
      case 'subscribed': tick = Number(event.tickSizeNanos) / 1e9; break;
      case 'snapshot': replaying.add(indicator); strategy.load(indicator, event.items); break;
      case 'upsert': strategy.update({ indicator, id: event.id, ts: event.ts, data: event.data } as Update, replaying.size === 0); break;
      case 'remove': strategy.remove(indicator, event.id); break;
      case 'status': replaying.delete(indicator); console.log(indicator, event.state); break;
    }
  }
}

Starting in the past reads history: it needs the Historical plan, or, within the last 7 days, the Live plan or the Sandbox rights; real time needs the Live plan. Only the part before midnight UTC today is charged: from midnight UTC, as here, nothing is. It also gives the strategy the large orders of the whole day, which the snapshot alone does not.