Mirexa

Clients

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

go
// 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()))
output
[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.

OptionDefaultWhat it does
TokennoneA token from mirexa-cli token issue. Needed unless the node has authentication off. Never renewed.
TokenSourcenoneA 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.
TLSplaintextA *tls.Config to speak TLS 1.3 to a node that has it on.
DialTimeout10sHow long connecting and the handshake may take.
RequestTimeout30sHow long a request waits for its reply.
DisableRenewalfalseTurns off the automatic token renewal a TokenSource enables (below).
MaxFramePayloadBytes16 MiBThe largest reply the client accepts. Matches the node’s default.
Retry1,000 attemptsRe-sending of writes and reads the node sheds under load (below).
ObservernoneReceives 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:

shell
mirexa-cli token issue -key ./data/auth/issuer.key -perms READ_CANDLES -validity 30m > token.txt

For 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.

shell
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.pub

Tokens 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.

a token that outlives the hour
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 TokenSource in anything that runs longer than a token. It is called on every connect and every reconnect; a static Token would 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; DisableRenewal turns 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’s security.auth.subscriber_grace, 0 by default). A revoked issuer key ends its sessions at their next request.
PermissionAllows
READ_CANDLESCandle queries and subscriptions, ListGaps.
READ_TICKSTrade queries and subscriptions.
WRITE_CANDLESIngestCandles, IngestCorrectionCandles, IngestHistoryCandles.
WRITE_TICKSIngestTicks.
LIST_STREAMSListStreams, ListNodes, NodeStats. Separate from reading on purpose: serving prices and disclosing which instruments a node holds are different things.
ADMIN_STREAMChanging 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.

go
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.

TypeFields
client.CandleTimestamp (Unix nanoseconds, the start of the bar), Open, High, Low, Close, Volume
client.TickTimestamp (Unix nanoseconds), Price, Volume
client.CandlePointOne 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

go
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.

DurabilityThe call returns when
DurabilityAckedThe batch is in the node’s write-ahead log and the log is fsynced. The zero value: you get it by not choosing.
DurabilityFireAndForgetThe 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.

Fire-and-forget as a pipeline. Frames on one connection are handled in order, so an acked batch sent after a run of fire-and-forget ones proves all of them were handled. It does not prove they were accepted: a refused fire-and-forget batch is still dropped without a word.

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.

A write that was in flight when the connection died is 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

go
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.
  • Add waits 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. Add after Close returns ErrBatcherClosed.
  • A process that exits without Close loses 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:

a backfill
// 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)
a restated bar
// 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

a range
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 fieldWhat it does
MaxResultsStop after this many points. A response that stopped early has HasMore set; continue from one nanosecond past the last point.
DescendingNewest first. With MaxResults: 100, the latest 100 bars; the node reads only the end of the range.
IncludeGapsReturn each missing bar as a point with IsGap set (below). Trades have no gaps: a trade is an event, not a scheduled slot.
AllowStaleIn a cluster, let an in-sync copy answer when it is the node you asked (below). Candles only.
RollupBars of this length, made at query time from the stream’s candles (or, with Ticks, its trades) and stored nowhere (below). Not with AllowStale.
ColumnsOnly these value columns of each candle, with the timestamp (below). Read with QueryColumns. Not with Ticks, IncludeGaps, AllowStale or Rollup.

Large ranges

go
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

go
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.

  • QueryColumns pages for you like QueryCandlesRows: MaxResults is the total cap, and Descending reads newest first. A request that names no column returns ErrNoColumns; a missing stream is a *client.QueryStatusError.
  • Slots without a candle are not rows, and there are no gap markers in the answer: IncludeGaps is refused. A derived bar whose source had a hole is marked: cols.Incomplete(i).
  • One page, without the paging loop, is c.QueryCandles with Columns set: the rows are in resp.Columns, and resp.Points is empty. QueryCandlesRows refuses a column request, since it iterates points.
  • Each sub-query of QueryMultiAll may ask for its own columns, beside plain ones: its rows come back in r.Columns.

Many streams in one round trip

go
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.QueryMulti is the raw single round trip, for callers who schedule the rounds themselves: a sub-query the response did not reach carries HasMore and a ResumeFrom.

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.

go
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)
}
output
missing: 5m0s
OPEN UNKNOWN true
StatusMeaning
GapStatusOpenData is missing and can still be backfilled.
GapStatusFillingA fill is under way.
GapStatusClosedIt was missing and has been filled; kept on record.
GapStatusPermanentNot recoverable. Market closures are filed this way.
GapStatusAcceptedAn 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

go
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() saysWhy
trueThe gap is open.
FillRefusalMarketClosedThe market was shut; there is nothing to recover.
FillRefusalPermanentMarked unrecoverable (also the answer for a status this client does not know).
FillRefusalAlreadyClosedAlready filled.
FillRefusalInProgressAnother fill is running.
FillRefusalAcceptedAn incomplete bar accepted as it is.
Ask 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

go
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 line

When 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

go
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

go
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

go
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.

go
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.RefiledNanos says 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 *RemoteError with ErrorCodeProtocol and the reason.
  • The lineage has a call of its own. SetStreamMetadata replaces everything else and keeps the lineage; a request carrying one is refused before it is sent. LineageHistoryClear with 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

go
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)
}
output, one event a line
records=5 backfill=true  live=false dropped=0
records=1 backfill=false live=true  dropped=0
  • Event.Live marks 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.Dropped counts batches the node discarded because this subscriber fell behind, with MissingFirst and MissingLast naming them. Dropped bars are gone, not late. A subscriber that keeps falling behind is ended with ErrSlowConsumer; 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 ErrForeignBatch rather 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 RequestTimeout applies to Next. 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.Sequence numbers live batches from 1 and history batches 0; let the client count drops rather than comparing sequences yourself.
  • Set Ticks: true to subscribe to trades. StartTime 0 backfills from the earliest stored record.
  • sub.Close() ends the loop but does not tell the node; call sub.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

go
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 continue

Needs 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: Cursor is the last stream’s String(), 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. Symbol is a case-insensitive prefix (type BTC, get BTCUSDT); Exchange and Timeframe are exact. Match returns 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) with Descending. 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 ResilientClient has ListStreamsAll(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

go
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.

ResilienceOptionsDefaultWhat it does
MaxAttempts3Connection attempts within one call. 1 dials once.
Backoff, MaxBackoff100 ms, 5 sThe wait between attempts, doubling with jitter.
BreakerThreshold5Failed connects in a row that open the breaker. Negative turns it off.
BreakerCooldown30 sHow 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.

a subscription that reconnects
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 *RedirectError names the serving node’s Addr, id, partition and epoch. The node redirects before storing anything, so a redirected write provably did not land, and sending it to Addr is a first attempt, not a retry.
  • In QueryMultiAll, a sub-query for a stream that lives elsewhere comes back with status 0x04 and r.Elsewhere naming 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), and client.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 sets Stale, and LevelAt (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’s cluster.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

go
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
}
ErrorWhat happened, and what to do
ErrAmbiguousA write was in flight when the connection failed. It may be stored. Read back, then send what is missing.
ErrRemote / *RemoteErrorThe 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.
ErrRetriesExhaustedShed on every attempt. The last RemoteError is wrapped inside.
ErrRequestTimeoutNo reply within RequestTimeout. The request may still run on the node; its late reply is discarded, never handed to a later call.
ErrClientClosedThe connection is gone: closed by you or by a network failure.
ErrCircuitOpenA resilient client is refusing calls after repeated failed connects.
ErrSlowConsumerA subscription fell too far behind and was ended. The client is still usable.
ErrRedirectThis node does not serve the stream in a cluster; *RedirectError names the node that does.
ErrForeignBatchTwo subscriptions on one client. Use a client per subscription.
ErrInvalidOptionsAn option value that cannot be meant, such as a negative timeout.
ErrBatcherClosedAdd on a batcher after Close.
*QueryStatusErrorA 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:

go
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.

TypeFields
IngestStatOne per call, not per attempt: StreamID, Ticks, Records, Attempts, Duration (backoff included), Err
StreamStatOne per delivery: StreamID, Ticks, Records, Backfill, Live, Dropped
ConnStatA resilient client’s state changes: Addr, State, Reconnects, Failures (in a row), Err. A plain Client never reports one.

Concurrency

  • Client, ResilientClient and batchers are safe for any number of goroutines.
  • Subscription, ResumingSubscriber and 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

go
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

SettingDefault
Transportplaintext TCP
Dial and request timeouts10 s and 30 s
Largest reply16 MiB
Write durabilityDurabilityAcked
Retry of shed requests1,000 attempts, from 5 ms, each wait at most 250 ms
Token lifetimeat most 1 hour; mirexa-cli token issue gives 30 minutes
Token renewalwith a TokenSource, at two-thirds of the token’s life
Without a tokenrefused (authentication is on); on a node with it off, read and write on candles and trades, no listing
Batcher1,000 records or 100 ms, whichever first
Resilient client3 attempts, 100 ms to 5 s, breaker after 5 failures for 30 s
Resuming subscriber5 reconnects, 200 ms apart; redirects not followed
List pages200, at most 1,000 (streams and gaps)
Sub-queries in one request128 (a node setting)

The Python client

Package mirexa speaks the node’s binary protocol directly, the same one the Go client and the server speak, with no HTTP gateway in between. It reads straight into pandas, polars or NumPy and writes from a DataFrame. Examples that show their output were run against a node; the others assume a client and a stream.

Import
import mirexa
Dependencies
google-crc32c; pandas, polars and NumPy optional
Concurrency
threads, or asyncio with AsyncClient
Python
3.10 or newer

Installing

The client is not on PyPI yet. Install it from a checkout of its repository, with the extras you want:

shell
pip install -e './python-client[pandas]'          # pandas (and NumPy)
pip install -e './python-client[pandas,polars]'   # polars too

The only required dependency is google-crc32c, a C implementation of the checksum every frame carries; a pure-Python fallback exists but is slow. Without NumPy the client still works: results come back as Python objects, and the DataFrame methods say which package they need.

Connecting

python
import mirexa

# A node started with -data-dir ./data writes its admin token here.
with mirexa.connect("localhost:8080", token_file="data/auth/admin.token") as client:
    btc = mirexa.StreamID("binance", "BTCUSDT", "1m")
    result = client.query_candles(btc, "2026-10-21", "2026-10-22")

mirexa.connect returns a connected Client; mirexa.Client(addr) builds one that connects on its first request. addr is one host:port or a list of them (Clusters). One client is safe from any number of threads: requests share each node’s connection and each is matched to its own answer. Closing it, or leaving the with block, ends every connection.

OptionDefaultWhat it does
tokennoneA token from mirexa-cli token issue. Needed, or one of the two below, unless the node has authentication off. Never renewed.
token_filenoneA file holding a token, read at every connect and every renewal (below).
token_sourcenoneA callable returning a token; takes precedence over the two above.
permissionsread and writeWhat an unsigned request asks for, when there is no token.
tlsplaintextTrue, or an ssl.SSLContext (TLS).
connect_timeout10 sHow long connecting and the handshake may take.
request_timeout30 sHow long a request waits for its answer.
max_frame_bytes16 MiBThe largest answer accepted. Matches the node’s default.
retry_attempts1,000Re-sending of requests the node sheds under load (below).
reconnect_attempts3Dialling a node again, and how many connections a read is tried on.
disable_renewalFalseTurns off the token renewal a token_file or token_source enables.

A value that cannot be meant, such as an address without a port, a malformed token or a frame cap under 4 KiB, raises ValueError when the client is built rather than a confusing connection error later.

Authentication

Authentication is on by default: a node accepts only sessions that present a token signed by an issuer key it trusts. Tokens are minted offline with mirexa-cli token issue and live at most an hour. A single node with no trusted_keys configured makes its own issuer key and keeps an admin token in <data_dir>/auth/admin.token, re-minted every 20 minutes, so token_file pointed at it always reads a current one; the Go tab shows how to mint narrower tokens and use your own key. With security.auth.enabled: false, a client without a token presents an unsigned request, and the permissions it asks for are taken on trust.

a client that outlives its token
client = mirexa.connect(ADDR, token_file="/run/secrets/mirexa-token")  # rotated by your orchestrator
  • Renewal. With token_file or token_source, every connection renews its token over the open connection two-thirds of the way through the token’s life, reading the file again each time. The session and its subscriptions are kept: a subscription runs on past its first token’s expiry without a reconnect or a backfill.
  • A refused renewal (an untrusted issuer, an expired token, another tenant) changes nothing and is not retried; the session ends with its old token and the next connect presents a fresh one. client.reauthenticate() renews now and raises the first refusal.
  • A fixed token is never renewed: it has nothing newer to offer. Use it for scripts that finish within the hour.
python
if not client.granted_permissions & mirexa.PERM_WRITE_CANDLES:
    raise SystemExit("this token cannot write candles")

The node may grant less than the token asks for: security.max_permissions caps every session. client.granted_permissions is what the connected nodes granted, as a bit set of PERM_READ_CANDLES, PERM_READ_TICKS, PERM_WRITE_CANDLES, PERM_WRITE_TICKS, PERM_ADMIN_STREAM (changing a stream’s metadata) and PERM_LIST_STREAMS. An unsigned request asks for all but the last; with authentication on it is refused, and the token alone decides. Listing is separate from reading on purpose: pass permissions=mirexa.DEFAULT_UNAUTHENTICATED_PERMISSIONS | mirexa.PERM_LIST_STREAMS to a node with authentication off.

Streams and records

python
btc = mirexa.StreamID(exchange="binance", symbol="BTCUSDT", timeframe="1m")
bar = mirexa.Candle(timestamp=1_792_670_400_000_000_000, open=64250.0, high=64270.0,
                    low=64240.0, close=64260.5, volume=12.5)
trade = mirexa.Tick(timestamp=1_792_670_400_250_000_000, price=64251.5, volume=0.02)

A stream is one instrument at one timeframe on one exchange. A candle’s timestamp is the start of its interval, in Unix nanoseconds, aligned to the timeframe. Candles and trades are frozen dataclasses.

  • Times anywhere the client takes one may be Unix nanoseconds (int), datetime, an ISO-8601 string, pandas.Timestamp or numpy.datetime64. A naive time is taken as UTC. A float is refused: whether it means seconds or nanoseconds would be a guess.
  • Prices are stored as fixed point with four decimals (FIXED_POINT_SCALE). A trade’s price may be negative: oil settled below zero once.

Writing

python
client.ingest_candles(btc, [bar])                    # returns once the batch is in the node's WAL
client.ingest_ticks(btc, [trade])
client.ingest_candles(btc, [bar], durability="fire_and_forget")
  • Acknowledged writes are durable. With durability="acked", the default, a write returns once the batch is in the write-ahead log of the node that serves the stream.
  • Only a shed is retried. A node under load answers Overloaded before storing anything, so the client re-sends the batch, honoring the node’s retry hint, up to retry_attempts. Every other refusal is raised at once; re-sending it unchanged gets the same answer.
  • A write that may have landed says so. If the connection fails while a write is on the wire, AmbiguousWriteError is raised: the batch may have been applied with only the acknowledgement lost. Query the range back and send what is missing. Re-sending the whole candle batch is also safe, since stored bars are restated and identical ones skipped; a trade batch is not, because two trades can share a timestamp.
  • A write that never left is not ambiguous. Nodes close connections that sit idle; the next write goes out on a fresh connection as a first attempt.
  • fire_and_forget returns once the batch is written to the socket. No answer comes back, so a refusal is never seen and a redirect cannot be followed: send it only to the node that serves the stream.

A live write takes new bars, and restates any bar the stream already holds, however old (below). A bar older than everything the stream stores is refused, and the refusal says where it should go:

python
old = mirexa.Candle(month_ago_ns, 1, 1, 1, 1, 1)
try:
    client.ingest_candles(btc, [old])
except mirexa.RemoteError as e:
    print(e.message)
output
batch not admissible: write to BTCUSDT:1m:binance covers 1 timestamp(s) in no chunk and outside the hot cache (first 1790157720000000000, last 1790157720000000000), older than anything the stream stores; a restatement can only reach a bar that is stored, so back-fill this range as history instead

DataFrames

python
import pandas as pd

start = pd.Timestamp.now(tz="UTC").floor("1min") - pd.Timedelta(hours=1)
index = pd.DatetimeIndex([start + pd.Timedelta(minutes=m) for m in (0, 1, 3)], name="time")  # minute 2 is missing
frame = pd.DataFrame(
    {"open": [64250.0, 64260.5, 64255.25], "high": [64270.0, 64270.0, 64262.0],
     "low": [64240.0, 64251.0, 64250.0], "close": [64260.5, 64255.25, 64261.0],
     "volume": [12.5, 8.25, 3.0]},
    index=index,
)
client.ingest_dataframe(frame, btc)

result = client.query_candles(btc, start, start + pd.Timedelta(minutes=4))
print(result.to_pandas())
print(result.gaps_frame())
output
                               open     high      low     close  volume
time
2026-10-22 12:19:00+00:00  64250.00  64270.0  64240.0  64260.50   12.50
2026-10-22 12:20:00+00:00  64260.50  64270.0  64251.0  64255.25    8.25
2026-10-22 12:22:00+00:00  64255.25  64262.0  64250.0  64261.00    3.00
                      start                       end status   reason  fillable fill_refusal
0 2026-10-22 12:21:00+00:00 2026-10-22 12:22:00+00:00   OPEN  UNKNOWN      True

ingest_dataframe takes a pandas or polars frame: times from time_column, else a DatetimeIndex, else a time or timestamp column, as datetimes of any resolution or integer nanoseconds. columns= maps open high low close volume to the frame’s names where they differ. Rows go in time order, batch_size (5,000) per request, and it returns how many it wrote. An AmbiguousWriteError from it names the batch whose fate is unknown; every batch before it was acknowledged.

MethodReturns
to_pandas()The candles only, on a UTC DatetimeIndex named time. No NaN rows for holes.
gaps_frame()Each hole: start, end, status, reason, fillable, fill_refusal.
to_polars(), gaps_polars()The same as polars frames. Polars has no index, so time is a time column, Datetime("ns", "UTC").
to_numpy()A structured array of the candles.
to_pandas(prices="decimal")Prices as decimal.Decimal, recovered exactly from the stored fixed point. float64 is the default.

With NumPy installed, a query’s pages are decoded straight into columns, and a frame is built from them without a Python object per candle. result.candles and result.points build the objects only when asked for.

History and corrections

python
client.ingest_dataframe(last_year, btc, mode="history")      # bulk back-fill, any age
client.ingest_candles(btc, [restated_bar])                     # restate a bar the node stores
client.ingest_candles(btc, [restated_bar], mode="correction")  # the same, refusing any new bar
  • mode="history" loads data older than the live window, at any age, below or between what the stream already holds. Use it for back-fills and imports.
  • Writing a stored bar restates it, in the hot cache or flushed, with or without a mode: the node decides where each bar goes. A restatement of flushed data is kept beside the original chunk, survives restarts, and a second one to the same chunk is served too. A bar identical to what is stored is skipped, so re-sending a batch rewrites nothing.
  • mode="correction" is the strict form: the same routes, but a bar newer than the newest one stored refuses the whole batch.
  • Filling an outage closes its gap. A write that puts a bar into an open gap marks that gap CLOSED; the record that the range was back-filled is kept.
  • Nothing fills a market closure. A gap whose reason is OFF_TIME covers hours the exchange was shut; anything written there would be invented, so the node refuses it, in any mode.

A correction that turns out to carry new data is refused, and says so:

python
try:
    client.ingest_candles(btc, [next_bar], mode="correction")
except mirexa.RemoteError as e:
    print(e.code == mirexa.ErrorCode.PROTOCOL, e.message)
output
True batch not admissible: correction for BTCUSDT:1m:binance holds 1 bar(s) past the newest one the stream stores (first 1792749720000000000, last 1792749720000000000); a correction restates stored history, so send new bars as an ordinary write

Reading

python
result = client.query_candles(btc, "2026-10-01", "2026-10-22")
last_100 = client.query_candles(btc, start, end, limit=100, descending=True)
trades = client.query_ticks(btc, start, end).to_pandas()
hourly = client.query_candles(btc, start, end, rollup="1h")   # made at query time

A candle query answers every interval in [start, end): the candles, and a classified marker for each interval that has none. It pages on its own until the range is done or limit slots are collected; descending=True with a limit is the last limit slots, newest first. A CandleResult has .points (every slot, in order), .candles, .gaps and the frame methods above. include_gaps=False asks for candles only.

A read changes nothing, so after a transport failure it is retried on a new connection. A stream the node has never seen raises StreamNotFoundError.

Only some columns

python
closes = client.query_columns(btc, "2026-01-01", "2026-10-01", "close")
closes.ts                # Unix nanoseconds, a NumPy int64 array
closes["close"]          # a NumPy float64 array
closes.to_pandas()       # a DataFrame: a UTC "time" index and a close column

bars = client.query_columns(btc, start, end, ["open", "volume"], limit=500, descending=True)
everything = client.query_columns(btc, start, end, "all")

query_columns asks the node for the timestamps and only the columns you name, so reading one column of a long history moves about a third of the bytes of query_candles (17 bytes a row where a whole bar is 49) and builds no candle objects. A ColumnResult has .ts, .values (a dict by column name, also reachable as result["close"]), to_pandas() and to_polars(). It pages until the range is done or limit rows are collected, and descending=True with a limit is the last limit rows. Slots without a candle are not rows and there are no gap markers; result.incomplete is a mask of derived bars whose source had a hole, or None when there are none. Not a rollup, a stale read or a trade query. AsyncClient.query_columns is the same call as a coroutine.

Gaps

A hole is data, not a NaN row. Each one carries a status (OPEN, FILLING, CLOSED, PERMANENT, and ACCEPTED for an accepted INCOMPLETE mark) and a reason (OFF_TIME when the stream’s trading calendar says the market was shut, UNKNOWN when nothing explains it, INCOMPLETE for a derived bar made from less than its window), and fillable is the node’s own rule: an open outage can be filled, a closure never.

python
gaps = client.list_gaps(btc, start, start + pd.Timedelta(hours=1))
print(gaps.summary)
missing = gaps.to_pandas()
to_fill = missing[missing["fillable"]]
output
GapSummary(missing_duration=60000000000, off_time_duration=0, count=1, open_count=1, off_time_count=0, fillable_count=1)

list_gaps reads the stream’s gap index as ranges: one row for a weekend instead of a marker per minute. open_only=True and exclude_off_time=True narrow it; summary totals the whole window. Only flushed data is indexed, so a hole still in the node’s hot cache is listed after its next flush, while a query shows it at once. A gap’s fill_refusal() says why it cannot be filled, or "" if it can. A stream’s calendar is set on the node with mirexa-cli calendar set, and changing it re-files the stream’s gaps at once.

python
for gap in client.list_gaps(btc, open_only=True).gaps:
    if gap.fillable:
        done = client.fill_gap(btc, gap.start, "linear")   # or "forward", "backward"
        print(done.filled, done.has_more)

When the real bars are gone for good, fill_gap asks the node to make them up from the real candles either side. Every made-up candle has zero volume. The node refuses a closure, writes a correction, and closes the gap once every slot holds a candle; has_more means max_candles stopped it short, so ask again. It is safe to re-send.

Derived streams and rollups

A node can make candles itself: 1-minute bars from trades, 5-minute bars from 1-minute ones, days from hours. Declare what a stream is derived from with client.set_stream_lineage (below) or mirexa-cli lineage set; the node then writes it as its source arrives. The handbook has the rules.

python
hourly = client.query_candles(btc, "2026-10-01", "2026-10-08", rollup="1h")
bars = client.query_candles(btc, start, end, rollup=dt.timedelta(minutes=1), from_ticks=True)

partial = [p for p in hourly.points if p.incomplete]       # real bars, made from less than their window
marks = [g for g in client.list_gaps(derived).gaps if g.accept_action == "accept"]
client.accept_gap(derived, marks[0].start)                  # accept=False puts it back

client.ingest_candles(five_min, bars, mode="correction", overwrite=True)
  • rollup takes a timeframe like "5m", a timedelta, or nanoseconds. It follows the rules a stored derivation does and answers only closed bars; from candles the length must be a whole multiple, at least twice, of the stream’s own. Not with allow_stale.
  • A derived bar whose source had a hole under it is kept with an INCOMPLETE mark. Fill the source and it is derived again; or accept_gap it as it is. GapRange.accept_action says which way a record may go.
  • Writing a derived stream raises DerivedStreamError and stores nothing. overwrite=True writes it anyway, on ingest_candles, ingest_dataframe and fill_gap, and the last bar written wins.

Stream metadata

A stream’s trading calendar decides what its gaps mean: inside the weekly hours a gap is missing data, outside them or inside a declared closure it is market closure, never fillable. The calendar, gap thresholds, custom fields and lineage are read and set over the same connection as the data.

python
from mirexa import StreamMetadata, TimeWindow, WorkingHours

calendar = StreamMetadata(
    working_hours=WorkingHours.weekly("America/New_York", TimeWindow("09:30", "16:00")),
    gap_threshold_low=2 * 60 * 1_000_000_000,   # pauses under two minutes are not gaps
    custom_fields={"desk": "equities"},
)
client.set_stream_metadata(msft, calendar, create=True)   # create: register it if new

change = client.add_stream_closure(msft, "2026-11-26", "2026-11-27", "Thanksgiving")
change.refiled_ns                                          # gap time re-filed as market closure
client.remove_stream_closure(msft, "2026-11-26", "2026-11-27")

client.set_stream_lineage(msft5, msft, "candles", history="from_now")   # or "rederive"
client.get_stream_metadata(msft5).lineage                  # since: stamped by the node
client.clear_stream_lineage(msft5)
  • Every change re-files the stream’s filed gaps at once and answers a MetadataChange: the metadata as the node now holds it, created, and refiled_ns.
  • A stream the node does not know raises StreamNotFoundError; set_stream_metadata registers one only with create=True. Metadata the node refuses, such as an unknown timezone, raises RemoteError with the reason.
  • set_stream_metadata keeps the stream’s lineage, and refuses metadata carrying one: a lineage is set only with set_stream_lineage.
  • WorkingHours.weekly puts the same windows on Monday to Friday; for anything else, a DaySchedule per day. Weekday numbers days as the server does, Sunday 0.
  • Changes need PERM_ADMIN_STREAM; reading needs PERM_READ_CANDLES. Every call is safe to re-send.

Subscriptions

python
with client.subscribe(btc, backfill=True, start=start) as sub:
    for event in sub:
        print(event.backfill, event.live, event.sequence, len(event.candles), event.dropped)
        if event.live:
            break
output
True False 0 3 0
False True 1 1 0
  • History, then live. With backfill=True, stored bars from start arrive first (event.backfill), then live batches as they are ingested. The two overlap at the boundary, so a bar can arrive twice: dedupe by timestamp.
  • Drops are counted, not hidden. A subscriber that falls behind has live batches dropped; event.dropped on the next one says how many. A subscriber that stays behind is cut off with SlowConsumerError.
  • A dropped connection resumes on its own, with a backfill from just past the last bar delivered, so the hole is filled from history (resume_attempts, 5; sub.reconnects).
  • sub.next(timeout=1.0) waits at most that long and returns None on a quiet stream. ticks=True subscribes to trades. Each subscription has its own connection.

Listing streams and nodes

python
for s in client.list_streams(exchange="binance", stats=True):
    print(s.stream, s.stats.record_count, s.stats.chunk_count, s.stats.gap_count)
output
BTCUSDT:1m:binance 3 1 1

list_streams needs PERM_LIST_STREAMS. It filters by exchange, symbol, timeframe or a match on the id, and pages on its own. With stats=True each stream carries its record and byte counts, first and last timestamps, chunks, patches and gaps. client.nodes() lists the cluster’s nodes (id, address, whether serving or draining, primaries and copies), and is empty for a single node.

Clusters

python
client = mirexa.connect(["10.0.0.1:9200", "10.0.0.2:9200", "10.0.0.3:9200"], token_file=TOKEN_FILE)

Give the client every node you know, or any one of them. Each stream is served by one node: the client sends a request to a contact point, follows the redirect the node answers with, and remembers where the stream lives, so the next request goes there directly. The rules are the Go client’s:

  • Following a redirect is always safe, write or not. A node redirects before it stores anything.
  • Routes only move forward. Each redirect carries the partition’s epoch, which grows every time the partition changes node, and an older answer never replaces a newer one. A node redirecting at an older epoch has not caught up with a move yet and is asked again for about 1.3 s before NodeBehindError; two nodes pointing at each other at one epoch is a RedirectLoopError, raised at once.
  • Writes carry the epoch the client believes, and a primary refuses one that carries a superseded epoch, with a redirect to where the partition went.
  • A node that does not answer sends the request back to the contact points, past any that do not answer either. An AmbiguousWriteError is never started over elsewhere.
  • Subscriptions follow their stream. When a partition moves, its old node ends the subscription with a redirect, and it resumes on the new node from just past the last bar delivered (sub.redirects, sub.addr).
  • list_streams() asks every node. If one does not answer it raises PartialListingError with what the others returned, rather than a listing that silently misses streams.

client.route_for(stream) and client.routing show what the client has learned.

asyncio

python
import asyncio

async def main() -> None:
    streams = [mirexa.StreamID("binance", s, "1m") for s in ("BTCUSDT", "ETHUSDT", "SOLUSDT")]
    async with await mirexa.connect_async(ADDR) as client:
        results = await asyncio.gather(*(client.query_candles(s, start, end) for s in streams))
        frames = {r.stream.symbol: r.to_pandas() for r in results}

        async with await client.subscribe(streams[0], backfill=True) as sub:
            async for event in sub:
                ...

asyncio.run(main())

mirexa.AsyncClient has the same constructor and methods as coroutines, and the same rules: both clients run one implementation of retries, ambiguity, redirects and resume, and the test suite runs every behaviour test against both. Requests run concurrently over one connection per node. Use one AsyncClient from one event loop; cancelling a request leaves the shared connection usable for the others.

TLS

python
import ssl

ctx = ssl.create_default_context(cafile="ca.crt")
client = mirexa.connect("node1.internal:9200", tls=ctx, token_file=TOKEN_FILE)

ctx.load_cert_chain("client.crt", "client.key")  # for a node that requires client certificates

tls=True uses the system’s trust store; an ssl.SSLContext gives you the CA, client certificates and anything else. The node’s certificate is checked against the host dialled, or server_hostname=. A plaintext client gets nothing from a TLS node, and a certificate from an untrusted CA or for another host is refused at connect.

Errors

python
try:
    client.ingest_candles(btc, batch)
except mirexa.AmbiguousWriteError:
    reconcile(btc, batch)          # read the range back; send only what is missing
except mirexa.RemoteError as e:
    log.error("refused (%s): %s", e.code, e.message)

Every error is a MirexaError. Three families decide what to do next:

ErrorMeaning
RemoteErrorThe node refused the request; code is an ErrorCode, message says why. Re-sending it unchanged gets the same answer. Subclasses: UnauthorizedError, SlowConsumerError, PartitionUnavailableError, OverloadedError, DerivedStreamError.
RetriesExhaustedErrorThe node shed the request on every attempt.
AmbiguousWriteErrorThe connection failed with a write on the wire. It may have been applied: reconcile by reading back.
TransportErrorThe connection failed or could not be made. RequestTimeoutError and ClientClosedError are kinds of it, as is AmbiguousWriteError.
QueryStatusErrorA query answered with a status other than OK; StreamNotFoundError for a stream the node has never seen.
RedirectLoopError, NodeBehindErrorThe cluster’s nodes disagree about where a stream lives, or one has not caught up with a move.
PartialListingErrorA cluster-wide listing some nodes did not answer: streams holds the rest, failed names each node.
WireFormatErrorBytes that do not decode. The connection is dropped, since it can no longer be trusted to be in step.

Defaults

SettingDefault
Transportplaintext TCP
Connect and request timeouts10 s and 30 s
Largest answer16 MiB
Write durability"acked"
Retry of shed requests1,000 attempts, from 5 ms, each wait at most 250 ms
Reconnect3 attempts, from 100 ms, each wait at most 5 s
Redirects per request3
Token renewalwith token_file or token_source, at two-thirds of the token’s life
Without a tokenrefused (authentication is on); on a node with it off, read and write on candles and trades, no listing
ingest_dataframe batch5,000 rows
Subscription resume5 attempts, 200 ms apart; redirects followed
List pages1,000 (streams and gaps)

Not yet

  • No automatic use of copies and no multi-stream queries. allow_stale=True on a query lets a copy answer if the request lands on one, and the answer carries stale and level_at; the Go side’s fallback to a copy when a primary is down, and its spreading of reads over copies, are not here, and neither is QueryMultiAll.
  • A subscription that loses its node reconnects to that same node; it does not go back to the contact points. The Go client’s resuming subscriber behaves the same way.
  • No in-process test server like Go’s clienttest; test against a real node.
  • A stream’s trading calendar lives on the node’s control listener; set it with mirexa-cli calendar set.