C# SDK
FathomCharts handles authentication, the initial snapshot, resuming after a disconnect, duplicates, history pagination, exports and rate-limit retries for you. This page describes every option and method; the behaviour the four SDKs share is in SDKs.
Install
dotnet add package FathomCharts --version 0.6.0- Targets: .NET 8 or later, and .NET Standard 2.0, so it also runs in .NET Framework 4.8 applications, such as the add-ons of trading platforms (see .NET Framework 4.8 below).
- No dependency, on every target: the package is
FathomCharts.dllalone, zstd decompression and JSON reading included. Nothing native to install.
.NET Framework 4.8
dotnet new console --framework net48 is refused: create a .NET project, then change its target.
- Run
dotnet new console -o MyApp. - Replace the content of
MyApp/MyApp.csprojwith the project file below: it already references theFathomChartspackage.
A .NET Framework project uses C# 7.3 by default. The SDK’s records, nullable annotations and await foreach, and the generated indicator types, need C# 9 or later, hence LangVersion. The examples on this page also rely on the implicit using directives of a dotnet new console project (System, System.IO, System.Threading.Tasks…), hence ImplicitUsings. The project file then reads:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FathomCharts" Version="0.6.0" />
</ItemGroup>
</Project>Every example on this page then builds and runs on .NET Framework 4.8 as on .NET 8 (dotnet run, on Windows).
In an add-on. A library loaded by another application, such as a trading platform, needs nothing but FathomCharts.dll next to it: copy the add-on’s DLL and FathomCharts.dll, both in the build output folder (bin/Debug/net48), into the platform’s add-on folder. The SDK references no assembly outside the .NET Framework, so the platform needs no binding redirect.
await foreach and await using. On .NET, Subscription<T> is an IAsyncEnumerable<StreamEvent> and the sequences the REST methods return (AsyncSequence<T>) are IAsyncEnumerable<T>, and FathomChartsStream and Subscription<T> are IAsyncDisposable. .NET Framework has neither interface without an extra package: there, these types have the methods await foreach and await using call (GetAsyncEnumerator, MoveNextAsync, DisposeAsync), so the same code works, but they cannot be passed to a method that takes an IAsyncEnumerable<…>.
Indicator types
dotnet dnx FathomCharts.Types@0.6.0 https://api.fathomcharts.com/v1/indicators FathomChartsTypes.csdotnet dnxcomes with the .NET 10 SDK and works in every shell (PowerShell, cmd, Git Bash). In an interactive shell, its first run asks you to confirm the download of the tool; elsewhere (a CI job, a scheduled task), it downloads it without asking.- Give the generator the same version as your
FathomChartspackage (@0.6.0here): the file it writes uses types of the package, such asWireNameAttribute. - With an earlier .NET SDK, install the tool once (
dotnet tool install -g FathomCharts.Types --version 0.6.0), then runFathomCharts.Typeswith the same arguments. - It takes the catalog’s URL or a file saved from
GET /v1/indicators. It prints nothing when it succeeds (exit code 0). On failure, it prints one line,fathom-charts-types: <reason>, and exits with code 1; with wrong arguments, it prints its usage and exits with code 2. dotnet dnx FathomCharts.Types@0.6.0 -- --helpprints its usage: the--passes--helpto the generator rather than todotnet dnx.
The file holds, in the namespace FathomCharts.Indicators, one record per indicator for its parameters (BigTradesParams) and one for its data (BigTradesData), with the catalog’s descriptions as XML doc comments. Strings with a fixed set of values become records deriving from WireEnum (BigTradesDataSide), whose known values are static properties (BigTradesDataSide.Buy); IndicatorIds lists the indicator ids (IndicatorIds.BigTrades). Every property carries its JSON name as [WireName("key")], and a field the catalog requires also carries [WireRequired]: data without it does not fit the type, and the SDK reports it (see Errors). These attributes come from the FathomCharts package, which reads the data itself: no JSON library is involved. A tuple, such as a footprint level [price, bid, ask, unidentified?] (the 4th element, the volume of trades without an identified aggressor, may be missing), is a double[], whose positions are described in its doc comment; its values are whole numbers, so cast them with (long) when you need integers. A field whose schema the generator cannot type is a JsonValue.
Objects of several kinds. An indicator that publishes several kinds of objects (Fathom Zones, Fathom Opening) gets one flat record, EffortZonesData for example: the properties of every kind, all nullable, those of the other kinds left null. A property two kinds give different types (High, a whole number of ticks for a bar and a number for a zone) is a JsonValue. The id tells the kind of an object: switch on its prefix.
await foreach (var e in stream.Subscribe<EffortZonesData>(new SubscribeOptions { Instrument = "NQ.front", Indicator = IndicatorIds.EffortZones }))
{
if (e is not Upsert<EffortZonesData> upsert) continue;
// The id tells the kind: bar:<weekSunday>:<index>, ema:<weekSunday>:<index>, zone:<weekSunday>:<startIndex>.
switch (upsert.Id.Split(':')[0])
{
case "bar":
Console.WriteLine($"bar {upsert.Data.Open} → {upsert.Data.Close}");
break;
case "zone":
Console.WriteLine($"{upsert.Data.Side} zone {upsert.Data.Low}–{upsert.Data.High}{(upsert.Data.Active == true ? ", active" : "")}");
break;
case "ema":
Console.WriteLine($"EMA {upsert.Data.Value}");
break;
}
}When the catalog changes. A new indicator or field reaches your code only through a new file. A new value of an enum does not break the file you have: it is read as a record of the same type (new BigTradesDataSide("cross")), which compares unequal to every known value and prints as on the wire. Generate the file again, with the generator of your package’s version, whenever the catalog changes.
Real time: FathomChartsStream
using FathomCharts;
using FathomCharts.Indicators;
await using var stream = new FathomChartsStream(new StreamOptions
{
Url = "wss://stream.fathomcharts.com/v1",
ApiKey = Environment.GetEnvironmentVariable("FATHOM_CHARTS_API_KEY"),
OnStateChange = state => Console.WriteLine($"connection {state}"),
});
var bigTrades = stream.Subscribe<BigTradesData>(new SubscribeOptions
{
Instrument = "NQ.front",
Indicator = IndicatorIds.BigTrades,
Params = new BigTradesParams { Minimum = 30 },
Mode = Mode.Confirmed,
});
await foreach (var e in bigTrades)
{
if (e is Upsert<BigTradesData> upsert) Console.WriteLine($"{upsert.Cursor} {upsert.Data.Side} {upsert.Data.Volume}");
}Options
StreamOptions, durations as TimeSpan:
| Option | Purpose |
|---|---|
Url | Required. The stream address: wss://stream.fathomcharts.com/v1. Anything other than an absolute ws:// or wss:// URL makes the constructor throw CONFIGURATION. |
ApiKey | API key, sent in the Authorization: Bearer header. A key with spaces or control characters around it (the \r a .env file with Windows line endings leaves, for example) makes the constructor throw CONFIGURATION; the message never shows the key. |
StreamToken | Instead of ApiKey, in an application distributed to end users, which must not hold the key: a function (CancellationToken → Task<string>) returning a fresh single-use token that your backend gets from POST /v1/stream-tokens (FathomChartsRest.StreamTokenAsync(), whose Token you return). It is called on every connection, reconnections included. Give exactly one of ApiKey and StreamToken, otherwise the constructor throws CONFIGURATION. When the function fails with a network failure raised before any answer (an HttpRequestException without a status, an IOException, a SocketException, a timeout) or with a FathomChartsException NETWORK_ERROR, RATE_LIMITED, CAPACITY, HTTP_429 (a 429 answer without a problem document) or with a Status of 500 or more, the SDK calls it again with backoff, silently: the state stays Reconnecting, so log the error in the function to see it. Any other failure ends every subscription, a bug in the function included: a FathomChartsException as it is (UNAUTHORIZED for a revoked key, QUOTA_EXCEEDED although its status is 429, for example), another exception as CONFIGURATION. An HttpRequestException that carries a status (from EnsureSuccessStatusCode(), on .NET 5 or later) is not retried: when your backend answers 502, throw a FathomChartsException with the code HTTP_502 and the status 502 to have it retried. An empty token, or one with spaces or control characters around it, is CONFIGURATION too. |
WebSocketFactory | Optional: opens the sockets, to set a proxy for example (see below). By default, a ClientWebSocket with the Authorization header. A socket it returns as new StreamSocket(socket, canPause: false) takes the MaxBuffered path below. |
Reconnect | Optional: new ReconnectOptions { InitialDelay, MaxDelay, QuotaRetry, QuotaDelay }: first reconnection delay (250 ms), backoff ceiling (30 s), how long a 4029 close code is retried (120 s), minimum delay between two attempts after a 4029 (5 s). The 4029 retries last at least QuotaRetry, then end every subscription with TOO_MANY_CONNECTIONS; meanwhile the state alternates Open (the connection opens, then the gateway closes it) and Reconnecting. |
HeartbeatTimeout | Silence after which the connection is considered lost, then reopened. 15 s by default: the server sends an hb every 5 seconds. The SDK checks every third of this delay, so it detects a silence between HeartbeatTimeout and 4/3 of it. |
HighWaterMark | 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 pause, the SDK itself replaces a queued provisional version of an object by the newer one, and closes at MaxBuffered. While it waits, it sends ping messages so that the server keeps the connection. 10,000 by default. |
MaxBuffered | 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 is Reconnecting at once), then reopens it from the last cursor received once the events waiting are down to half of HighWaterMark. Nothing waiting is lost. null (the default) means 4 × HighWaterMark. |
Random | Optional, for tests: the source of the jitter of reconnections and subscription retries, in [0, 1). |
OnStateChange | Called on every change of ConnectionState. When it changes to Reconnecting, stream.LastClose already tells why the connection closed. The SDK reconnects silently, so this is where to show or log it (example below). |
OnNotice | Called with each Notice from the server (Kind, Id, EffectiveAt, EndsAt, Message): a restart, a maintenance window announced or cancelled. See Updates and maintenance. |
OnStateChange and OnNotice run on the stream’s threads: keep them short. await using (or DisposeAsync(), Close()) closes the stream. stream.ConnectionState is Idle (no subscription), Connecting, Open, Reconnecting (from the close of a connection until the next one opens) or Closed: after Close(), where a Subscribe() throws CLOSED, and after a final error that ended every subscription (a refused key, 4029 past QuotaRetry…), where a Subscribe() throws that error.
stream.LastClose is a ConnectionClose record (Code, Reason): the last close of an open connection, null until one closes. It 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() or DisposeAsync() if the connection was still open, failed after a final error). With await using after the end of the loop, LastClose stays 1000 idle: leaving the loop closed the last subscription, and the connection with it. It is set before OnStateChange is called. An attempt that fails before the connection opens leaves it as it is. A lambda cannot use the variable its own declaration assigns: declare the stream first to read it there.
using FathomCharts;
FathomChartsStream? stream = null;
stream = new FathomChartsStream(new StreamOptions
{
Url = "wss://stream.fathomcharts.com/v1",
ApiKey = Environment.GetEnvironmentVariable("FATHOM_CHARTS_API_KEY"),
OnStateChange = state =>
{
if (state == ConnectionState.Reconnecting && stream?.LastClose is { } close) Console.WriteLine($"reconnecting after {close.Code} {close.Reason}");
},
});
await using var closing = stream;WebSocketFactory is a delegate: Task<StreamSocket> WebSocketFactory(Uri url, IReadOnlyDictionary<string, string>? headers, CancellationToken cancellationToken). With ApiKey, headers holds the Authorization header: copy every header onto the socket before connecting, otherwise the gateway refuses the connection (4001). With StreamToken, headers is null. Through a proxy, for example, inside new StreamOptions { … }:
WebSocketFactory = async (url, headers, ct) =>
{
var ws = new ClientWebSocket();
ws.Options.Proxy = new WebProxy("http://proxy.example.com:3128");
if (headers is not null) foreach (var h in headers) ws.Options.SetRequestHeader(h.Key, h.Value);
await ws.ConnectAsync(url, ct);
return new StreamSocket(ws);
},(using System.Net; and using System.Net.WebSockets;.) A FathomChartsException the factory throws with the code UNAUTHORIZED, FORBIDDEN, CONFIGURATION or HTTP_4xx (other than HTTP_429) ends every subscription; any other exception is retried with backoff, silently: the state stays Reconnecting and LastClose does not change, so log the exception in the factory to see it (a proxy that cannot be reached, for example).
Subscribe()
stream.Subscribe<T>(options) opens a subscription and returns a Subscription<T>, to read with await foreach. SubscribeOptions holds the fields of the subscribe message:
InstrumentandIndicator: required. When one is missing or empty,Subscribe()throwsCONFIGURATIONand sends nothing.Params: a generated<Name>Params, or any object, written as JSON asJsonValue.FromObjectdoes: its public properties in camelCase (or the name of their[WireName]),nullones left out; the keys of a dictionary as they are; enums by their[EnumMember]value,WireEnumrecords by their text. A value JSON cannot carry (double.NaN, for example) makesSubscribe()throwCONFIGURATION.Mode:Mode.Liveby default.From:null(the default) meansFrom.Live; otherwiseFrom.Cursor(cursor, engine)orFrom.Time(time). They are the recordsFromLive,FromCursor(Cursor,Engine) andFromTime(Time), which you can read back fromRequest.From.
The SDK picks the sub name itself. A subscribe message over the 65,536 bytes the server accepts (very long Params) makes Subscribe() throw CONFIGURATION and sends nothing: sent, it would close the connection of every subscription with 1009. T is the indicator’s data type (BigTradesData…); without it, Subscribe(options) gives the data as a JsonValue.
The events are records deriving from StreamEvent: Subscribed, Snapshot<T>, Upsert<T>, Remove, Status, Reset, Notice and Retrying (Code, Message, DelayMs: the SDK subscribes again after a transient error, see Events), to test with is or switch. A new subscription receives Subscribed, a Status with state Warming while the stream is still being prepared (normal, not a failure), Snapshot<T>, then a Status (Live, for example); a change of computation or contract, Subscribed, Reset, Snapshot<T>, then Status. Their fields are those of Events, in Pascal case (TickSizeNanos, LagMs):
- the objects of
Snapshot<T>.ItemsareItem<T>records:Id,Final,Ts,Data; Status.Stateis aSourceState:SourceState.Live,Warming,SourceDelayed,SourceDownorMarketClosed;Reset.Reasonis aResetReason:Roll,CursorExpired,EntitlementChangedorEngineChange;Notice.Kindis aNoticeKind:Reconnect,MaintenanceorMaintenanceCancelled.
These three types, like EngineState, ParamType, ParamCategory, IndicatorOrigin and PlanCode over REST and the string enums of the generated indicator types, are records deriving from WireEnum, not C# enums. Their known values are static properties: compare them with == (status.State == SourceState.Live), or in a switch with a when clause; ToString() gives the text as on the wire (live), and so does Value. A value your version of the SDK does not know (a new reset reason, for example) is delivered all the same, as a record of the same type built from its text (new ResetReason("replay")), never dropped and never an error: keep a default branch. An unknown reset reason is still a reset.
An error on the subscription ends the loop: await foreach throws a FathomChartsException carrying the received Code.
To stop a loop from outside, give it a CancellationToken with WithCancellation. The loop then throws a FathomChartsException with Code ABORTED (the cancellation is its InnerException), not an OperationCanceledException. For example, to stop the loop of the first example cleanly on Ctrl+C, so that await using closes the stream:
using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, args) => { args.Cancel = true; stop.Cancel(); };
try
{
await foreach (var e in bigTrades.WithCancellation(stop.Token))
{
if (e is Upsert<BigTradesData> upsert) Console.WriteLine($"{upsert.Cursor} {upsert.Data.Side} {upsert.Data.Volume}");
}
}
catch (FathomChartsException error) when (error.Code == ErrorCodes.Aborted) { }Subscription
| Member | Purpose |
|---|---|
Cursor | The cursor of the last event handed to you: your resume point. null until a cursor has arrived. hb messages repeat the last cursor sent: they move Cursor forward only after a replay from history (From.Time, or a resume caught up from history), to the end of the replay, and only when no event is waiting to be read. On a quiet stream, it stays on the last cursor received, and 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 From.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(), DisposeAsync() | Stops the subscription: the SDK sends unsubscribe, and a pending loop ends. await using calls DisposeAsync(). |
Leaving the loop (break, return, a cancellation or an exception in its body) closes the subscription.
Connection lifecycle
The connection opens on the first Subscribe() and closes (1000, idle) when the last subscription closes; stream.Close() closes everything, and a Subscribe() after it throws CLOSED. Reconnection, resuming and close codes: see Connection lifecycle. When the SDK itself drops the connection before reconnecting (no message for HeartbeatTimeout, or MaxBuffered reached), it uses close code 4000 (CloseCode.ClientReconnect). A close with code 1002, 1003, 1007 or 1009 (the server refused a message the SDK sent) ends every subscription with an error whose Code is the close reason (PROTOCOL_ERROR, BINARY_NOT_SUPPORTED, INVALID_UTF8 or MESSAGE_TOO_BIG; PROTOCOL_ERROR when the close has no reason): the same messages would be refused again. A connection refused at its handshake with an HTTP 4xx other than 429 (404 for a wrong Url path, for example) ends every subscription with HTTP_<status>; other failures are retried with backoff. To resume after your process restarts, see Resume after a restart.
Maintenance windows
stream.Maintenance lists the maintenance windows announced on the connection and not over, by start. Each is a MaintenanceWindow record: Id, StartsAt (the EffectiveAt of its notice), EndsAt and Message, times in Unix nanoseconds as strings. See Updates and maintenance.
History: FathomChartsRest
using FathomCharts;
using var rest = new FathomChartsRest(new RestOptions
{
BaseUrl = "https://api.fathomcharts.com",
ApiKey = Environment.GetEnvironmentVariable("FATHOM_CHARTS_API_KEY"),
});| Option | Purpose |
|---|---|
BaseUrl | Required. The API address: https://api.fathomcharts.com. |
ApiKey | Required. API key, sent in the Authorization: Bearer header. Missing, empty, or with spaces or control characters around it: the constructor throws CONFIGURATION. |
HttpClient | Optional: your own HttpClient (proxy, handler…). |
RateLimitRetries | 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. The wait follows the Retry-After header, a number of seconds or an HTTP date, up to 60 s. |
Methods
Queries are records with the fields of the API, as on the History page: PageQuery (Instrument, Indicator, Params, From, To, Mode, Limit, Cursor, UntilCursor, Snapshot), and RangeQuery (the first six) for exports. Cursor is the Next of the previous page, not the cursor of an item; UntilCursor is the cursor of an item or of a subscription (a stream cursor), where the query stops. Instrument, Indicator, From and To are required: when one is missing or empty, or the query itself is null, the method throws CONFIGURATION and sends nothing. Every method takes a CancellationToken as its last parameter (ct below, optional): cancelling a call, or the wait for a retry, throws ABORTED.
| Method | Returns |
|---|---|
PageAsync<T>(query, ct) | One Page<T>: Instrument, TickSizeNanos, Snapshot (a PageSnapshot<T>: Cursor, Items), Items (the Mutation<T> records), Next, ComputeUnits. |
PagesAsync<T>(query, ct) | The pages one at a time, following Next, as you read them (await foreach). |
HistoryAsync<T>(query, ct) | The results one at a time, across pages, as HistoryEntry<T> records (await foreach). With Snapshot = true, a HistorySnapshot<T> (Cursor, Items), the state at From, comes first. |
EstimateAsync(query, ct) | The cost estimate, charging nothing: an Estimate (Instrument, TickSizeNanos, Trades, ComputeUnits, CoveredFrom, CoveredTo, MissingDays, RemainingComputeUnits). |
ExportAsync(query, resume, ct) | One export response, as an ExportStream (see below). |
ExportNdjsonAsync(query, options, ct) | The decompressed export, in chunks of whole lines (byte[]), with automatic resume (await foreach). See below and Exports. |
StreamTokenAsync(ct) | A stream token, as an IssuedStreamToken: Token, ExpiresAt. |
UsageAsync(ct) | Your usage this month and your limits: a Usage (Period, ResetsAt, Plan, Limits, Used, Remaining). |
InstrumentsAsync(ct) | Every instrument served: an InstrumentList, whose Instruments have Symbol, Alias, TickSizeNanos, Status (a SourceState) and UpdatedAt. |
StatusAsync(ct) | A ServiceStatus: the state of the computation (Engine.State, Up or Down), the Maintenance windows announced (MaintenanceWindow records), and the state of each instrument (Instruments). |
IndicatorsAsync(ct) | The indicator Catalog: Version, EngineFingerprint, Indicators. |
A Mutation<T> (in Page<T>.Items, and from HistoryAsync<T>) has:
Cursor,Id,FinalandTs;Type:MutationType.UpsertorMutationType.Remove;Data: the indicator’s data,nullfor a removal.
T is the indicator’s data type, as with Subscribe<T>(). Data that does not fit it throws CONFIGURATION (see Errors); with JsonValue, the data comes as it is.
ExportNdjsonAsync hands you byte[] chunks, each made of whole NDJSON lines; write them as they come (file.Write(chunk, 0, chunk.Length)). Its ExportOptions:
MaxResumes(5): consecutive resumptions without a new line (connection lost, stream cut before its end line,5xx) before the error is thrown;ResumeDelay(1 s): the delay before the first resumption, doubled for each consecutive one, up to 30 s.
The first request is never sent again: when it fails, the error is thrown.
ExportAsync(RangeQuery query, ExportResume? resume = null, CancellationToken cancellationToken = default) returns an ExportStream: Body (a Stream: the zstd-compressed NDJSON file, as sent), ContentType, Filename and Token. Dispose it to release the connection. To resume a cut export yourself, call ExportAsync again with the same query and new ExportResume(Token, After), where After is the cursor of the last complete line you received: the new response continues strictly after that line. ExportNdjsonAsync does all of this for you.
Errors
Every error FathomChartsStream, FathomChartsRest and their subscriptions and sequences throw, or end a loop with, is a FathomChartsException, missing options included (new FathomChartsStream(null!) throws CONFIGURATION). The members of JsonValue throw as those of JsonElement do. The codes are listed in Errors; in C#, the constants are in ErrorCodes (ErrorCodes.All lists them all) and the WebSocket close codes in CloseCode.
| Property | Content |
|---|---|
Code | The stable error code. |
Message | A human-readable explanation. Over REST: the detail of the response, followed by the invalid fields it does not already name (<detail>: <path> <message>; …). |
Status | The HTTP status, over REST. |
CloseCode | The WebSocket close code, when the connection was closed. |
RetryAfter | The value of the Retry-After header, when the response has one. |
Problem | The problem+json document of the response, as a ProblemDocument: Json (the whole document, a JsonValue, to read detail, type or instance) and Errors (the invalid fields, ProblemFieldError records with Path and Message; an empty list when the API lists none). null when the response is not a problem+json document. |
InnerException | The original error, when there is one (the cancellation, the error of HttpClient…). |
ToString() shows the code in brackets before the message (FathomCharts.FathomChartsException [NOT_COVERED]: …), then the inner exception and the stack trace. The records of the SDK print the content of their lists (MissingDays = [2026-10-03, 2026-10-04]), not the name of the list type.
In C#, CONFIGURATION also covers:
- missing options (
StreamOptions,RestOptions,SubscribeOptionsor a query that isnull); - an invalid
UrlorBaseUrl, and an API key with spaces or control characters around it; - a missing
InstrumentorIndicatorinSubscribeOptions, and a missingInstrument,Indicator,FromorToin a query; Paramsthat cannot be written as JSON, or asubscribemessage over the 65,536 bytes the server accepts;- a
StreamTokenfunction that gives no usable token, or fails with an error the SDK does not retry (see Options); - data that does not fit the type
Tyou asked for (a value of another type, a required field missing), on the stream and over REST:The data of <indicator> does not fit <Type>: <cause>.
ABORTED covers a REST call, the wait for a retry, and a subscription loop stopped by its CancellationToken: catch FathomChartsException with Code == ErrorCodes.Aborted, not OperationCanceledException. UPSTREAM_ERROR covers an answer that is not JSON, and JSON whose values do not have the type your version of the SDK expects (a number where it expects text, for example). A new value of one of its WireEnum types is read, not an error.
JsonValue
JsonValue is the SDK’s own JSON value, immutable, with members named as those of JsonElement: the data of an indicator read without a type of its own (Subscribe(options), PageAsync<JsonValue>), the schemas and defaults of the catalog, Problem.Json.
JsonValue.Parse(text)reads JSON (astring, or UTF-8 bytes); invalid JSON throws aFormatExceptionthat gives the position.Kindis aJsonKind:Null,True,False,Number,String,ArrayorObject.GetProperty(name)(orvalue["name"]),TryGetProperty,EnumerateObject(),value[index],EnumerateArray()andGetArrayLength()read objects and arrays;GetString(),GetBoolean(),GetInt64(),GetInt32(),GetDouble()andGetDecimal()read values, with aTryGet…form for numbers. A number keeps its text, soGetInt64()andGetDecimal()read it exactly. A member or kind that is not there throws, as withJsonElement.Deserialize<T>()reads the value as a type, as the SDK reads the data of an indicator ([WireName],[WireRequired], enums by their[EnumMember]value,WireEnumrecords by their text); data that does not fit throws aFormatExceptionthat says where and why.JsonValue.FromObject(value)writes an object as JSON, as the SDK writesParams.ToString()(orGetRawText()) writes the value as compact JSON. Two values areEqualswhen they hold the same JSON: numbers of the same value, object members in any order.
With the stream of the first example:
await foreach (var e in stream.Subscribe(new SubscribeOptions { Instrument = "NQ.front", Indicator = "big-trades" }))
{
if (e is Upsert<JsonValue> upsert) Console.WriteLine($"{upsert.Data.GetProperty("side").GetString()} {upsert.Data.GetProperty("volume").GetInt64()}");
}Cursors
Cursors.Compare(a, b) orders two cursors <utcDay>.<rank>.<k> (negative, zero, positive), number by number. Each of the three numbers is an unsigned 32-bit integer. A malformed cursor (numbers with leading zeros, a number above 4294967295, a missing field…) throws INVALID_PARAMETERS.
Cursors.Compare("20720.111416.0", "20720.111417.0"); // < 0