The Go client
Package client dials a Mirexa node, writes candles and trades, reads them back and subscribes to live data. Examples that show their output were run against a node; the others are abbreviated and assume a ctx, a client and a stream.
- Import
- github.com/AmiraliOmidvar/mirexa/client
- Dependencies
- none outside the standard library
- Concurrency
- one Client, many goroutines
- Go
- 1.25 or newer
Connecting
// A node started with -data-dir ./data writes its admin token here.
c, err := client.Dial("localhost:8080", client.Options{
TokenSource: func() (string, error) {
b, err := os.ReadFile("data/auth/admin.token")
return strings.TrimSpace(string(b)), err
},
})
if err != nil {
log.Fatal(err)
}
defer c.Close()
fmt.Println(client.PermissionNames(c.GrantedPermissions()))[READ_TICKS READ_CANDLES WRITE_TICKS WRITE_CANDLES ADMIN_STREAM LIST_STREAMS ADMIN_CLUSTER]A Client is one connection, safe for any number of goroutines: requests overlap on the wire and each gets its own reply. The node works through one connection’s requests in order, so a slow query delays the ones behind it; give each worker its own client when you want the node to work on them in parallel. The zero Options is usable.
| Option | Default | What it does |
|---|---|---|
Token | none | A token from mirexa-cli token issue. Needed unless the node has authentication off. Never renewed. |
TokenSource | none | A function the client calls for a token on every connect and before the session’s token expires; it renews the session over the open connection. Use it in a long-running program with a token file refreshed elsewhere. Takes precedence over Token. |
TLS | plaintext | A *tls.Config to speak TLS 1.3 to a node that has it on. |
DialTimeout | 10s | How long connecting and the handshake may take. |
RequestTimeout | 30s | How long a request waits for its reply. |
DisableRenewal | false | Turns off the automatic token renewal a TokenSource enables (below). |
MaxFramePayloadBytes | 16 MiB | The largest reply the client accepts. Matches the node’s default. |
Retry | 1,000 attempts | Re-sending of writes and reads the node sheds under load (below). |
Observer | none | Receives the client’s own measurements (below). |
Every zero value means the default. A value that cannot be meant, such as a negative timeout or a frame cap under 4 KiB, makes Dial fail with ErrInvalidOptions rather than turning into a confusing connection error later. c.SessionID() is the id the node gave this session; c.Close() ends it, and every call after that fails with ErrClientClosed.
Authentication
Authentication is on by default: a node accepts only sessions that present a token signed by an issuer key it trusts. A single node with no security.auth.trusted_keys configured makes its own issuer key, <data_dir>/auth/issuer.key, and writes an admin token carrying every permission to <data_dir>/auth/admin.token, re-minted every 20 minutes. Point a TokenSource at that file (above), or mint narrower tokens from the node’s key:
mirexa-cli token issue -key ./data/auth/issuer.key -perms READ_CANDLES -validity 30m > token.txtFor anything real, and always for a cluster, use a key of your own and keep its private half off the node. Once trusted_keys lists a key, the node makes none. Every node of a cluster must list the same keys; a clustered node with authentication on and none listed refuses to start.
mirexa-cli token keygen -name ops -dir ./keys # once: ops.key (mode 0600) and ops.pub
mirexa-cli token issue -key ./keys/ops.key -perms READ_CANDLES,WRITE_CANDLES,LIST_STREAMS -validity 1h > token.txt
mirexa-cli token inspect "$(cat token.txt)" -pub ./keys/ops.pubTokens are minted offline: no service is involved. The node trusts the public key through security.auth.trusted_keys. With security.auth.enabled: false, a client without a token is accepted and the permissions it asks for are taken on trust: do not expose such a node to an untrusted network. A token signs a tenant, a set of permissions and an expiry, and lives at most client.MaxTokenValidity, one hour; issue defaults to 30 minutes.
c, err := client.Dial(addr, client.Options{
TokenSource: func() (string, error) {
b, err := os.ReadFile("/run/secrets/mirexa-token") // refreshed by your orchestrator
return strings.TrimSpace(string(b)), err
},
})- Use
TokenSourcein anything that runs longer than a token. It is called on every connect and every reconnect; a staticTokenwould reconnect with an expired token forever. It runs on the dial path, so keep it quick; an error fails the connect. - Renewal. With a
TokenSource, the client renews its session two-thirds of the way through the token’s life: it asks for a fresh token and hands it over the open connection, so a subscription outlives its tokens without reconnecting. A renewal that fails is not retried; the session carries on under the token it has.c.Reauthenticate(ctx)renews at once;DisableRenewalturns the automatic one off. A renewal that narrows the grant ends any subscription the new grant does not allow. - Expiry. Once a session’s token expires, its next request is refused with
ErrorCodeUnauthorized, and a subscriber is cut off at the expiry (or after the node’ssecurity.auth.subscriber_grace, 0 by default). A revoked issuer key ends its sessions at their next request.
| Permission | Allows |
|---|---|
READ_CANDLES | Candle queries and subscriptions, ListGaps. |
READ_TICKS | Trade queries and subscriptions. |
WRITE_CANDLES | IngestCandles, IngestCorrectionCandles, IngestHistoryCandles. |
WRITE_TICKS | IngestTicks. |
LIST_STREAMS | ListStreams, ListNodes, NodeStats. Separate from reading on purpose: serving prices and disclosing which instruments a node holds are different things. |
ADMIN_STREAM | Changing a stream’s metadata: SetStreamMetadata, AddStreamClosure, RemoveStreamClosure, SetStreamLineage. Reading it needs only READ_CANDLES. |
The node may grant less than the token asks for: security.max_permissions caps every session. Check before you rely on a permission. c.HasPermission requires every bit you pass. A client without a token asks for reading and writing on candles and trades and for ADMIN_STREAM, not LIST_STREAMS; only a node with authentication off accepts it; with authentication on, the default, the token alone decides.
if !c.HasPermission(client.PermWriteCandles) {
return fmt.Errorf("cannot write: granted %v", client.PermissionNames(c.GrantedPermissions()))
}Streams and records
A stream is client.NewStreamID(exchange, symbol, timeframe). The timeframe is a positive whole number and a unit, one of s, m, h, d, w: 30s, 1m, 5m, 1h, 1d, 1w. The node checks it on every request and refuses one it cannot read. There is nothing to create first: the first write to a stream registers it. stream.String() is symbol:timeframe:exchange, the form listing cursors use.
| Type | Fields |
|---|---|
client.Candle | Timestamp (Unix nanoseconds, the start of the bar), Open, High, Low, Close, Volume |
client.Tick | Timestamp (Unix nanoseconds), Price, Volume |
client.CandlePoint | One query result: a Candle, or a gap with IsGap, Status and Reason set (below) |
The node checks every record it is sent, and refuses the whole batch, before storing any of it, with ErrorCodeProtocol if one fails:
- Every value finite and storable. Values are kept to four decimal places, so their size must stay under about 9.2 × 1014.
- Volume zero or more. Prices may be negative: WTI settled at −$37.63 on 20 April 2020.
- A candle’s open and close between its low and high.
- Candles on the stream’s grid: one interval apart, counted from its first bar. Truncate the time to the interval,
t.Truncate(time.Minute).UnixNano(), and every bar lands on it.
Writing
stream := client.NewStreamID("binance", "SOLUSDT", "1m")
bars := []client.Candle{
{Timestamp: t.UnixNano(), Open: 152.40, High: 153.65, Low: 151.65, Close: 152.90, Volume: 12.5},
}
if err := c.IngestCandles(ctx, stream, bars, client.DurabilityAcked); err != nil {
log.Fatal(err)
}A stream is an exchange, a symbol and a timeframe. Timestamps are Unix nanoseconds. Trades go through IngestTicks with client.Tick (timestamp, price, volume) the same way.
| Durability | The call returns when |
|---|---|
DurabilityAcked | The batch is in the node’s write-ahead log and the log is fsynced. The zero value: you get it by not choosing. |
DurabilityFireAndForget | The bytes are written to the socket. A batch the node refuses is dropped with no signal back. |
Live writes land in memory near each stream’s newest data, a window of slots that is flushed to chunks as it fills: 50,000 slots for 1m streams and shorter, fewer for slower ones (2,048 for 30m and longer), or what an operator set with mirexa-cli cache. A batch spanning more slots than the window holds is refused. Writing a bar the stream already holds, at any age, restates it wherever the node keeps it (below); a bar older than everything the stream stores is refused: load it as history. A stream that goes quiet for a long time picks up again with its next write, and the time it was silent is filed as a gap.
When the node is busy
A node that cannot take a write right now sheds it with ErrorCodeOverloaded before storing anything, and says how long to wait. The client waits that long (at most 250 ms a time, plus a little jitter) and sends the batch again, up to 1,000 attempts. That cannot duplicate data: a shed batch provably was not stored. Tune it with Options.Retry (MaxAttempts 1,000, BaseBackoff 5 ms when the node gives no hint, MaxBackoff 250 ms); MaxAttempts: 1 turns it off. Reads the node sheds are re-sent the same way. Your context and RequestTimeout still bound the call, and a call shed every time fails with ErrRetriesExhausted. Nothing else is retried: no other error code, no fire-and-forget write, no subscription request.
ErrAmbiguous. It may or may not be stored, and the client will not guess or re-send it. Read the range back and send what is missing. Re-sending the whole candle batch is also safe: bars that landed are found unchanged and skipped. Trades have no such key, so send only the trades that are missing.The same is true of a write whose context you cancel after it was sent, or that hits ErrRequestTimeout: the node may still apply it.
Batching
b, err := client.NewCandleBatcher(c, stream, client.BatchOptions{
MaxRecords: 500,
MaxDelay: 50 * time.Millisecond,
})
if err != nil {
log.Fatal(err)
}
for bar := range feed {
if err := b.Add(ctx, bar); err != nil {
log.Fatal(err) // an earlier batch failed
}
}
if err := b.Close(); err != nil { // sends the rest; the last word on what failed
log.Fatal(err)
}A batcher sends a batch when it holds MaxRecords records or when its oldest record has waited MaxDelay, whichever comes first: size alone strands a slow stream, time alone sends half-empty batches on a fast one. Defaults are 1,000 records, 100 ms, acked. NewTickBatcher does the same for trades.
Add returns when a record is buffered, so a failed send shows up at a later Add, at Flush or at Close. Always check Close: it sends the last partial batch and is the one place you are sure to hear about a failure. A batcher accepts any client.Ingester, which a plain Client and a reconnecting one both are.
- A failed send poisons the batcher: every later call returns that error, because carrying on would mix stored and unstored records with no way to tell which is which.
Addwaits while a send is in progress. That is backpressure, not a stall.- A batcher serves one stream and is safe for many goroutines. Make one per symbol.
AddafterClosereturnsErrBatcherClosed. - A process that exits without
Closeloses whatever was buffered, and was never told it was stored.
History and corrections
Live writes go through the node’s write-ahead log and memory near the present. Two calls cover the rest:
// The bulk without waiting, then one acked call: when it returns, every
// staged candle has been compressed into chunks and can be read.
err := c.IngestHistoryCandles(ctx, stream, week[:100], client.DurabilityFireAndForget)
// …
err = c.IngestHistoryCandles(ctx, stream, week[100:], client.DurabilityAcked)// The exchange republished a closed bar: write it again.
err := c.IngestCandles(ctx, stream, []client.Candle{fixed}, client.DurabilityAcked)
// The strict form: refused if any bar is newer than the newest one stored.
err = c.IngestCorrectionCandles(ctx, stream, []client.Candle{fixed}, client.DurabilityAcked)History bypasses the log and writes chunks directly, so DurabilityAcked there means compressed and on disk, a stronger promise than the live path. A bar the stream already holds is restated by an ordinary write: the node decides, bar by bar, whether it is still in memory (replaced in place) or in a chunk (a patch that reads overlay), so you never need to know which. IngestCorrectionCandles routes bars the same way and refuses the whole batch if one of them is new: code that means to correct history is told when it is not. It is also how a gap is filled (below).
- History can land anywhere in time, including below data already written live. Sent fire-and-forget, it is staged but not yet readable; the acked call is what makes it readable. A chunk that fails to install fails the acked call.
- A bar identical to what is stored is skipped: nothing is written and subscribers are sent nothing for it, so re-sending a day costs a read, not a rewrite. Restating a flushed bar is written durably even when sent fire-and-forget, and costs about what five acked writes do.
- A restatement reaches only times the stream already holds, a stored bar or a hole between stored bars; a bar older than all of them is refused rather than ignored. A batch is a correction or history, never both. There is no history route for trades.
Reading
resp, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: stream,
StartTime: from.UnixNano(), // inclusive
EndTime: to.UnixNano(), // exclusive
})
if err != nil {
log.Fatal(err) // the request failed
}
if resp.Status != client.QueryStatusOK {
log.Fatal(resp.Status) // the request was fine; the data is not there
}
for _, p := range resp.Points {
fmt.Println(p.Candle.Timestamp, p.Candle.Close)
}An error means the request failed; Status reports an answer about the data: QueryStatusStreamNotFound or QueryStatusInvalidRange.
| QueryRequest field | What it does |
|---|---|
MaxResults | Stop after this many points. A response that stopped early has HasMore set; continue from one nanosecond past the last point. |
Descending | Newest first. With MaxResults: 100, the latest 100 bars; the node reads only the end of the range. |
IncludeGaps | Return each missing bar as a point with IsGap set (below). Trades have no gaps: a trade is an event, not a scheduled slot. |
AllowStale | In a cluster, let an in-sync copy answer when it is the node you asked (below). Candles only. |
Rollup | Bars of this length, made at query time from the stream’s candles (or, with Ticks, its trades) and stored nowhere (below). Not with AllowStale. |
Columns | Only these value columns of each candle, with the timestamp (below). Read with QueryColumns. Not with Ticks, IncludeGaps, AllowStale or Rollup. |
Large ranges
rows := c.QueryCandlesRows(ctx, client.QueryRequest{StreamID: stream, StartTime: 0, EndTime: now})
defer rows.Close()
for rows.Next() {
p := rows.Point()
_ = p
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}The iterator fetches page after page as you loop, so a range of any size never sits in memory at once. MaxResults is a cap on the total here, and a descending range pages newest first. Always check Err after the loop: a missing stream or a broken connection ends the loop exactly as the end of the data does, and without the check “no such stream” reads as “no data”. A refusal comes back as a *client.QueryStatusError. QueryTicks and QueryTicksRows are the same for trades.
Only some columns
cols, err := c.QueryColumns(ctx, client.QueryRequest{
StreamID: stream,
StartTime: from.UnixNano(),
EndTime: to.UnixNano(),
Columns: client.ColumnClose, // the timestamps and the close
})
if err != nil {
log.Fatal(err)
}
for i, ts := range cols.Timestamp {
fmt.Println(ts, cols.Close[i])
}A backtest that needs the close of a long history does not need the other four values of every bar. With Columns set, the node decodes only the columns you name, sends only those, and QueryColumns returns them as slices: Timestamp and one []float64 for each column asked for, with the others nil. A close-only row is 17 bytes on the wire where a whole bar is 49, and no struct is made per bar. Combine columns with |: client.ColumnOpen | client.ColumnVolume, or client.ColumnsAll.
QueryColumnspages for you likeQueryCandlesRows:MaxResultsis the total cap, andDescendingreads newest first. A request that names no column returnsErrNoColumns; a missing stream is a*client.QueryStatusError.- Slots without a candle are not rows, and there are no gap markers in the answer:
IncludeGapsis refused. A derived bar whose source had a hole is marked:cols.Incomplete(i). - One page, without the paging loop, is
c.QueryCandleswithColumnsset: the rows are inresp.Columns, andresp.Pointsis empty.QueryCandlesRowsrefuses a column request, since it iterates points. - Each sub-query of
QueryMultiAllmay ask for its own columns, beside plain ones: its rows come back inr.Columns.
Many streams in one round trip
res, err := c.QueryMultiAll(ctx, []client.QueryRequest{
{StreamID: sol, StartTime: a, EndTime: b},
{StreamID: sol, StartTime: a2, EndTime: b2}, // a second window of the same stream
{StreamID: eth, StartTime: a, EndTime: b},
})
for i, r := range res {
fmt.Println(i, r.Status, len(r.Points))
}Results come back in request order, each a complete, separate series; nothing is merged. A missing stream marks only its own result (QueryStatusStreamNotFound) and the rest are answered. Results too large for one response are completed for you, and MaxResults is a total per sub-query. Candle and trade sub-queries may be mixed: r.Ticks says which of r.Points and r.TickData holds the answer. A sub-query with Columns set (above) is answered in r.Columns instead, so a hundred symbols’ closes come back as a hundred pairs of slices in one round trip.
- A connection serves one request at a time, so a hundred symbols cost about one round trip instead of a hundred: roughly 50 ms saved on a network with a 0.5 ms round trip.
- A node takes at most 128 sub-queries in one request (
max_subqueries_per_request) and refuses a larger batch whole. - If the connection breaks part-way, the call returns the error and none of the results, rather than a half-labelled set.
c.QueryMultiis the raw single round trip, for callers who schedule the rounds themselves: a sub-query the response did not reach carriesHasMoreand aResumeFrom.
Gaps
A missing bar is one of two things: the market was closed, or data was lost. Mirexa keeps them apart, using each stream’s trading calendar, and the client reports which is which. A calendar is stream metadata, set on the node’s control listener with mirexa-cli calendar; changing it re-files the stream’s recorded gaps at once, so read a gap’s classification again rather than caching it.
resp, err := c.ListGaps(ctx, client.ListGapsRequest{StreamID: stream, StartTime: 0, EndTime: now})
if err != nil {
log.Fatal(err)
}
fmt.Println("missing:", time.Duration(resp.Summary.MissingDuration))
for _, g := range resp.Gaps { // each gap covers [StartTs, EndTs)
ok, why := g.Fillable()
fmt.Println(g.Status, g.Reason, ok, why)
}missing: 5m0s
OPEN UNKNOWN true| Status | Meaning |
|---|---|
GapStatusOpen | Data is missing and can still be backfilled. |
GapStatusFilling | A fill is under way. |
GapStatusClosed | It was missing and has been filled; kept on record. |
GapStatusPermanent | Not recoverable. Market closures are filed this way. |
GapStatusAccepted | An INCOMPLETE mark accepted as it is (below). Only an INCOMPLETE record is ever accepted. |
The reason is GapReasonOffTime for a market closure, which is not data loss; Network, Crash, Maintenance, RateLimit, Exchange, Corruption or Manual for a recorded cause of a loss; and Unknown when nobody said. GapReasonIncomplete is not a hole at all: it marks a derived bar made from less than its whole window, which a query returns as a candle (p.Incomplete()). A slot still in memory reports OPEN/UNKNOWN: not yet classified, rather than a guess.
A query with IncludeGaps answers per bar, so a weekend on a 1-minute stream is 2,880 gap points; ListGaps answers per hole, as ranges. A gap overlapping the window is returned whole, since a hole is not two holes because a window cut it. Summary describes the whole requested window, so it does not change as you page through Gaps with Limit and the cursor. OpenOnly and ExcludeOffTime narrow the list. Pages hold 200 gaps by default and at most 1,000 (a larger Limit is refused, not clamped); to continue, send the last gap’s StartTs as Cursor with HasCursor set. The summary’s MissingDuration counts only time genuinely absent, excluding closures and gaps already filled, and is the number to alert on: a stream for an exchange open 32 hours a week looks 80% incomplete by any naive count and is perfectly healthy. The node lists the gaps in data it has already written to chunks; the newest minutes show up as gap points in a query with IncludeGaps.
Filling one
if ok, _ := g.Fillable(); ok {
var bars []client.Candle
for t := g.StartTs; t < g.EndTs; t += int64(time.Minute) {
bars = append(bars, recovered(t)) // from your source of truth
}
err := c.IngestCorrectionCandles(ctx, stream, bars, client.DurabilityAcked)
}Once the bars are stored, every gap the correction covers completely is marked CLOSED, kept on record rather than deleted, and its missing time drops to zero. A partial fill leaves the gap open.
Fillable() says | Why |
|---|---|
true | The gap is open. |
FillRefusalMarketClosed | The market was shut; there is nothing to recover. |
FillRefusalPermanent | Marked unrecoverable (also the answer for a status this client does not know). |
FillRefusalAlreadyClosed | Already filled. |
FillRefusalInProgress | Another fill is running. |
FillRefusalAccepted | An incomplete bar accepted as it is. |
Fillable; never decide from the reason yourself. A market closure is not fillable: there was no trading, so anything written there would be invented, permanently. The node refuses such a fill too, and Fillable is the same rule it enforces.Ordinary writes of real bars during hours the calendar calls closed are not refused: data arriving then means the calendar is wrong (an extended session, a moved holiday), and the node keeps it.
Letting the node fill it
resp, err := c.FillGap(ctx, client.FillGapRequest{
StreamID: stream,
GapStart: g.StartTs, // exactly as ListGaps gave it
Method: client.FillMethodLinear, // or FillMethodForward, FillMethodBackward
})
// resp.Filled candles written; resp.HasMore: ask again, it continues the lineWhen the real bars are gone for good, the node can make them up from the real candles either side: a straight line from the close before the gap to the open after it, or flat at one neighbour. Every made-up candle has zero volume, the one mark a synthetic bar keeps once stored. The node refuses any gap Fillable refuses, writes the candles as a correction, and closes the gap once every slot holds one. MaxCandles caps one request (0 is the node’s cap). Re-sending is safe. Needs the write-candles permission.
Derived streams and rollups
A node can make candles itself: 1-minute bars from a stream’s trades, 5-minute bars from 1-minute ones, days from hours. What a stream is derived from is its lineage, declared once with SetStreamLineage (below) or mirexa-cli lineage set; from then on the node writes it as the source arrives, and copies replicate it like any stream. See the handbook for the rules.
Longer bars at query time
hourly, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: oneMinute, StartTime: from, EndTime: to,
IncludeGaps: true, Rollup: time.Hour, // from the stream's candles
})
bars, err := c.QueryCandles(ctx, client.QueryRequest{
StreamID: oneMinute, StartTime: from, EndTime: to,
Ticks: true, Rollup: time.Minute, // from its trades; answered as candles
})A rollup runs the rules a stored derivation runs, so it answers the same bars, marks included, and only closed ones. From candles the length must be a whole multiple, at least twice, of the stream’s own; a daily bar is the stream’s local trading date and a weekly bar starts on Monday. Anything else is refused with Protocol, naming why. A million trades into 1-minute bars took 45 ms, measured 2026-10-22.
INCOMPLETE bars
for _, p := range resp.Points {
if p.Incomplete() { // a real bar, made from less than its whole window
fmt.Println("partial bar at", p.Candle.Timestamp, p.Status)
}
}
mark, err := c.AcceptGap(ctx, client.AcceptGapRequest{
StreamID: derived, GapStart: g.StartTs, Accept: true, // false puts it back to OPEN
})A derived bar whose source had a hole under it is stored and served with an INCOMPLETE mark rather than dropped. Fill the source’s hole and the bar is derived again and the mark cleared; or accept it as it is, which sets GapStatusAccepted. g.AcceptAction() says which way a record may go. A gap of missing data is never accepted.
Writing a derived stream
err := c.OverwriteCandles(ctx, fiveMinute, bars, client.DurabilityAcked, client.RouteCorrection)Every ordinary write to a derived stream is refused with ErrorCodeDerivedStream before anything is stored, because the node would interleave its bars with yours. OverwriteCandles says you mean it: RouteLive, RouteHistory or RouteCorrection picks the route, and between your write and a later re-derivation of the same bar the last one written wins. FillGapRequest.Overwrite does the same for a fill.
Stream metadata
A stream’s trading calendar decides what each of its gaps means: inside its weekly hours a gap is missing data, outside them or inside a declared closure it is market closure, never fillable. The calendar, the gap thresholds, custom fields and the lineage are the stream’s metadata, read and set over the same connection as its data.
md := &client.StreamMetadata{
WorkingHours: &client.WorkingHours{Timezone: "America/New_York"},
GapThresholdLow: 2 * time.Minute, // pauses shorter than this are not gaps
}
for _, d := range []time.Weekday{time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday} {
md.WorkingHours.Schedule = append(md.WorkingHours.Schedule, client.DaySchedule{
Day: d, Windows: []client.TimeWindow{client.NewTimeWindow(9, 30, 16, 0)},
})
}
resp, err := c.SetStreamMetadata(ctx, client.SetStreamMetadataRequest{
StreamID: msft, Create: true, Metadata: md, // Create registers a stream the node does not know
})
// A holiday or a halt; removing a range cuts any closure it overlaps.
_, err = c.AddStreamClosure(ctx, client.AddStreamClosureRequest{StreamID: msft,
Closure: client.Closure{StartTs: start, EndTs: end, Note: "Thanksgiving"}})
_, err = c.RemoveStreamClosure(ctx, client.RemoveStreamClosureRequest{
StreamID: msft, StartTs: start, EndTs: end})
// Derive 5m bars from the 1m stream, from now on (LineageHistoryRederive: its history too).
_, err = c.SetStreamLineage(ctx, client.SetStreamLineageRequest{
StreamID: msft5, History: client.LineageHistoryFromNow,
Lineage: &client.Lineage{Source: msft, Kind: client.SourceCandles},
})
got, err := c.GetStreamMetadata(ctx, msft5) // got.Metadata.Lineage.Since: stamped by the node- Every change re-files the stream’s gaps at once. A filed outage inside a new closure becomes market closure;
resp.RefiledNanossays how much gap time changed class. A gap since filled with data never changes. - Each call answers with the metadata as the node now holds it. A stream the node does not know comes back as
resp.Status == client.QueryStatusStreamNotFound, as a query of one does; metadata the node refuses, such as an unknown timezone, is a*RemoteErrorwithErrorCodeProtocoland the reason. - The lineage has a call of its own.
SetStreamMetadatareplaces everything else and keeps the lineage; a request carrying one is refused before it is sent.LineageHistoryClearwith no lineage makes a derived stream plain again. - Changes need
ADMIN_STREAM. Every call is safe to re-send, so it is retried like a read, and a routing client sends it to the node that owns the stream. The node’s control listener does the same operations for an operator (mirexa-cli calendar,mirexa-cli lineage).
Subscriptions
sub, err := c.SubscribeStream(ctx, client.SubscribeRequest{
StreamID: stream,
Backfill: true, // stored history first,
StartTime: from.UnixNano(), // from here
})
if err != nil {
log.Fatal(err)
}
defer sub.Close()
for sub.Next(ctx) {
ev := sub.Event()
if ev.Dropped > 0 {
log.Printf("the node dropped %d batches: those bars are gone", ev.Dropped)
}
for _, bar := range ev.Candles {
_ = bar
}
}
if err := sub.Err(); err != nil {
log.Fatal(err)
}records=5 backfill=true live=false dropped=0
records=1 backfill=false live=true dropped=0Event.Livemarks the switch from history to live data. Across it there is no gap, but there can be a duplicate: a bar written while the history was being sent can arrive on both sides. Writes are idempotent by stream and timestamp; deduplicate on the same key if it matters.Event.Droppedcounts batches the node discarded because this subscriber fell behind, withMissingFirstandMissingLastnaming them. Dropped bars are gone, not late. A subscriber that keeps falling behind is ended withErrSlowConsumer; subscribe again with backfill.- A connection carries one subscription: use a separate client for each, and one goroutine to drive it. A delivery for another stream fails with
ErrForeignBatchrather than being mixed in. Request calls on the same client still work alongside it. - Keep reading: the client buffers only so much, and a consumer that stops reading eventually holds up every request on its client.
- Silence is normal: no
RequestTimeoutapplies toNext. Give it a context with a deadline if you want one. - An event’s slices are reused by the next
Next; copy what you keep.Event.Sequencenumbers live batches from 1 and history batches 0; let the client count drops rather than comparing sequences yourself. - Set
Ticks: trueto subscribe to trades.StartTime0 backfills from the earliest stored record. sub.Close()ends the loop but does not tell the node; callsub.Unsubscribe(ctx)first if it should stop sending. In-progress candles (Partials) are refused as unsupported: the node sends closed bars only.
Listing streams and nodes
resp, err := c.ListStreams(ctx, client.ListStreamsRequest{Exchange: "binance", IncludeStats: true, Limit: 100})
if err != nil {
log.Fatal(err)
}
for _, s := range resp.Streams {
fmt.Println(s)
}
// resp.HasMore: ask again with Cursor set to continueNeeds the LIST_STREAMS permission, which is separate from reading on purpose: a node can serve prices without disclosing which instruments it holds. Match, Exchange, Symbol and Timeframe filter; IncludeStats adds, per stream in resp.Stats, its record count and bytes on disk, first and last timestamps, missing time and gap counts.
- Paging is by key, not offset:
Cursoris the last stream’sString(), and the next page is everything after it. That stays right while streams are being created. There is no total count. Pages hold 200 by default and at most 1,000. - The node filters before cutting the page, so a filtered page is never short.
Symbolis a case-insensitive prefix (typeBTC, getBTCUSDT);ExchangeandTimeframeare exact.Matchreturns one stream by its full id, or nothing if it does not exist. SortBy(id by default; last update, record count or size on disk) withDescending. Any order but by id makes the node compute stats for every stream it holds, not just the page.- The counts and sizes are what is on disk; the timestamps include what is still in memory, so a stream being written has a last timestamp newer than its count.
- A
ResilientClienthasListStreamsAll(ctx), which pages to the end for you and resumes from its cursor across a reconnect, skipping and repeating nothing.
c.ListNodes(ctx) lists a cluster’s nodes as the node you asked knows them: id, whether it is serving or draining, how many partitions it is primary and copy of, and its address. An empty list means the node is on its own. c.NodeStats(ctx) returns the node’s own figures: CPU, memory and disk, what it holds and what it is primary of, ingest and query counters, live subscriptions and latency histograms; a figure it did not measure is marked unknown, never zero. Both need LIST_STREAMS.
Surviving disconnects
rc, err := client.DialResilient("localhost:8080", opts, client.ResilienceOptions{})
if err != nil {
log.Print(err) // not fatal: rc keeps trying, so you may start before the node
}
defer rc.Close()A ResilientClient has the same reads and writes as a Client and redials on its own: 3 attempts per call, backing off from 100 ms to 5 s, and a circuit breaker that opens after 5 failed connects in a row and refuses calls with ErrCircuitOpen for 30 s instead of making each one wait out the backoff. Reads retry across a reconnect; writes do not: a write in flight when the connection broke returns ErrAmbiguous. A write attempted while the connection is known to be down, including one the node closed while it sat idle, simply goes out on a fresh one.
| ResilienceOptions | Default | What it does |
|---|---|---|
MaxAttempts | 3 | Connection attempts within one call. 1 dials once. |
Backoff, MaxBackoff | 100 ms, 5 s | The wait between attempts, doubling with jitter. |
BreakerThreshold | 5 | Failed connects in a row that open the breaker. Negative turns it off. |
BreakerCooldown | 30 s | How long the breaker stays open before letting one call try. |
rc.State() is StateDisconnected, StateConnected, StateOpen (the breaker is refusing) or StateHalfOpen (the next call tries); rc.Reconnects() counts replaced connections. Goroutines that find the connection dead share one redial. rc.GrantedPermissions() is 0 while disconnected, which means “not connected”, not “granted nothing”. A row iterator re-fetches only the page it lost and resumes exactly; a multi-query loses only the round in flight.
To recover from ErrAmbiguous: read the range back and send what is missing with IngestCandles, or send the whole candle batch again, which restates what landed and writes what did not. The client does not do that for you, because a re-send overwrites any bar someone else restated in the meantime. A lost first batch is older than everything the stream stores; send it with IngestHistoryCandles.
sub, err := client.NewResumingSubscriber("localhost:8080", opts,
client.SubscribeRequest{StreamID: stream, Backfill: true, StartTime: from.UnixNano()},
client.ResumeOptions{})
if err != nil {
log.Fatal(err)
}
defer sub.Close()
for {
ev, err := sub.Next(ctx)
if err != nil {
log.Fatal(err)
}
_ = ev
}When its connection drops it redials and subscribes again from one nanosecond past the last bar it delivered, so you see a continuous stream and no bar twice. Every reconnect asks for history, because that is what fills the hole the disconnect left; Backfill in the request decides only the first subscription. ResumeOptions defaults to 5 reconnects in a row, 200 ms apart; sub.Reconnects() and sub.Redirects() count them, and sub.Unsubscribe(ctx) tells the node to stop. A ResilientClient does not cover subscriptions; this does.
Clusters
A Mirexa cluster spreads streams across nodes by partition, each with one primary and possibly in-sync copies. The client in this package holds one connection to one address and does not yet route on its own. Against a cluster:
- A node that does not serve the stream answers with a redirect: an error matching
ErrRedirect, whose*RedirectErrornames the serving node’sAddr, id, partition and epoch. The node redirects before storing anything, so a redirected write provably did not land, and sending it toAddris a first attempt, not a retry. - In
QueryMultiAll, a sub-query for a stream that lives elsewhere comes back with status0x04andr.Elsewherenaming the node; the rest of the batch is answered. - Two refusals have no named constant yet:
client.ErrorCode(0x0008), the node is behind on the cluster’s state (retry after its hint), andclient.ErrorCode(0x0009), the partition’s primary is down and has not yet been failed over (no hint; it heals on the cluster’s clock). - A partition being moved sheds its writes briefly with
ErrorCodeOverloaded, which the automatic retry rides out. - Stale reads. With
AllowStale: true, an in-sync copy may answer a candle query its primary cannot, for example while a dead primary waits to be failed over. The answer setsStale, andLevelAt(Unix nanoseconds) is when the copy last matched its primary: everything durable on the primary until then is in it. A copy answers only while it is within the node’scluster.copy_read_max_staleness(5 seconds by default) of its primary; one further behind redirects, as one outside the in-sync set does, so a stale answer is never older than that plus one heartbeat. Never for trades, never without the flag. This client sends a read where you point it and does not spread reads over copies itself. ResumeOptions{FollowRedirects: true}makes a resuming subscriber follow a redirect, at the first subscription and when its stream’s partition moves, resuming with history from the last bar delivered.- A write is acknowledged by the primary alone; copies pull from it shortly after. A graceful move loses no acknowledged write, but a primary that crashes can lose the last few milliseconds of writes it acknowledged.
Errors
var re *client.RemoteError
switch {
case errors.Is(err, client.ErrAmbiguous):
// may be stored: read the range back before sending again
case errors.As(err, &re):
if wait, ok := re.RetryAfter(); ok {
_ = wait // only ErrorCodeOverloaded: nothing was stored, try again later
}
log.Print(re.Code) // the node refused the request itself
}| Error | What happened, and what to do |
|---|---|
ErrAmbiguous | A write was in flight when the connection failed. It may be stored. Read back, then send what is missing. |
ErrRemote / *RemoteError | The node refused. Code says why: Unauthorized, Protocol, PayloadTooLarge, Unsupported, Internal, SlowConsumer, Overloaded, DerivedStream. Only Overloaded is retryable. Protocol is a request the node judged invalid, such as a bad batch or timeframe; Internal is the node’s own fault, and should not be replayed blindly. re.Message says more. |
ErrRetriesExhausted | Shed on every attempt. The last RemoteError is wrapped inside. |
ErrRequestTimeout | No reply within RequestTimeout. The request may still run on the node; its late reply is discarded, never handed to a later call. |
ErrClientClosed | The connection is gone: closed by you or by a network failure. |
ErrCircuitOpen | A resilient client is refusing calls after repeated failed connects. |
ErrSlowConsumer | A subscription fell too far behind and was ended. The client is still usable. |
ErrRedirect | This node does not serve the stream in a cluster; *RedirectError names the node that does. |
ErrForeignBatch | Two subscriptions on one client. Use a client per subscription. |
ErrInvalidOptions | An option value that cannot be meant, such as a negative timeout. |
ErrBatcherClosed | Add on a batcher after Close. |
*QueryStatusError | A row iterator’s query was refused in-band: the stream does not exist, or the range is invalid. |
Canceling a call’s context stops you waiting, not the request: it may still run on the node.
Observing the client
Set Options.Observer to anything with three methods, and attach whatever metrics you already run:
type metrics struct{}
func (metrics) IngestCompleted(s client.IngestStat) { /* s.Records, s.Attempts, s.Duration, s.Err */ }
func (metrics) StreamDelivered(s client.StreamStat) { /* one subscription delivery */ }
func (metrics) ConnectionChanged(s client.ConnStat) { /* connected, reconnects, breaker */ }IngestStat.Attempts is the number to watch: a batch the node shed and the client re-sent never reached storage, so no server-side counter sees a producer riding out backpressure. The methods run on the goroutine doing the work: count and return. A slow observer slows your writes, and one that panics takes the calling goroutine with it.
| Type | Fields |
|---|---|
IngestStat | One per call, not per attempt: StreamID, Ticks, Records, Attempts, Duration (backoff included), Err |
StreamStat | One per delivery: StreamID, Ticks, Records, Backfill, Live, Dropped |
ConnStat | A resilient client’s state changes: Addr, State, Reconnects, Failures (in a row), Err. A plain Client never reports one. |
Concurrency
Client,ResilientClientand batchers are safe for any number of goroutines.Subscription,ResumingSubscriberand the row iterators are not: one goroutine drives each.- A node works through one connection’s requests in order. When you want it to work on several at once, give each worker its own client.
- Canceling a context stops you waiting, not the request. Its late reply is discarded and never handed to a later call.
Testing
import "github.com/AmiraliOmidvar/mirexa/client/clienttest"
func TestAShedWriteIsRetried(t *testing.T) {
srv, err := clienttest.NewServer()
if err != nil {
t.Fatal(err)
}
defer srv.Close()
c, err := client.Dial(srv.Addr(), client.Options{})
if err != nil {
t.Fatal(err)
}
defer c.Close()
srv.FailNext(client.ErrorCodeOverloaded, "busy") // shed the next request once
stream := client.NewStreamID("binance", "BTCUSDT", "1m")
bar := client.Candle{Timestamp: time.Now().Truncate(time.Minute).UnixNano(), Open: 1, High: 1, Low: 1, Close: 1, Volume: 1}
if err := c.IngestCandles(context.Background(), stream, []client.Candle{bar}, client.DurabilityAcked); err != nil {
t.Fatalf("a shed write should be retried, got %v", err)
}
}clienttest.Server is an in-process node that speaks the real protocol, with no disk and no fixtures: SeedCandles, SeedTicks and SeedGaps load data, PublishCandles pushes to subscribers, FailNext makes the next request fail with a code, GrantPermissions sets what a session may do, LastToken shows the token your code presented, RequestCount counts requests by type and Close cuts every connection so you can drive your reconnect path. It is not the storage engine, since records live in a map, so use it to test how your code reacts to a node that answers, refuses or vanishes, and a real node to test storage. Gaps are seeded rather than worked out from the data, because whether a hole is an outage or a closure comes from a calendar, not from the hole.
The stream-metadata calls work against it as against a node: a stream is known once it holds data or was created, SetStreamMetadata keeps the lineage, closures merge and are cut, and a calendar a node would refuse is refused. SeedStreamMetadata stores metadata directly. The calendar files no gaps here, so RefiledNanos is always 0. FillGap, AcceptGap, ListNodes and NodeStats are refused as Unsupported.
Defaults
| Setting | Default |
|---|---|
| Transport | plaintext TCP |
| Dial and request timeouts | 10 s and 30 s |
| Largest reply | 16 MiB |
| Write durability | DurabilityAcked |
| Retry of shed requests | 1,000 attempts, from 5 ms, each wait at most 250 ms |
| Token lifetime | at most 1 hour; mirexa-cli token issue gives 30 minutes |
| Token renewal | with a TokenSource, at two-thirds of the token’s life |
| Without a token | refused (authentication is on); on a node with it off, read and write on candles and trades, no listing |
| Batcher | 1,000 records or 100 ms, whichever first |
| Resilient client | 3 attempts, 100 ms to 5 s, breaker after 5 failures for 30 s |
| Resuming subscriber | 5 reconnects, 200 ms apart; redirects not followed |
| List pages | 200, at most 1,000 (streams and gaps) |
| Sub-queries in one request | 128 (a node setting) |