Mirexa

Wiki Guides

Writing data

How to write candles and ticks to Mirexa — the three write routes, batching a live feed, what the live path accepts, handling refusals and ambiguous failures — from Go, the command line and Python.

Every write sends one batch of records for one stream and chooses a route and a durability. This guide covers which to choose, how to feed a stream continuously, what the node accepts and refuses, and how to handle each kind of failure. The concepts behind it are in Corrections, restatements and history and Durability.

Choosing a route

You are writing Route Go CLI Python
Bars as a feed produces them, or re-sending bars you already sent live IngestCandles ingest ingest_candles(..., mode="live")
Corrections of bars the stream holds, refusing anything new correction IngestCorrectionCandles ingest -correct mode="correction"
Bulk history the stream does not hold history IngestHistoryCandles ingest -history mode="history"
Trades live (ticks) IngestTicks ingest -ticks ingest_ticks
Bars of a stream the node derives any, with overwrite OverwriteCandles ingest -overwrite overwrite=True

A plain live write is forgiving: a bar the stream already stores is restated with the values you send, wherever the node keeps it, and an identical one is skipped. You rarely need the correction route except to be told when a "correction" is actually new data.

For files on disk, use mirexa-cli load rather than writing a loader.

Writing from Go

go
// Authentication is on by default: read the token from a file on every connect.
// A single node with no keys configured writes its own to <data_dir>/auth/admin.token.
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 {
	return err
}
defer c.Close()

stream := client.NewStreamID("binance", "BTCUSDT", "1m")
err = c.IngestCandles(ctx, stream, candles, client.DurabilityAcked)
  • DurabilityAcked (the zero value) blocks until the node's acknowledgement: the batch is in the write-ahead log and fsynced. DurabilityFireAndForget returns once the bytes are on the socket and tells you nothing, including about refusals.
  • A Client is safe for concurrent use; requests overlap on one connection, though the node serves one connection's requests in order. Use several clients for server-side parallelism.
  • Ticks: c.IngestTicks(ctx, stream, ticks, client.DurabilityAcked).
  • Writing needs the WRITE_CANDLES (or WRITE_TICKS) permission when authentication is on.

Batching a live feed

A feed that produces one record at a time should be batched. The batcher sends when either threshold is reached first: MaxRecords buffered (default 1,000), or the oldest buffered record has waited MaxDelay (default 100 ms).[1]

go
b, err := client.NewCandleBatcher(c, stream, client.BatchOptions{
	MaxRecords: 1000,
	MaxDelay:   100 * time.Millisecond,
})
if err != nil {
	return err
}
for candle := range feed {
	if err := b.Add(ctx, candle); err != nil {
		return err
	}
}
return b.Close() // sends the last partial batch and returns the final verdict
  • Add returning nil means buffered, not stored. A failed flush surfaces at a later Add, at Flush or at Close, and poisons the batcher: every later call returns it.
  • Always check Close. A program that exits without it loses what was buffered.
  • One batcher per stream; NewTickBatcher for trades. Add blocks during a flush — that is backpressure.
  • The batcher accepts a *Client or a *ResilientClient (which reconnects by itself).

Writing from the command line

bash
./bin/cli ingest -stream binance:BTCUSDT:1m < candles.csv

The CSV is timestamp,open,high,low,close,volume for candles and timestamp,price,volume for ticks (-ticks), no header, timestamps in RFC 3339 or Unix nanoseconds.[2]

Flag Default Meaning
-addr localhost:8080 node address
-stream — exchange:symbol:timeframe
-ack true wait for each batch's acknowledgement; -ack=false is fire-and-forget
-batch 1000 records per frame
-flush 100ms send a partial batch once its oldest record is this old
-ticks false read trades
-correct false strict correction
-history false bulk history route
-overwrite false write a derived stream (combines with -history or -correct)
-token, -token-file $MIREXA_TOKEN session token
-tls-ca, -tls-server-name — TLS
-reconnect 3 connection attempts per operation

-history and -correct cannot be combined, and neither applies to ticks. The command prints a summary on standard error, including any batches that were shed and retried.

What the live path accepts

Each stream has a hot cache: a window of slots ending near its newest data (50,000 slots for 1m and shorter by default, 10,000 for 5m, 2,048 for 30m and longer; see Streams). For a live write:[3]

  • Bars must be on the stream's grid and valid (see Candles and ticks). One bad bar refuses the whole batch with Protocol.
  • New bars land inside the window or past its leading edge. A stream idle for a long time simply resumes; the span it skipped is recorded as a gap.
  • A batch may span at most as many slots as the stream's cache holds. A wider batch is refused with Protocol ("split it"). Split it, or send old data by the history route.
  • Bars older than the window that the stream holds (in a chunk, or in a hole between stored bars) are restated. Bars older than everything the stream holds are refused with HistoryRequired.
  • Bars inside a filed market closure are refused when they restate history.
  • When the cache is full, the node waits briefly for a flush to make room (admission_wait × admission_retries, 10 ms × 3 by default), then sheds the batch with Overloaded.

Keep batches for one stream in time order and send old bars and brand-new bars in separate batches. A batch reaching both back past the cache and forward past what a flush can make room for is refused as "older than the stream's hot cache holds".

Handling errors

Error What it means What to do
nil (acked) Durable in the log. —
*RemoteError Overloaded Nothing stored. The SDK already retried it (Options.Retry, default 1,000 attempts); after ErrRetriesExhausted, back off and re-send.
*RemoteError Protocol The batch does not fit the stream; nothing stored. The message says why. Fix the data; do not retry unchanged.
*RemoteError HistoryRequired Bars no chunk or cache can hold; nothing stored. Re-send those bars with IngestHistoryCandles.
*RemoteError DerivedStream The stream is derived; nothing stored. Write with OverwriteCandles if you mean to.
*RemoteError Unauthorized The session lacks the permission. Fix the token.
ErrRedirect (*RedirectError) Cluster: another node serves this stream; nothing stored. Send to Addr — a first attempt, not a retry.
ErrAmbiguous The connection died mid-write; the batch may or may not be stored. Candles: re-send the batch. Ticks and history: read back and send what is missing.

Branch on codes with errors.As:

go
var remote *client.RemoteError
if errors.As(err, &remote) {
	if _, retryable := remote.RetryAfter(); retryable {
		// only Overloaded is retryable
	}
	switch remote.Code {
	case client.ErrorCodeDerivedStream:
		// ...
	}
}

HistoryRequired has no exported constant in the Go client package at this commit; compare remote.Code with client.ErrorCode(0x000B). The full list is in Error codes.

Surviving disconnects

client.DialResilient returns a client that redials on demand, shares one redial among concurrent callers, and opens a circuit breaker after repeated connection failures. Reads are re-run across a reconnect; writes in flight return ErrAmbiguous, and a write whose connection was already dead goes out fresh. It returns a usable client even when the first dial fails, so a program can start before its node.[4]

From Python

The Python SDK (mirexa, its own repository) has the same routes and rules: ingest_candles(stream, candles, durability="acked", mode="live"), ingest_ticks, and ingest_dataframe for a pandas or polars frame. See Python SDK.

References

Source

Tests

Further reading


  1. Example_batcher; TestBatcher_DelayIsMeasuredFromTheOldestRecord, TestBatcher_FailedFlushPoisonsTheBatcher. ↩︎

  2. runIngest, parseCandleRow, parseTickRow in /cmd/cli/main.go. ↩︎

  3. TestIngest_ABatchWiderThanTheArenaIsRefusedNotShed, TestIngest_AFullHotCacheWaitsForTheFlushInsteadOfRefusing, TestIngest_AResumedStreamFilesTheAbsenceBeforeIt; the admission knobs are ingestion.live_candle.admission_wait and admission_retries in /internal/config/config.go. ↩︎

  4. Example_resilientClient, TestResilient_InFlightWriteIsAmbiguousNotRetried. ↩︎