History
Compute an indicator over a past range, with the same parameters as in real time. You get exactly what the real-time stream published at that moment.
History requires the Historical plan, or the last 7 days with the Live plan or the Sandbox rights (a key without a plan), and a key with the history scope. With the Live plan, history that starts within the last 7 days consumes no compute budget.
from and to select updates by the time our servers received them (reception time), not objects. A one-minute footprint query from 13:30 to 13:55 UTC returns the 13:29 bar, published by the first trade at 13:30. It does not return the 13:54 bar, published after to. To get every bar of a range, extend to by one bar.
The same goes for the end of a session: its last bar, and the objects it completes, are published by the first trade of the 18:00 New York reopen. A range that ends at the 17:00 close does not contain them; in confirmed mode, an object still in progress at to is missing entirely.
Make a query
curl https://api.fathomcharts.com/v1/indicator-queries \
-H "Authorization: Bearer $FATHOM_CHARTS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"instrument":"NQZ6","indicator":"big-trades","params":{"minimum":30},"from":"1790256600000000000","to":"1790258100000000000"}'The curl examples on this page are written for bash (macOS, Linux, Git Bash on Windows). In PowerShell, write curl.exe and send the body from a file with -d "@query.json", as in the Quickstart: Windows PowerShell 5.1 strips the quotes of a JSON argument passed to a program, and the API then responds with 400 INVALID_PARAMETERS (The body is not valid JSON).
| Field | Required | Description |
|---|---|---|
instrument | yes | A specific contract (NQZ6) or the front month (NQ.front), as in real time. Case-sensitive: nqz6 is rejected with 404 UNKNOWN_INSTRUMENT. An expired contract (NQU6) can still be queried. Over a past range, a symbol designates the contract listed under it at from, and an alias the contract it pointed to then (see Available range). |
indicator | yes | The indicator id from the catalog. |
params | no | The indicator parameters, exactly as in real time. |
from, to | yes | Start (inclusive) and end (exclusive) of the range: a timestamp in nanoseconds since January 1, 1970 UTC, as a string. The range is bounded by the time our servers received the trades (reception time), which trails their market time (ts) by a few milliseconds to a few tens of milliseconds. Here, 13:30 to 13:55 UTC on September 24, 2026. |
mode | no | live (default): every version published live, intermediate ones (final: false) included. confirmed: only the final versions (final: true). As on the WebSocket, at the same cost. |
snapshot | no | true: the first page also carries the state of the objects at from. See State at the start of the range. |
limit | no | Maximum number of results per page, from 1 to 10,000. Default: 1,000. A page is also bounded in size: with large objects, it holds fewer (see Next pages). |
cursor | no | To get the next page: the next value of the previous page. |
untilCursor | no | Stops the query at this cursor, inclusive, before to if needed. |
from and to must be Unix nanoseconds, from 1000000000000000000 to 18446744073709551615, with from not in the future and to after from. Otherwise the query is rejected with 400 INVALID_PARAMETERS, and errors gives the field and the rule ({"path":"/from","message":"must be Unix nanoseconds, from 1000000000000000000 to 18446744073709551615"}, must not be in the future, must be after from). A value in seconds or milliseconds is therefore rejected right away.
The query is rejected with 403 FORBIDDEN if your plan does not cover the requested range: no history included, a range older than your plan allows, or a range ending within the last 10 minutes while your data is delayed. It is rejected with 402 NOT_COVERED if the data itself is not available: see Available range.
Read the response
{
"instrument": "NQZ6",
"tickSizeNanos": "250000000",
"items": [
{"cursor":"20720.111416.0","t":"upsert","id":"1790256600533489285:0","final":false,"ts":"1790256600533489285","data":{"side":"sell","volume":31,"trades":15,"start":"1790256600533489285","end":"1790256600533489285","first":122041,"last":122027,"price":122027,"vwap":122034.25806451614}},
{"cursor":"20720.111417.0","t":"upsert","id":"1790256600533489285:0","final":false,"ts":"1790256600533489285","data":{"side":"sell","volume":34,"trades":16,"start":"1790256600533489285","end":"1790256600533489285","first":122041,"last":122026,"price":122026,"vwap":122033.5294117647}}
],
"next": null,
"computeUnits": 46811
}Above, the first two of the 323 items of this range (next is null: everything fits in one page).
instrument: the contract actually read. With an alias such asNQ.front, it is the contract the alias designated atfrom(the front month at that time), not today’s. The whole range reads that contract, even if it crosses a rollover: for a long range, make one query per contract. A contract symbol is reused every 10 years:NQU6is September 2016, then September 2026. A raw symbol also reads the contract listed atfrom, soNQU6with afromin 2016 reads the 2016 contract;tickSizeNanos: the tick size of that contract in billionths of a point, as a string ("250000000"= 0.25);items: the updates, in order, in the same shape as in real time;next: send it back to get the next page, ornullonce everything has been served;computeUnits: what this page cost against your compute budget.
Each item holds:
| Field | Content |
|---|---|
t | upsert (the object is created or entirely replaced) or remove (it is deleted). |
cursor | The position of the update in the stream, the same as in real time. See Cursors. |
id | The stable id of the object. |
final | true for the last version of the object, false while it can still change. |
ts | The market time of the trade that produced this version, in nanoseconds, as a string. Since the range is bounded by reception time, the first items can have a ts a few milliseconds to a few tens of milliseconds before from. A version produced by a session open (closing bar of the previous session, objects completed by the Sunday reset) carries the time of the first trade of that open, often exactly 18:00:00.000000000 New York time. |
data | The object data, described on the indicator page. Absent from a remove. |
In live mode, history contains every version published live, including intermediate ones (final: false). Above, the cluster of sell trades shows up as soon as it crosses the 30-contract threshold, then is republished on every trade that extends it, up to its final version (66 contracts, final: true). If you only care about the finished result, send "mode": "confirmed": you only receive the final versions, at the same cost. An object still in progress at to then does not appear: its final version comes after to.
Objects that started before from are computed exactly as they were live, at no extra cost. Such an object only appears in items if it changes during the range: a zone opened before from and updated during it appears exactly as it did live, a zone opened before from and left unchanged does not. To get those objects as well, ask for the state at the start of the range.
An empty list (items: [] and next: null) means the computation ran and found nothing in the range, for example no large order above the minimum threshold. It is never a disguised error: if data is missing you get 402 NOT_COVERED.
State at the start of the range
With "snapshot": true, the first page also carries a snapshot field: the state of the objects at from, like the snapshot of a subscription.
{
"instrument": "NQZ6",
"tickSizeNanos": "250000000",
"snapshot": { "cursor": "20720.110992.0", "items": [ … ] },
"items": [ … ],
"next": null,
"computeUnits": 46811
}snapshot.items: first the objects in progress atfrom, those that can still change or be removed, such as all thekey-levelslevels. Then the last 32 completed objects of the period of the last trade beforefrom, exactly as in a subscription snapshot. Each item is shaped{id, final, ts, data}, withouttorcursor. Inconfirmedmode, only the objects in their final version are included;snapshot.cursor: the position of this state in the stream, that is the cursor of the last update published beforefrom, as for a subscription snapshot. Theitemsthat follow all come after it. A subscription that starts at the same time (from: {"time": …}) can give the same state another cursor: when nothing was published between midnight UTC and that time, its snapshot carries<previous utcDay>.<rank>.4294967295, the position after the last trade of the previous UTC day. Both resume at the same point.
Start from the snapshot, then apply the items in order: you get exactly the state a client subscribed live had. Later pages carry no snapshot. The snapshot is free. With the SDK, rest.history()rest.history()rest.HistoryAsync()rest.history() first yields the snapshot, then the updates.
Next pages
As long as next is not null, send the same query again with "cursor": "<value of next>".
- A page can hold fewer than
limitresults, or none at all, before the range is done: onlynext: nullmarks the end. A page is also bounded in size (about 4 MB) and in computation time (about 10 seconds): onfootprint, where every bar carries all its levels, a page requested withlimit: 10000can come back with fewer results, how many depending ontimeframe,groupTicksand the activity of the market. Always follownext. nextis signed: it is only valid for your account and for the same query (sameinstrument,indicator,params,from,to,modeanduntilCursor). Forinstrument, another symbol or alias that designates the same contract atfromcounts as the same: anextreceived withNQ.frontis valid withNQZ6ifNQ.frontdesignatedNQZ6atfrom. Otherwise the query is rejected with400 INVALID_PARAMETERS.limitmay change from one page to the next.- Each page is computed and charged when you request it: sending the same
nextagain computes and charges that page again. - After an update to how the indicator is computed, a
nextreceived before it is rejected with410 CURSOR_EXPIRED: start over from the beginning.
With the SDK, the pages are walked for you: rest.history()rest.history()rest.HistoryAsync()rest.history() yields results one at a time, as you read them (and rest.pages()rest.pages()rest.PagesAsync()rest.pages() one page at a time):
import { FathomChartsRest, type PageQuery } from '@fathom-charts/sdk';
import type { BigTradesData } from './fathom-charts-types.js';
const rest = new FathomChartsRest({ baseUrl: 'https://api.fathomcharts.com', apiKey: process.env.FATHOM_CHARTS_API_KEY! });
// Typed as PageQuery, so that `mode: 'confirmed'` keeps its literal type if you add it.
const query: PageQuery = {
instrument: 'NQZ6',
indicator: 'big-trades',
params: { minimum: 30 },
from: '1790256600000000000',
to: '1790258100000000000',
};
for await (const m of rest.history<BigTradesData>(query)) {
if (m.t === 'upsert' && m.final && m.data) console.log(m.cursor, m.data.side, m.data.volume);
}import asyncio
import os
from fathom_charts import FathomChartsRest, PageQuery
async def main() -> None:
query: PageQuery = {
"instrument": "NQZ6",
"indicator": "big-trades",
"params": {"minimum": 30},
"from": "1790256600000000000",
"to": "1790258100000000000",
}
async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=os.environ["FATHOM_CHARTS_API_KEY"]) as rest:
async for m in rest.history(query):
if m["t"] == "upsert" and m["final"] and "data" in m:
print(m["cursor"], m["data"]["side"], m["data"]["volume"])
asyncio.run(main())using FathomCharts;
using FathomCharts.Indicators;
using var rest = new FathomChartsRest(new RestOptions
{
BaseUrl = "https://api.fathomcharts.com",
ApiKey = Environment.GetEnvironmentVariable("FATHOM_CHARTS_API_KEY"),
});
var query = new PageQuery
{
Instrument = "NQZ6",
Indicator = IndicatorIds.BigTrades,
Params = new BigTradesParams { Minimum = 30 },
From = "1790256600000000000",
To = "1790258100000000000",
};
await foreach (var entry in rest.HistoryAsync<BigTradesData>(query))
{
if (entry is Mutation<BigTradesData> { Type: MutationType.Upsert, Final: true, Data: { } data } m)
Console.WriteLine($"{m.Cursor} {data.Side} {data.Volume}");
}use fathom_charts::{FathomChartsRest, HistoryItem, PageQuery};
use futures::StreamExt;
use serde_json::json;
mod fathom_charts_types;
use fathom_charts_types::BigTradesData;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let rest = FathomChartsRest::new(
"https://api.fathomcharts.com",
std::env::var("FATHOM_CHARTS_API_KEY").map_err(|_| "FATHOM_CHARTS_API_KEY is not set")?,
)?;
let query = PageQuery::new("NQZ6", "big-trades", "1790256600000000000", "1790258100000000000").params(json!({ "minimum": 30 }));
let mut history = Box::pin(rest.history::<BigTradesData>(query));
while let Some(item) = history.next().await {
if let HistoryItem::Mutation(m) = item? {
if let (true, Some(data)) = (m.is_final, m.data) {
println!("{} {} {}", m.cursor, data.side, data.volume);
}
}
}
Ok(())
}History items keep the protocol’s t field (upsert or remove), unlike stream events, which the SDKs hand you by kind. On error, the SDK throws an error carrying its code. When you hit the rate limit, it waits and retries automatically.
Cursors
The cursor of an item is a string <utcDay>.<rank>.<k>: the UTC day of the trade (by its reception time), its rank within that day among the trades of that instrument, then the rank of the update for that trade. These are the same cursors as in real time.
- Ranks are counted per instrument: the cursors of two instruments say nothing about which came first. Only compare cursors of the same instrument.
- To compare two cursors, compare their three numbers one by one. They are unsigned 32-bit integers: read them as a
numberor aBigInt, never as a signed 32-bit integer (int32), and never compare them as strings. k = 4294967295(the largest value) marks the position after every update of that trade. You see it in three cases:- in the cursor of a snapshot, when nothing has been published yet since the start of the computation period;
- in the cursor of the snapshot of a
from: {"time": …}subscription, when nothing was published between midnight UTC and that time:<previous utcDay>.<rank>.4294967295, the position after the last trade of the previous UTC day, even if updates were published earlier in the session. It can differ from the last cursor of a history query ending at that time, but both resume at the same point; - in the cursor of an
hbthat follows a replay from history: afrom: {"time": …}subscription, or a cursor resume caught up from history. Once the replay is over, thehbgives its end position with thisk, until a new update follows.
- Only use cursors received from the API: an altered cursor is not always detected.
The next of a page is something else entirely: a signed string, tied to your account and your query. Do not alter it or build it: send it back as is.
Estimate the cost
Every query is charged against your monthly compute budget. Before every query, ask for an estimate: same request body, nothing is charged. snapshot and cursor are ignored, limit is checked as in a query (at least 1) but has no effect; untilCursor is taken into account (an untilCursor before from gives 0 compute units).
curl https://api.fathomcharts.com/v1/indicator-queries/estimate \
-H "Authorization: Bearer $FATHOM_CHARTS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"instrument":"NQZ6","indicator":"big-trades","params":{"minimum":30},"from":"1790256600000000000","to":"1790258100000000000"}'{
"instrument": "NQZ6",
"tickSizeNanos": "250000000",
"trades": 46811,
"computeUnits": 46811,
"coveredFrom": "1790121600000000000",
"coveredTo": "1790258100000000000",
"missingDays": [],
"remainingComputeUnits": 19999953189
}computeUnits: the cost of the query, that is the number of trades in the range (trades) multiplied by the indicator’s cost per trade (computeUnitsPerTradein the catalog, currently 1 for every indicator);remainingComputeUnits: what is left of this month’s budget before this query. Here, the budget is already reduced by the query of the previous example;coveredFrom,coveredTo: the data used. It starts beforefrom, and the catalog’soriginsets how far. Only the requested range, fromfromtoto, is charged.- With
origin: none, such asbig-trades, the computation starts at 00:00 UTC of the day before the last trade beforefrom. The objects in progress atfromand the snapshot are then complete. Here, the data starts on September 23 at 00:00 UTC. - For a weekly indicator,
coveredFromis the Saturday 00:00 UTC that starts the week of the last trade beforefrom: the computation starts over from the start of that trading week. Whenfromfalls in a market closure, or at the Sunday reopen before its first trade, it is therefore the previous week’s Saturday. The first trade of the reopen still publishes the end of the previous week: Friday’s last bar and the objects it completes;
- With
missingDays: the days the query would fail on with402 NOT_COVERED(a day not over yet, or before the start of our data). The estimate is not refused when the computation needs to read back days before the start of history: it lists them here. If the range touches the current UTC day, that day is always listed: the estimate does not cover it;instrument,tickSizeNanos: the contract that would be read and its tick size, as in a response.
The estimate’s computeUnits is exactly what the query will charge you. On a long range never requested before, the estimate can take several seconds. mode is accepted and does not change the cost.
With the SDK: await rest.estimate(query)await rest.estimate(query)await rest.EstimateAsync(query)rest.estimate(&query).await?.
A query that would cost more than your remaining budget is rejected before it starts, with 429 QUOTA_EXCEEDED. The Retry-After header tells you when your budget renews.
What drives the cost
A query costs the number of trades in the requested range (from from included to to excluded, by reception time) multiplied by the indicator’s cost per trade (computeUnitsPerTrade in the catalog, currently 1 for every indicator). A range without trades, a Saturday for example, costs nothing. The data before from that the indicator needs (the start of the week for a weekly indicator, for example) is never charged.
- The cost follows the requested range. The first 25 minutes of the US cash session (from 09:30 New York time) on September 24, 2026 on NQZ6 hold 46,811 trades: 46,811 compute units on
big-tradesas onfootprint, however much history the indicator needs beforefrom. - Order of magnitude: NQ trades roughly 300,000 to 1 million times per trading day. A full day therefore costs 300,000 to 1 million compute units.
- On the Sandbox, the month’s 50 million compute units cover about 50 to 166 trading days at 1 compute unit per trade: far more than the 7 days available, on several indicators. Estimate before every query: it is free and gives the exact cost.
- Response time: a short range on a weekly indicator is answered more slowly late in the week than early in the week, without costing more.
- A live WebSocket subscription (
from: "live") never costs anything, even while the computation is warming up (warming). Of a subscription withfrom: {"time": …}, only the part before midnight UTC today is charged, like a historical query over the same range; the part of the current day costs nothing (see Starting in the past). - With the Live plan (alone or with Historical), a query, an estimate or a
from: {"time": …}subscription whosefromis within the last 7 days (the 7 × 24 hours before the request) costs nothing: its estimate givescomputeUnits0. A range that starts earlier is charged in full.
Available range
Historical queries and exports cover the completed days, in UTC: a day becomes available after midnight UTC (20:00 in New York in summer, 19:00 in winter). A range that touches the current day, or that needs data before the start of our history, is rejected with 402 NOT_COVERED, and the message gives the limit served, the same over REST and on the WebSocket:
the history of NQZ6 starts on <day>: <day> is before it: the range starts before the start of the contract’s history;no contract is known before <day>: <day> is before it: the range starts before the start of all of our history, when no contract is known under the symbol or alias yet (NQM0orNQ.frontin May 2010);<indicator> with these parameters replays NQZ6 from <origin> to serve <day>: the history of NQZ6 starts on <day>: the range is covered, but the computation needs to read back days before the start of history (for example an indicator whose period started before the contract was stored);key-levels with these parameters replays the front month of NQ from <origin>, before the history of NQZ6 (<day>), to serve <day>: it has no data before <day>:key-levelsreads the periods that start before the contract's history from the product's front month, which is not stored that far back either;key-levels with these parameters reads the <period> <key> from the front month of NQ, as it starts before the history of NQZ6 (<day>): it is served only once that period has ended, …: that period started before the contract's history and is still open at the instant asked for;the history of NQZ6 has no data for <day>, …, N more: days are missing inside the history (at most 10 are named);<day> is not closed yet: history serves trades up to <RFC 3339 time>: the day is not over yet.
A symbol designates the contract listed under it at from. Symbols come back every 10 years: NQZ6 with a from in October 2016 reads the December 2016 contract, and with a from in 2026, the December 2026 contract. When no contract was listed under that symbol in the 7 UTC days before from, the query is rejected with 404 UNKNOWN_INSTRUMENT and the message no definition of NQZ6 in the 7 UTC days before <RFC 3339 time>. This happens, for example, with NQZ6 and a from in May 2020.
An alias reads the contract it designated at from (NQ.front with a from in 2015 reads a 2015 contract). On the WebSocket, from: {"time": …} differs: it reads the contract the alias designates now, the one named in subscribed, even before its last rollover (see Starting in the past).
402 NOT_COVERED means the data is not available; 403 FORBIDDEN, that your plan does not cover the request (depth, delay, missing plan). A 402 is final: sending the same request again gets the same answer, except for a day not closed yet, served once it is over. To include the current day, subscribe on the WebSocket with from: {"time": …}: the stream chains history and live data with no gap (see Starting in the past).
Depth depends on your plan: the last 7 days on the Sandbox and with the Live plan alone (from within the 7 × 24 hours before the request), all of our history with the Historical plan. The estimate lists in missingDays the days that would not be served. Each contract has its own history start date, given by the 402 NOT_COVERED message; expired contracts can still be queried, even though they no longer appear in GET /v1/instruments (see Instruments).
Hand off to real time
To load the past and then follow the market with no gap and no duplicate, you have two options:
- the simplest: subscribe on the WebSocket with
from: {"time": "<start>"}. You receive the past, then live data, back to back. See Starting in the past; - in two steps: load the completed days over REST, with
toat midnight UTC today, then subscribe on the WebSocket withfrom: {"time": "<that same instant>"}. The snapshot gives the state at that instant, then the stream replays the current day and continues live. The current day always goes through the WebSocket: REST history stops at midnight UTC.
In two steps with the SDK, the history fills a map of the objects by id (see Keep a state by id), from the state at from, and the stream carries on with the same map from midnight UTC. Here, from midnight UTC yesterday:
import { FathomChartsRest, FathomChartsStream } from '@fathom-charts/sdk';
import type { BigTradesData } from './fathom-charts-types.js';
const apiKey = process.env.FATHOM_CHARTS_API_KEY!;
const rest = new FathomChartsRest({ baseUrl: 'https://api.fathomcharts.com', apiKey });
const stream = new FathomChartsStream({ url: 'wss://stream.fathomcharts.com/v1', apiKey });
// Midnight UTC today, in Unix nanoseconds.
const DAY_NS = 86_400_000_000_000n;
const midnight = ((BigInt(Date.now()) * 1_000_000n) / DAY_NS) * DAY_NS;
const objects = new Map<string, BigTradesData>();
// 1. The completed days over REST, from the state at `from`.
const history = rest.history<BigTradesData>({
instrument: 'NQ.front',
indicator: 'big-trades',
params: { minimum: 30 },
from: String(midnight - DAY_NS),
to: String(midnight),
snapshot: true,
});
for await (const entry of history) {
if (entry.t === 'snapshot') for (const item of entry.items) objects.set(item.id, item.data);
else if (entry.t === 'upsert' && entry.data) objects.set(entry.id, entry.data);
else if (entry.t === 'remove') objects.delete(entry.id);
}
// 2. The current day, then live data, over the WebSocket from that same instant.
const sub = stream.subscribe<BigTradesData>({
instrument: 'NQ.front',
indicator: 'big-trades',
params: { minimum: 30 },
from: { time: String(midnight) },
});
for await (const event of sub) {
switch (event.type) {
case 'snapshot':
// The state at midnight, where the history ends; after a reset, the whole state.
for (const item of event.items) objects.set(item.id, item.data);
break;
case 'upsert':
objects.set(event.id, event.data);
break;
case 'remove':
objects.delete(event.id);
break;
case 'reset':
objects.clear();
break;
case 'status':
console.log(event.state, objects.size, 'objects');
break;
}
}import asyncio
import os
import time
from fathom_charts import FathomChartsRest, FathomChartsStream, PageQuery, Remove, Reset, Snapshot, Status, Upsert
from fathom_charts_types import BigTradesData
DAY_NS = 86_400_000_000_000
async def main() -> None:
api_key = os.environ["FATHOM_CHARTS_API_KEY"]
# Midnight UTC today, in Unix nanoseconds.
midnight = time.time_ns() // DAY_NS * DAY_NS
objects: dict[str, BigTradesData] = {}
# 1. The completed days over REST, from the state at `from`.
query: PageQuery = {
"instrument": "NQ.front",
"indicator": "big-trades",
"params": {"minimum": 30},
"from": str(midnight - DAY_NS),
"to": str(midnight),
"snapshot": True,
}
async with FathomChartsRest(base_url="https://api.fathomcharts.com", api_key=api_key) as rest:
async for entry in rest.history(query, data=BigTradesData):
if entry["t"] == "snapshot":
objects.update((item["id"], item["data"]) for item in entry["items"])
elif entry["t"] == "upsert" and "data" in entry:
objects[entry["id"]] = entry["data"]
elif entry["t"] == "remove":
objects.pop(entry["id"], None)
# 2. The current day, then live data, over the WebSocket from that same instant.
async with FathomChartsStream(url="wss://stream.fathomcharts.com/v1", api_key=api_key) as stream:
async with stream.subscribe(
instrument="NQ.front",
indicator="big-trades",
params={"minimum": 30},
from_={"time": str(midnight)},
data=BigTradesData,
) as sub:
async for event in sub:
match event:
case Snapshot():
# The state at midnight, where the history ends; after a reset, the whole state.
objects.update((item.id, item.data) for item in event.items)
case Upsert():
objects[event.id] = event.data
case Remove():
objects.pop(event.id, None)
case Reset():
objects.clear()
case Status():
print(event.state, len(objects), "objects")
case _:
pass
asyncio.run(main())using FathomCharts;
using FathomCharts.Indicators;
var apiKey = Environment.GetEnvironmentVariable("FATHOM_CHARTS_API_KEY");
using var rest = new FathomChartsRest(new RestOptions { BaseUrl = "https://api.fathomcharts.com", ApiKey = apiKey });
await using var stream = new FathomChartsStream(new StreamOptions { Url = "wss://stream.fathomcharts.com/v1", ApiKey = apiKey });
// Midnight UTC today, in Unix nanoseconds.
const long DayNs = 86_400_000_000_000;
var midnight = new DateTimeOffset(DateTime.UtcNow.Date, TimeSpan.Zero).ToUnixTimeMilliseconds() * 1_000_000;
var objects = new Dictionary<string, BigTradesData>();
// 1. The completed days over REST, from the state at `From`.
var query = new PageQuery
{
Instrument = "NQ.front",
Indicator = IndicatorIds.BigTrades,
Params = new BigTradesParams { Minimum = 30 },
From = (midnight - DayNs).ToString(),
To = midnight.ToString(),
Snapshot = true,
};
await foreach (var entry in rest.HistoryAsync<BigTradesData>(query))
{
switch (entry)
{
case HistorySnapshot<BigTradesData> snapshot:
foreach (var item in snapshot.Items) objects[item.Id] = item.Data;
break;
case Mutation<BigTradesData> { Type: MutationType.Upsert, Data: { } data } upsert:
objects[upsert.Id] = data;
break;
case Mutation<BigTradesData> { Type: MutationType.Remove } remove:
objects.Remove(remove.Id);
break;
}
}
// 2. The current day, then live data, over the WebSocket from that same instant.
var sub = stream.Subscribe<BigTradesData>(new SubscribeOptions
{
Instrument = "NQ.front",
Indicator = IndicatorIds.BigTrades,
Params = new BigTradesParams { Minimum = 30 },
From = From.Time(midnight.ToString()),
});
await foreach (var e in sub)
{
switch (e)
{
case Snapshot<BigTradesData> snapshot:
// The state at midnight, where the history ends; after a reset, the whole state.
foreach (var item in snapshot.Items) objects[item.Id] = item.Data;
break;
case Upsert<BigTradesData> upsert:
objects[upsert.Id] = upsert.Data;
break;
case Remove remove:
objects.Remove(remove.Id);
break;
case Reset:
objects.Clear();
break;
case Status status:
Console.WriteLine($"{status.State} {objects.Count} objects");
break;
}
}use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use fathom_charts::{FathomChartsRest, FathomChartsStream, HistoryItem, MutationKind, PageQuery, StartFrom, StreamEvent, SubscribeOptions};
use futures::StreamExt;
use serde_json::json;
mod fathom_charts_types;
use fathom_charts_types::BigTradesData;
const DAY_NS: u64 = 86_400_000_000_000;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = std::env::var("FATHOM_CHARTS_API_KEY").map_err(|_| "FATHOM_CHARTS_API_KEY is not set")?;
let rest = FathomChartsRest::new("https://api.fathomcharts.com", api_key.clone())?;
let stream = FathomChartsStream::builder("wss://stream.fathomcharts.com/v1").api_key(api_key).build()?;
// Midnight UTC today, in Unix nanoseconds.
let midnight = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() / 86_400 * DAY_NS;
let mut objects: HashMap<String, BigTradesData> = HashMap::new();
// 1. The completed days over REST, from the state at `from`.
let query = PageQuery::new("NQ.front", "big-trades", (midnight - DAY_NS).to_string(), midnight.to_string())
.params(json!({ "minimum": 30 }))
.snapshot(true);
let mut history = Box::pin(rest.history::<BigTradesData>(query));
while let Some(entry) = history.next().await {
match entry? {
HistoryItem::Snapshot(snapshot) => objects.extend(snapshot.items.into_iter().map(|item| (item.id, item.data))),
HistoryItem::Mutation(m) => match (m.t, m.data) {
(MutationKind::Upsert, Some(data)) => {
objects.insert(m.id, data);
}
(MutationKind::Remove, _) => {
objects.remove(&m.id);
}
_ => {}
},
}
}
// 2. The current day, then live data, over the WebSocket from that same instant.
let mut sub = stream.subscribe::<BigTradesData>(
SubscribeOptions::new("NQ.front", "big-trades")
.params(json!({ "minimum": 30 }))
.from(StartFrom::Time(midnight.to_string())),
)?;
while let Some(event) = sub.next().await {
match event? {
// The state at midnight, where the history ends; after a reset, the whole state.
StreamEvent::Snapshot(snapshot) => objects.extend(snapshot.items.into_iter().map(|item| (item.id, item.data))),
StreamEvent::Upsert(upsert) => {
objects.insert(upsert.id, upsert.data);
}
StreamEvent::Remove(remove) => {
objects.remove(&remove.id);
}
StreamEvent::Reset(_) => objects.clear(),
StreamEvent::Status(status) => println!("{} {} objects", status.state, objects.len()),
_ => {}
}
}
Ok(())
}- The snapshot of the stream is the state at midnight, where the history ends. The examples add its objects to the map instead of replacing it: a snapshot lists the objects in progress and the last completed ones, not every object of the day before, and the history already holds them all. After a
reset, the map starts over from the snapshot that follows. - Its cursor is
<previous utcDay>.<rank>.4294967295, the position after the last trade of the previous UTC day, when nothing was published between midnight UTC and that instant, which is the case here. It differs from the cursor of the last history item, but both resume at the same point: nothing was published between them. - The history charges the trades of the completed days, as any query. The stream part covers only the current UTC day: it costs nothing. Both read from history, so both need the Historical plan, or the last 7 days with the Live plan or the Sandbox rights.
- With an alias, the history reads the contract the alias designated at
from, and the stream the one it designates now, named insubscribed. Around a rollover, give both the same contract (NQZ6).