Rust SDK
fathom-charts handles authentication, the initial snapshot, resuming after a disconnect, duplicates, history pagination, exports and rate-limit retries for you, on Tokio. This page describes every option and method; the behaviour the four SDKs share is in SDKs.
Code without fn main is a fragment: it goes inside an async function that returns Result<(), Box<dyn std::error::Error>>, such as main in the first example, with that example’s imports plus those the fragment names. The full types and their fields are on docs.rs: the return types are named after the API objects (Page, Estimate, Usage, Catalog…).
Install
cargo add fathom-charts@0.6.0
cargo add tokio --features full
cargo add futures serde serde_json --features serde/derive- Rust 1.88 or later, on Tokio: a runtime with its time and I/O drivers, as
#[tokio::main]gives. Building a stream outside a runtime returnsCONFIGURATION. - TLS is rustls: no OpenSSL. A C compiler is needed to build the crate (MSVC Build Tools on Windows,
ccon Linux and macOS). - Subscriptions and paginated results are
futures::Streams: read them withStreamExt::next. - The crate’s licence is proprietary, given in its
LICENSEfile (license-file) rather than as an SPDX identifier: crates.io therefore shows it as non-standard, or unknown. Its terms are in that file.
Indicator types
cargo install fathom-charts@0.6.0 --features cli --locked
fathom-charts-types https://api.fathomcharts.com/v1/indicators src/fathom_charts_types.rsInstall the command at the version of your fathom-charts dependency (0.6.0 here). It is a release build of the crate: about 1 to 2 minutes. The cli feature only builds the fathom-charts-types binary; it adds nothing to the library. fathom-charts-types --help prints its usage. The command prints nothing when it succeeds (exit code 0). On failure, it prints one line (fathom-charts-types: …) and exits with code 1; with wrong arguments, it prints its usage and exits with code 2.
The command takes the catalog’s URL or a file saved from GET /v1/indicators; declare the file as a module (mod fathom_charts_types;). It needs serde (with derive); its header says when it also needs serde_json. Per indicator:
<Name>Paramsand<Name>Data(big-trades→BigTradesParams,BigTradesData), with the catalog’s descriptions as doc comments.- Strings with a fixed set of values become enums, with an
Other(String)variant for a value the file does not list yet: data with a new value is read, not refused, and written back as it came. They print as on the wire with{}(sell), andas_str()gives the same text. - Optional fields become
Option<_>. - An indicator that publishes several kinds of objects (Fathom Zones, Fathom Opening) gets one struct per kind (
EffortZonesDataBar,EffortZonesDataZone,EffortZonesDataEma), and its data type is an untagged enum with one variant per kind (EffortZonesData::Bar(…)): serde picks the variant whose fields the object has. Theidof an object also tells its kind (bar:<weekSunday>:<index>…). - A tuple with optional elements, such as a footprint level
[price, bid, ask, unknown?], becomes aVec<i64>; its doc comment gives the shape. INDICATOR_IDSlists the ids. Each indicator implements theIndicatortrait:ID,Params(Serialize + DeserializeOwned + Default + Clone…) andData(DeserializeOwned + Serialize + Clone…). Generic code can useI::Params::default()andsubscribe::<I::Data>.
Match the kind of an object of several kinds on the variant:
use fathom_charts_types::EffortZonesData;
async fn print_zones(stream: &FathomChartsStream) -> Result<(), fathom_charts::Error> {
let mut zones = stream.subscribe::<EffortZonesData>(SubscribeOptions::new("NQ.front", "effort-zones"))?;
while let Some(event) = zones.next().await {
if let StreamEvent::Upsert(upsert) = event? {
match upsert.data {
EffortZonesData::Bar(bar) => println!("bar {} → {}", bar.open, bar.close),
EffortZonesData::Zone(zone) => println!("{} zone {}–{}", zone.side, zone.low, zone.high),
EffortZonesData::Ema(ema) => println!("EMA {}", ema.value),
}
}
}
Ok(())
}Generate the file again when the catalog changes: a new indicator or field reaches your code only through a new file.
Real time: FathomChartsStream
use fathom_charts::{FathomChartsStream, Mode, StreamEvent, SubscribeOptions};
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 stream = FathomChartsStream::builder("wss://stream.fathomcharts.com/v1")
.api_key(std::env::var("FATHOM_CHARTS_API_KEY").map_err(|_| "FATHOM_CHARTS_API_KEY is not set")?)
.on_state_change(|state| println!("connection {state:?}"))
.build()?;
let mut big_trades = stream.subscribe::<BigTradesData>(
SubscribeOptions::new("NQ.front", "big-trades")
.params(json!({ "minimum": 30 }))
.mode(Mode::Confirmed),
)?;
while let Some(event) = big_trades.next().await {
if let StreamEvent::Upsert(upsert) = event? {
println!("{} {} {}", upsert.cursor, upsert.data.side, upsert.data.volume);
}
}
Ok(())
}map_err(…)? stops the program with a readable message when the variable is not set; an empty key, or one with spaces or control characters around it, is CONFIGURATION (see below).
An error returned from main prints in its Debug form (Error { code: …, message: … }). For a readable message, print it with {} (eprintln!("{e}")) or match e.code() (see Errors).
Options
FathomChartsStream::builder(url) takes the stream address, wss://stream.fathomcharts.com/v1. Then call the builder methods below (durations are std::time::Duration), and finish with build()?:
| Method | Purpose |
|---|---|
api_key(key) | API key, sent in the Authorization: Bearer header. |
stream_token(f) | Instead of api_key, in an application distributed to end users, which must not hold the key. See Stream tokens. |
web_socket(f) | Optional: opens the connections. See Your own WebSocket. |
reconnect(Reconnect { … }) | Optional: initial_delay (first reconnection delay, 250 ms), max_delay (backoff ceiling, 30 s), quota_retry (how long a 4029 close code is retried, 120 s), quota_delay (minimum delay between two attempts after a 4029, 5 s). Reconnect::default() gives these values. |
heartbeat_timeout(d) | Silence after which the connection is considered lost: the SDK closes it (close code 4000, reason heartbeat timeout) and reopens it. It checks every third of this delay, so a silence is detected between heartbeat_timeout and 4/3 of it. 15 s by default: the server sends an hb every 5 seconds. |
high_water_mark(n) | Number of events waiting to be read, all subscriptions together, above which the SDK stops reading the socket; the server then keeps only the latest version of each object in progress. With a socket that cannot be paused, the SDK itself replaces a queued provisional version by the newer one, and closes the connection at max_buffered. While it waits, it sends ping messages so that the server keeps the connection. 10,000 by default. |
max_buffered(n) | For a socket that cannot be paused: number of waiting events above which the SDK closes the connection (close code 4000, reason client buffer full); the state goes Reconnecting at once and stays so until the connection is open again. It reopens it from the last cursor received once the events waiting fall to half of high_water_mark; a subscription added meanwhile waits for that reopening. Nothing waiting is lost. 4 × high_water_mark by default. |
random(f) | Optional, for tests: the source of the jitter of reconnections and subscription retries, a function returning a number in [0, 1). |
on_state_change(f) | Called on every change of connection_state(), with the new state. When it becomes Reconnecting, last_close() already tells why the connection closed. |
on_notice(f) | Called with each Notice from the server (kind, id, effective_at, ends_at, message): a restart, a maintenance window announced or cancelled. See Updates and maintenance. |
Give exactly one of api_key and stream_token. build() returns CONFIGURATION when:
- both or neither are given, or the key is empty;
- the key has spaces or control characters around it (a
.envfile with Windows line endings leaves a\r); - the address is not an absolute
ws://orwss://URL.
The message never quotes the key.
A handshake refused with an HTTP status from 400 to 499 other than 429 (a wrong path, 404) ends every subscription with HTTP_<status>; status() gives it. A 5xx or 429 answer is retried with backoff.
A 4029 close code (every connection of your plan is in use) is retried for at least quota_retry (the attempt in progress at its end finishes first), then every subscription ends with TOO_MANY_CONNECTIONS: The plan's connection limit was still reached after 120 s of retries (4029): close another connection, then subscribe again. Meanwhile each refused connection opens, then closes: the state alternates between Open and Reconnecting. A 4008 close code is resumed at once, unless the connection closed again before any Subscribed: then with the backoff.
A 1002, 1003, 1007 or 1009 close code ends every subscription with an error whose code is the close reason (PROTOCOL_ERROR, BINARY_NOT_SUPPORTED, INVALID_UTF8, MESSAGE_TOO_BIG), or PROTOCOL_ERROR when the reason is empty.
stream.close() closes every subscription and the connection. Dropping the FathomChartsStream does not: it is a handle, and its clones and its open subscriptions keep the connection. stream.connection_state() is Idle, Connecting, Open, Reconnecting or Closed; stream.last_close() is the ConnectionClose (code, reason) of the last close of an open connection, None until one closes; stream.maintenance() lists the maintenance windows announced on the connection and not over, by start. CloseCode lists the close codes: those of the gateway, and CLIENT_RECONNECT (4000), the one the SDK uses when it drops the connection itself.
last_close() is the server’s close frame (4029 TOO_MANY_CONNECTIONS when every connection of your plan is in use, for example), 1005 for a close frame without a code, 1006 for a connection lost without one, or the SDK’s own close (4000 heartbeat timeout or client buffer full before it reconnects; 1000 idle when the last subscription closed, client closed after close() if the connection was still open, failed after a final error); it is set before on_state_change is called. The SDK reconnects silently: on_state_change is where to show or log it. The callback is given before the stream exists: to read last_close() on a change, send the state to code that holds the stream, through a channel for example:
use fathom_charts::ConnectionState;
let (states, mut changes) = tokio::sync::mpsc::unbounded_channel();
let stream = FathomChartsStream::builder("wss://stream.fathomcharts.com/v1")
.api_key(std::env::var("FATHOM_CHARTS_API_KEY").map_err(|_| "FATHOM_CHARTS_API_KEY is not set")?)
.on_state_change(move |state| {
let _ = states.send(state);
})
.build()?;
let watched = stream.clone();
tokio::spawn(async move {
while let Some(state) = changes.recv().await {
match state {
ConnectionState::Reconnecting => {
if let Some(close) = watched.last_close() {
println!("reconnecting after {} {}", close.code, close.reason);
}
}
ConnectionState::Closed => break,
_ => {}
}
}
});Stream tokens
stream_token(|| async { … }) takes an async function returning Result<String, fathom_charts::BoxError>: a fresh single-use token that your backend gets from POST /v1/stream-tokens (FathomChartsRest::stream_token). The SDK calls it on every connection, reconnections included.
// Asks your backend for a token: its route calls `FathomChartsRest::stream_token` with your API key.
async fn fetch_token_from_my_backend() -> Result<String, reqwest::Error> {
reqwest::get("https://my-app.example/stream-token").await?.error_for_status()?.text().await
}
let stream = FathomChartsStream::builder("wss://stream.fathomcharts.com/v1")
.stream_token(|| async { Ok(fetch_token_from_my_backend().await?) })
.build()?;Here the token comes through reqwest (reqwest = "0.13" in your dependencies); any async code returning a String will do.
| The function returns | The SDK |
|---|---|
A network failure raised before any answer: an I/O error, a reqwest connection, request or timeout error without a status, an elapsed tokio::time::timeout (also as the source() of your error) | Calls it again, with the reconnection backoff. |
A fathom_charts::Error NETWORK_ERROR, RATE_LIMITED, CAPACITY, HTTP_429 (a 429 answer without a problem document) or with a status of 500 or more | Calls it again, with the reconnection backoff. |
Another fathom_charts::Error (QUOTA_EXCEEDED, status 429; Error::new(ErrorCode::Forbidden, "…")) | Ends every subscription with that error. |
| Any other error, a bug in the function included | Ends every subscription with CONFIGURATION stream_token failed: …; source() is your error. A reqwest status error (from error_for_status()) is one of them, whatever its status: to have a 502 of your backend retried, return Error::new(ErrorCode::Http(502), "…"). |
| An empty token, or one with spaces or control characters around it | Ends every subscription with CONFIGURATION. The message never quotes the token. |
Your own WebSocket
web_socket(|url, headers| async move { … }) opens each connection:
urlis aString, andheadersis anOption<Vec<(String, String)>>:Authorization: Bearer <key>with an API key,Nonewith a stream token.- The function returns
Result<Socket, fathom_charts::Error>.Socket::connect(&url, headers)is the default.
A Socket has three fields:
| Field | Content |
|---|---|
incoming | A stream of Frame: Frame::Text(String), or Frame::Close { code, reason }, the last one. It ends when the connection is lost. |
outgoing | A sink of Frame (futures::Sink<Frame, Error = fathom_charts::Error>). |
pausable | Whether not reading incoming slows the server down (TCP backpressure). When it is false, the max_buffered limit applies. |
An error from the function with code UNAUTHORIZED, FORBIDDEN, CONFIGURATION or HTTP_<status> (400 to 499, but 429) ends every subscription; any other error is retried with backoff.
subscribe()
stream.subscribe::<T>(options)? opens a subscription and returns a Subscription<T>.
SubscribeOptions::new(instrument, indicator) holds the fields of the subscribe message, with:
.params(json!({…})), orserde_json::to_valueof a generated<Name>Params;.mode(Mode::Confirmed);Mode::Liveby default;.from(…):StartFrom::Liveby default,StartFrom::Cursor { cursor, engine }orStartFrom::Time(time).
The SDK picks the sub name itself. An empty instrument or indicator is refused by subscribe() with CONFIGURATION (instrument is missing: give a raw symbol or an alias, e.g. NQ.front), and nothing is sent. A subscribe message over 65,536 bytes (UTF-8), with very large params, is refused by subscribe() with CONFIGURATION (The subscribe message is 70123 bytes, over the 65,536 bytes the gateway accepts: send smaller params), and nothing is sent: the gateway would close the connection, ending every subscription.
StartFrom is fathom_charts::From under a name of its own: From has the name of Rust’s From trait, so use fathom_charts::From; hides the trait, and an impl From<X> for Y in the same module then fails to compile. Import StartFrom instead (use fathom_charts::StartFrom;), or write the full path, fathom_charts::From::Cursor { cursor, engine }.
T is the type of the objects’ data: a generated <Name>Data (BigTradesData…). For untyped data, name serde_json::Value: subscribe::<serde_json::Value>(…), or let sub: Subscription = stream.subscribe(…)?;. Rust cannot infer it, and a bare stream.subscribe(options)? does not compile.
A Subscription<T> is a futures::Stream of Result<StreamEvent<T>, Error>. StreamEvent is Subscribed, Snapshot, Upsert, Remove, Status, Reset, Notice or Retrying; it is #[non_exhaustive], so a match needs a _ arm. Their fields are those of Events, in snake case (tick_size_nanos, lag_ms, delay_ms; is_final for final). state, reason and kind are enums (SourceState, ResetReason, NoticeKind) with an Other(String) variant for a value this version does not know: such a value is delivered, not dropped. {} prints them as on the wire (live), as every SDK does. After an error with a transient code (UPSTREAM_ERROR, CAPACITY, INTERNAL, SOURCE_DOWN), the loop goes on: it receives Retrying (code, message, delay_ms), and the SDK subscribes again from the last cursor received.
An error on the subscription is yielded once as an Err, then the stream ends. Data that does not fit T is yielded as a CONFIGURATION error, such as The data of big-trades does not fit FootprintData: missing field `close` , and the subscription ends.
Subscription
| Member | Purpose |
|---|---|
cursor() | The cursor of the last event handed to you: your resume point. None until a cursor has arrived. When no event is waiting to be read, it also moves to the cursor of an hb message that is later (after a replay from history, for example). On a stream with no update, it stays on the last cursor received: resuming from it loses nothing. A cursor that ends in .4294967295 is a position after every update of a trade: see Which cursor is for what. |
topic() | The topic of the latest Subscribed. |
engine() | The engine of the latest Subscribed, or the engine given in StartFrom::Cursor until a Subscribed arrives: the computation your state comes from. Save it with cursor() to resume later. |
id() | The sub name the SDK chose for this subscription (s1, s2…). |
request() | The options of subscribe(), completed with the default values. |
close() | Stops the subscription: the SDK sends unsubscribe, and the stream ends. |
Dropping the subscription closes it. Reconnection, resuming and close codes: see Connection lifecycle; to resume after your process restarts, see Resume after a restart.
History: FathomChartsRest
use fathom_charts::FathomChartsRest;
let rest = FathomChartsRest::new(
"https://api.fathomcharts.com",
std::env::var("FATHOM_CHARTS_API_KEY").map_err(|_| "FATHOM_CHARTS_API_KEY is not set")?,
)?;FathomChartsRest::builder(base_url) takes the API address, https://api.fathomcharts.com; build()? ends it. An address that is not an absolute http:// or https:// URL, or a key that is missing, empty or has spaces around it, returns CONFIGURATION. Its methods:
| Method | Purpose |
|---|---|
api_key(key) | Required. API key, sent in the Authorization: Bearer header. |
rate_limit_retries(n) | Number of retries of a request the server did not process, or of a read that failed (see Rate limit and retries). 3 by default. |
client(c) | Optional: your own reqwest::Client (proxy, timeouts…). It must come from reqwest 0.13, the version of the SDK: add reqwest = "0.13" to your dependencies. |
Methods
Queries are PageQuery::new(instrument, indicator, from, to) and, for exports, RangeQuery::new(…). Set the other fields with .params(…), .mode(…) and the fields of the History page (limit, cursor, until_cursor, snapshot); the SDK serializes them as the API expects. An empty instrument, indicator, from or to returns CONFIGURATION before anything is sent. cursor is the next of the previous page, not the cursor of an item; until_cursor is the cursor of an item or of a subscription (a stream cursor), where the query stops.
| Method | Returns |
|---|---|
page::<T>(&query).await | One page: instrument, tick_size_nanos, snapshot, items, next, compute_units. |
pages::<T>(query) | A stream of the pages, following next, as you read them. |
history::<T>(query) | A stream of the results across pages: HistoryItem::Mutation (t is Upsert or Remove, each with its cursor), preceded, with snapshot, by HistoryItem::Snapshot, the state at from. |
estimate(&query).await | The cost estimate, charging nothing. It takes a PageQuery: to estimate an export, convert its RangeQuery with PageQuery::from(range_query.clone()). |
export(&query, resume).await | One export response, an ExportStream: body (the zstd-compressed file as is, a stream of Bytes), content_type, filename and token. resume is None, or Some(&ExportResume { token, after: Some(cursor) }) to continue a cut response after the line whose cursor is cursor: token is the token of the first response, cursor that of the last complete line received. With after: None (no complete line received), the export starts over from the beginning, with no new compute charge. |
export_ndjson(query, options) | A stream of the decompressed export, in chunks (Bytes) of whole lines, with automatic resume. ExportOptions: max_resumes (5), resume_delay (1 s). See Exports. |
stream_token().await | A stream token: token, expires_at. |
usage().await | Your usage this month and your limits. |
instruments().await | Every instrument served. |
status().await | The state of the computation, of each instrument, and the maintenance windows announced. |
indicators().await | The indicator catalog. |
The counters of the responses (compute_units, trades, remaining_compute_units, the usage and the limits) are f64, as JSON numbers: {:?} prints 15158.0, {} prints 15158.
T is the data type, as for subscribe(): name serde_json::Value for untyped data (page::<serde_json::Value>(&query)). Data that does not fit T returns CONFIGURATION; the page is computed, and charged, all the same.
The streams of pages, history and export_ndjson must be pinned before you call .next(): let mut pages = Box::pin(rest.pages::<BigTradesData>(query));, or futures::pin_mut!(pages);.
Cancellation is Rust’s: dropping the future of a call, or a stream of pages, history or export_ndjson, stops it, including while it waits to retry.
Errors
Every error the SDK returns, or ends a stream with, is a fathom_charts::Error. Its codes are listed in Errors.
| Method | Content |
|---|---|
code() | The stable error code, a &ErrorCode. |
message() | A human-readable explanation. Display ({}) prints it. |
status() | The HTTP status, over REST, or of a refused handshake. |
close_code() | The WebSocket close code, when the connection was closed. |
retry_after() | The delay of the Retry-After header, given in seconds or as an HTTP date, when the response has one. |
problem() | The full problem+json document of the response; None when the answer is not one. |
problem_errors() | The invalid fields of that document, a Vec<ProblemFieldError> (path, message); empty otherwise. |
source() | The original error, when there is one (of the HTTP client, of the WebSocket, of your stream_token function…). It is the method of the std::error::Error trait: bring it into scope with use std::error::Error as _;. |
ErrorCode has one variant per code (InvalidParameters, Forbidden, Configuration…), Http(status) for HTTP_<status>, and Other(String) for a code this version of the SDK does not know. It is #[non_exhaustive]: a match needs a _ arm. It also compares with a string, and code().as_str() gives it as on the wire. ERROR_CODES lists the codes.
To return a fathom_charts::Error from your own code (a stream_token or web_socket function), build it with Error::new(code, message), and add .with_source(e) to keep the error it stems from. ErrorCode::parse("FORBIDDEN") reads a code as on the wire; a code this version does not know gives Other.
match rest.usage().await {
Ok(usage) => println!("{} compute units left", usage.remaining.compute_units),
Err(e) if e.code() == "FORBIDDEN" => eprintln!("not in your plan: {e}"),
Err(e) => eprintln!("{}: {e}", e.code()),
}Cursors
use fathom_charts::compare_cursors;
fn order() -> Result<(), fathom_charts::Error> {
let ordering = compare_cursors("20720.111416.0", "20720.111417.0")?; // Ordering::Less
println!("{ordering:?}");
Ok(())
}compare_cursors(a, b) returns a std::cmp::Ordering. A cursor is <utcDay>.<rank>.<k>: three unsigned 32-bit integers, without leading zeros. Anything else returns INVALID_PARAMETERS.