Python client guide
A native Python client for Mirexa, with pandas support. It speaks Mirexa’s binary wire protocol directly, the same protocol as the Go client and the server, with no HTTP gateway in between.
pip install 'mirexa[pandas]'
Python 3.10+. The only required dependency is google-crc32c (a C checksum; a pure-Python
fallback exists). pandas comes with the pandas extra, polars with polars
(pip install 'mirexa[polars]'), NumPy with either.
Quickstart
import pandas as pd
import mirexa
btc = mirexa.StreamID(exchange="binance", symbol="BTCUSDT", timeframe="1m")
start = pd.Timestamp.now(tz="UTC").floor("1min") - pd.Timedelta(hours=1)
with mirexa.connect(ADDR) as client:
# Write candles from a DataFrame: a UTC DatetimeIndex and open/high/low/close/volume.
# Minute 2 is missing.
index = pd.DatetimeIndex([start + pd.Timedelta(minutes=m) for m in (0, 1, 3)], name="time")
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)
# Read them back. A query answers every interval in [start, end): the
# candles, and a classified marker for each interval that has none.
result = client.query_candles(btc, start, start + pd.Timedelta(minutes=4))
candles = result.to_pandas() # the candles only, no NaN rows
gaps = result.gaps_frame() # the holes: start, end, status, reason, fillable
pd.testing.assert_frame_equal(candles, frame, check_index_type=False)
assert list(gaps["start"]) == [start + pd.Timedelta(minutes=2)]
assert list(gaps["status"]) == ["OPEN"] and list(gaps["fillable"]) == [True]
# Data older than the live window goes in as a history back-fill.
client.ingest_dataframe(frame.set_axis(index - pd.Timedelta(days=30)), btc, mode="history")
What the client promises
The rules are the Go client’s, and the conformance suite holds the two to the same bytes.
Acknowledged writes are durable.
ingest_candles(..., durability="acked")(the default) returns once the batch is in the node’s write-ahead log.Only a shed is retried. A node under load answers
Overloadedbefore storing anything, so the client re-sends the batch, honoring the node’s retry hint. No other error is retried.A write that may have landed says so. If the connection fails while a write is on the wire,
AmbiguousWriteErroris raised: the batch may have been applied with only the acknowledgement lost. Reconcile by querying the range back. Re-sending a candle batch is safe (stored bars are restated, identical ones skipped), but the client does not do it for you: it would overwrite a bar someone else restated meanwhile, and a re-sent trade batch can store a trade twice.Re-sending a bar restates it. A candle the stream already stores is replaced by the one you send, whether the node still holds it in memory or has flushed it to disk; you do not need to know which. A bar identical to what is stored is skipped. A bar older than anything the stream stores is refused: load it with
mode="history".mode="correction"is the strict form, refusing a batch that carries a bar newer than the newest one stored. Neither writes into a market closure the node has filed.A write that never left is not ambiguous. Nodes close idle connections; the next write goes out on a fresh connection as a first attempt.
Reads are retried on a new connection after a transport failure.
Gaps are data, not NaN rows.
to_pandas()returns candles only;gaps_frame()returns each hole with its status and reason.fillableis computed by the server’s own rule: a market closure (reason == "OFF_TIME") is never fillable, because no data exists for it.Prices are exact on request. The server stores prices as fixed point with four decimals.
to_pandas(prices="decimal")returnsdecimal.Decimalvalues recovered exactly;float64is the default.Subscriptions report drops.
client.subscribe(stream, backfill=True)yields history, then live batches.Event.droppedcounts live batches the node dropped because the subscriber fell behind. History and live overlap at the boundary, so a bar can arrive twice: dedupe by timestamp. A dropped connection is resumed from just past the last bar delivered.
Reference
Call |
Does |
|---|---|
|
Connect to one node or a list of contact points. With |
|
Renew the token on every open connection now |
|
|
|
Trades. A negative price is legal |
|
Candles from a pandas or polars frame, in time order |
|
|
|
|
|
|
|
Every node’s streams. Needs the |
|
The cluster’s nodes (empty for a single node) |
|
The gap index as ranges, with a summary over the window |
|
Fill one OPEN gap with made-up candles: |
|
Accept a derived bar’s INCOMPLETE mark as it is, or put it back |
|
A stream’s trading calendar, gap thresholds, closures, custom fields and lineage. See Stream metadata |
|
Replace it (all but the lineage); the stream’s filed gaps are re-classified at once. Needs |
|
Declare or remove a holiday or halt. Needs |
|
Declare a stream derived from another’s |
|
An iterator of |
Times are Unix nanoseconds (int), datetime, ISO-8601 strings, pandas.Timestamp or
numpy.datetime64. A naive time is taken as UTC. A float is refused: seconds and
nanoseconds would be a guess.
Without a token the client presents an unsigned request for read and write permissions and for
setting stream metadata (ADMIN_STREAM), which only a node with authentication off accepts; pass
permissions= to ask for more (for example mirexa.PERM_LIST_STREAMS). With authentication on
a tokenless client is refused, and the token alone decides: mint one with mirexa-token issue.
Tokens
With authentication on, a node accepts a session token minted by mirexa-token issue, valid for
at most an hour. Give the client a token_file (or a token_source callable) rather than a fixed
token, and keep the file rotated:
client = mirexa.connect(ADDR, token_file="/run/secrets/mirexa-token")
Every connection then renews its token over the open connection, two-thirds into the token’s
life, reading the file again each time. The connection, the session and its subscriptions are
kept: a subscription runs on past its first token’s expiry without a reconnect or a backfill. A
renewal the node refuses (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; disable_renewal=True turns it off. A fixed token
is never renewed, since it has nothing newer to offer.
polars
Every result that has to_pandas() has to_polars(), and ingest_dataframe takes a polars
frame too. Polars has no index, so time is a time column (Datetime("ns", "UTC")):
from datetime import datetime, timedelta, timezone
import polars as pl
import mirexa
eth = mirexa.StreamID("binance", "ETHUSDT", "1m")
start = datetime.now(timezone.utc).replace(second=0, microsecond=0) - timedelta(hours=1)
# Minute 2 is missing.
frame = pl.DataFrame(
{
"time": [start + timedelta(minutes=m) for m in (0, 1, 3)],
"open": [3150.0, 3152.5, 3149.0],
"high": [3155.0, 3156.0, 3151.25],
"low": [3148.0, 3150.0, 3147.5],
"close": [3152.5, 3151.0, 3150.75],
"volume": [41.5, 22.0, 9.25],
}
).with_columns(pl.col("time").cast(pl.Datetime("ns", "UTC")))
with mirexa.connect(ADDR) as client:
client.ingest_dataframe(frame, eth)
result = client.query_candles(eth, start, start + timedelta(minutes=4))
assert result.to_polars().equals(frame)
gaps = result.gaps_polars() # the missing minute: start, end, status, reason, fillable
assert gaps["fillable"].to_list() == [True]
asyncio
mirexa.AsyncClient has the same constructor and methods, as coroutines:
import asyncio
import pandas as pd
import mirexa
async def main() -> None:
start = pd.Timestamp.now(tz="UTC").floor("1min") - pd.Timedelta(hours=1)
streams = [mirexa.StreamID("binance", symbol, "1m") for symbol in ("ETHUSDT", "SOLUSDT", "XRPUSDT")]
bar = mirexa.Candle(start.value, 100.0, 101.0, 99.5, 100.5, 7.0)
async with await mirexa.connect_async(ADDR) as client:
# Requests run concurrently over one connection per node.
await asyncio.gather(*(client.ingest_candles(s, [bar]) for s in streams))
results = await asyncio.gather(
*(client.query_candles(s, start, start + pd.Timedelta(minutes=1)) for s in streams)
)
assert all(r.candles == [bar] for r in results)
async with await client.subscribe(streams[0], backfill=True, start=start) as sub:
async for event in sub:
assert event.candles == [bar]
break
asyncio.run(main())
It is not a second implementation: both clients run the same request rules (retries, ambiguity,
redirects, resume), written once; only how they wait differs. The test suite runs every
behaviour test against both. Use one AsyncClient from one event loop. Cancelling a request
leaves the shared connection usable for the others.
Reading only some columns
A backtest that needs the close of a long history does not need the other four values of every
bar. query_columns asks the node for the stamps and only the columns you name, so one column
moves about a third of the bytes of query_candles (17 bytes a row where a whole bar is 49) and
makes no candle objects.
btc = mirexa.StreamID("binance", "ETHUSDT", "1m")
start = pd.Timestamp.now(tz="UTC").floor("1min") - pd.Timedelta(hours=3)
bars = [
mirexa.Candle(int((start + pd.Timedelta(minutes=m)).value), 2400.0 + m, 2402.0 + m, 2399.0 + m, 2401.0 + m, 10.0 + m)
for m in range(120)
]
client.ingest_candles(btc, bars)
closes = client.query_columns(btc, start, start + pd.Timedelta(hours=2), "close")
assert len(closes) == 120 and closes["close"][-1] == 2401.0 + 119 # a NumPy float64 array
assert closes.ts[0] == bars[0].timestamp # Unix nanoseconds
frame = closes.to_pandas() # a UTC "time" index and a close column
assert list(frame.columns) == ["close"]
newest = client.query_columns(btc, start, start + pd.Timedelta(hours=2), ["open", "volume"], limit=5, descending=True)
assert newest["open"].tolist() == [b.open for b in bars][::-1][:5]
columnsis a name, a list of names (open high low close volume) or"all". A name the node does not know raisesValueErrorbefore anything is sent.It pages until the range is done or
limitrows are collected;descending=Truewith alimitis the lastlimitrows, newest first.AsyncClient.query_columnsis the same call as a coroutine.Slots without a candle are not rows, and there are no gap markers in the answer.
result.incompleteis a mask of derived bars whose source had a hole, orNonewhen there are none.Not a rollup, a stale read or a trade query. A node that predates column queries refuses the request with a
RemoteErrorrather than answering with whole candles.
Derived streams, rollups and gap repair
A node can make candles itself: 1m bars from a stream’s trades, 5m from 1m, 1d from 1h. Declare
what a stream is derived from once, with client.set_stream_lineage (or mirexa-cli lineage set on the node’s control listener); from then on the node writes it as its source arrives, and copies replicate it like
any other stream.
btc = mirexa.StreamID("binance", "BTCUSDT", "1m")
# Bars of any length the rules can bucket, made at query time and stored nowhere:
# from the stream's candles, or with from_ticks from its trades.
hourly = client.query_candles(btc, "2026-10-01", "2026-10-08", rollup="1h")
from_trades = client.query_candles(btc, "2026-10-21T09:00", "2026-10-21T10:00", rollup="1m", from_ticks=True)
# A derived bar whose source had a hole under it is kept and MARKED, not dropped.
partial = [p for p in hourly.points if p.incomplete]
# Repair: fill an outage with candles made from its neighbours, or accept a marked bar as is.
for gap in client.list_gaps(btc, open_only=True).gaps:
if gap.fillable:
client.fill_gap(btc, gap.start, "linear")
A rollup follows the rules a stored derivation does, marks included, and answers only bars that are closed. From candles its length must be a whole multiple, at least twice, of the stream’s own; daily bars are the local trading date and weekly bars start on Monday.
Writing a derived stream yourself raises
DerivedStreamErrorand stores nothing, because the node would interleave its bars with yours.overwrite=Truewrites it anyway, and the last bar written wins.fill_gaprefuses a market closure: no data exists for those hours, so anything written there would be invented. It writes a correction, closes the gap once every slot holds a candle, and is safe to re-send.has_moreon the answer meansmax_candlesstopped it short.GapRange.accept_actionsays what may be done about a record:"accept"an OPEN incomplete mark,"unaccept"an accepted one, or nothing.
Stream metadata
A stream’s trading calendar decides what a gap means: inside the weekly hours it is missing data, outside them (or inside a declared closure) it is market closure, which is never fillable. Set it from the client, and every gap the node has already filed for the stream is re-classified at once.
import mirexa
from mirexa import StreamID, StreamMetadata, TimeWindow, WorkingHours
with mirexa.connect(ADDR) as client:
msft = StreamID("nyse", "MSFT", "1m")
calendar = StreamMetadata(
working_hours=WorkingHours.weekly("America/New_York", TimeWindow("09:30", "16:00")),
gap_threshold_low=2 * 60 * 1_000_000_000, # ignore pauses under two minutes
custom_fields={"desk": "equities"},
)
client.set_stream_metadata(msft, calendar, create=True) # create: register it if new
# A holiday: gaps inside it become market closure. refiled_ns says how much changed.
change = client.add_stream_closure(msft, "2026-11-26", "2026-11-27", "Thanksgiving")
print(change.metadata.closures, change.refiled_ns)
# Derive 5m bars from the 1m stream, from now on ("rederive" also derives its history).
msft5 = StreamID("nyse", "MSFT", "5m")
client.set_stream_metadata(msft5, StreamMetadata(), create=True)
client.set_stream_lineage(msft5, msft, "candles", history="from_now")
print(client.get_stream_metadata(msft5).lineage)
Reading needs
READ_CANDLES; every change needsADMIN_STREAM. A stream the node does not know raisesStreamNotFoundError(andset_stream_metadataregisters one only withcreate=True); metadata the node refuses, such as an unknown timezone, raisesRemoteErrorwith the reason.set_stream_metadatareplaces everything but the lineage, which it keeps: a lineage is set and cleared only withset_stream_lineage/clear_stream_lineage.Weekdaynumbers days as the server does, Sunday 0. Every call is safe to re-send.
Clusters
Give the client every node you know, or any one of them:
client = mirexa.connect(["10.0.0.1:9200", "10.0.0.2:9200", "10.0.0.3:9200"])
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 which node serves the stream, 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, so the request is a first attempt wherever it goes next.
Routes only move forward. Every redirect carries the partition’s epoch, a number that grows each time the partition changes node. An older answer never replaces a newer one. A node that redirects at an older epoch than one already seen has not caught up with a move yet; it is asked again a few times (about 1.3 s in all) before
NodeBehindError. Two nodes pointing at each other at the same epoch is aRedirectLoopError, raised at once.Writes carry the epoch the client believes. Once a redirect has taught it, every write carries the partition’s epoch, and a primary refuses a write that carries a superseded one, 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
AmbiguousWriteErroris never started over elsewhere.Subscriptions follow their stream. When a partition moves, its old node ends the subscription with a redirect; the subscription resumes on the new node from just past the last record it delivered (
sub.redirects,sub.addr).list_streams()asks every node for the streams it serves and merges them. If a node does not answer it raisesPartialListingError, with what the others returned attached, rather than return a listing that silently misses a node.
client.nodes() lists the cluster’s nodes; client.route_for(stream) and client.routing
show what the client has learned.
Performance
bench/backtest.py measures what Python users of Mirexa mostly do: load a universe into a
node, read it back into DataFrames, and run a strategy over them. One run, 2026-10-22, at
server 2fa192c and client 2e9ecad: 20 symbols × 1 year of 1-minute candles (10,512,000 rows),
one node on the same 12-core laptop; reads are the best of 3, the load ran once. The machine was not quiet (load average
8–10 from other test suites throughout), so treat these as floors.
Workload |
Rows/s |
Time |
|---|---|---|
Bulk load: |
127K |
83 s |
Read the universe into pandas |
5.40M |
1.95 s |
… into polars |
5.48M |
1.92 s |
… into pandas, |
6.55M |
1.61 s |
… the same reads through the Go SDK ( |
7.39M |
1.42 s |
… into pandas with the object-per-candle reference decoder |
382K |
27.5 s |
One symbol (525,600 rows) into pandas |
3.98M |
0.13 s |
SMA crossover over all 20 symbols: load 2.20 s + strategy 0.37 s |
4.08M |
2.58 s |
Reading into pandas takes 1.37× the Go SDK’s time for the same reads, and the asyncio client, which asks for the symbols concurrently, is within 1.13×. Decoding is not where the difference sits: the columnar decoder alone runs 44M rows/s against 571K for the reference, and for one symbol building the frame took 0.018 s of 0.13 s. Where the rest goes is not profiled.
Bulk loading is the slow path, 127K rows/s where reads run at millions.
bench/profile_load.py splits it (4 symbols × 1 year, 2026-10-22, load average 10.6):
The node waits on disk syncs, most of the time. Of 16.8 s of round trips, the client waited 10.9 s for answers while the node used 3.7 s of CPU. Each 50,000-row history batch is installed as about five chunks, each with about five fsyncs (
strace: 565 fsyncs for 22 requests, 12 ms each on average), so a request spends about 310 ms of its 390 ms syncing. The client sends one request at a time, so nothing overlaps them.The client’s own share is about a quarter: turning the frame into
Candleobjects took 3.5 s (600K rows/s) and encoding them 1.4 s (1.5M rows/s), most of it per-candle validation.Loading symbols concurrently helps. Four threads over four symbols ran at 477K rows/s against 296K for one at a time, both from candles already built (load average 6, which is why both beat the figure above).
ingest_dataframeloads one stream at a time; for a universe, give each symbol its own thread orasynciotask.
MIREXA_REPO=/path/to/mirexa python bench/backtest.py # this run
python bench/backtest.py --symbols 5 --days 30 # a quick smoke run
Results are written to bench/results/ (not committed).
Not yet
No automatic use of copies and no multi-stream queries.
allow_stale=Trueon a query lets a copy answer if the request lands on one (the result’sstaleandlevel_atsay so), and a copy further behind than the node’scluster.copy_read_max_staleness(5s by default) redirects instead, which the client follows to the primary. The Go routing client’s fallback to a copy when a primary is down and its spreading of reads over copies are not here, and neither isQueryMultiAll. Reads go where the route says.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).
A
fire_and_forgetwrite gets no answer, so it cannot be redirected: send those only to the node serving the stream.
Conformance
tests/conformance/wire-v2.json holds every frame this client speaks, as bytes beside what they
mean, each produced by the server’s own Go codecs and parsed back by them, and malformed frames
the server refuses, each with the reason it refuses them. The suite decodes every frame, encodes
every meaning back to the same bytes, and checks that every malformed frame is refused for the
same reason. The server repository does not carry a copy yet, so
test_the_vendored_suite_is_the_servers fails when MIREXA_REPO is set.
Development
python -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest # builds mirexa-server and mirexa-cli with `go build`
.venv/bin/ruff check src tests && .venv/bin/mypy
The server tests build mirexa-server, mirexa-cli and mirexa-certs from MIREXA_REPO
(default: the nearest parent directory holding the server’s go.mod), or use
MIREXA_SERVER_BIN, MIREXA_CLI_BIN and MIREXA_CERTS_BIN. Without a Go toolchain or binaries
they are skipped, not passed. tests/test_cluster.py runs a real two-node cluster (about 25 s);
-m "not cluster" leaves it out.