Connecting
The two clients, their options, and how to make one.
- mirexa.connect(addr: str | Sequence[str], **kwargs: Any) Client
A connected
Client;addris onehost:portor a list of contact points. See the constructor for the options.
- class mirexa.Client(addr: str | Sequence[str], **kwargs: Any)
A Mirexa client: one node, or a cluster reached through contact points.
addris onehost:portor a list of them. In a cluster each stream is served by one node, and the client finds it by following the redirects nodes answer with, remembers where each stream lives, and goes there directly next time. A single node never redirects, so nothing changes there.Thread-safe: requests from several threads share each node’s connection, each matched to its response by correlation id. For
asynciouseAsyncClient, which has the same methods and rules.Authentication, in order of precedence:
token_source(called at every connect),token_file(re-read at every connect),token. With none, the client presents an unsigned request forpermissions, which only a node with authentication off accepts.Renewal. With
token_sourceortoken_file, every connection renews its token over the open connection two-thirds into the token’s life — subscriptions included — so a session outlives its first token without a reconnect. The token is read again from its source each time, so whatever rotates the file is what the client renews with. A refused renewal is not retried: the session keeps its old token and ends with it, and the next connect presents a fresh one.disable_renewal=Trueturns this off;reauthenticate()renews now. A fixedtokenis never renewed: it has nothing newer to offer.Keyword options, all optional:
token,token_file,token_sourceHow a session authenticates, as above. A malformed
tokenis refused here, not at first use.permissionsWhat an unsigned request asks for. Default: read and write on candles and trades (
DEFAULT_UNAUTHENTICATED_PERMISSIONS).tlsTruefor TLS with the system’s trust store, or anssl.SSLContext. Default: plaintext.server_hostnameThe name the node’s certificate is checked against. Default: the host of the address dialled.
connect_timeout,request_timeoutSeconds for a connect and its handshake, and for a request’s answer. Defaults 10 and 30.
max_frame_bytesThe largest answer accepted. Default 16 MiB, the node’s own; at least 4 KiB.
retry_attempts,retry_base_backoff,retry_max_backoffRe-sending a request the node shed under load (
Overloaded), the only refusal retried; the node’s retry hint wins over the backoff. Defaults 1,000 attempts, 5 ms doubling, at most 250 ms a wait.reconnect_attempts,reconnect_backoff,reconnect_max_backoffDialling a node again, and how many connections a read (or a write that never left) is tried on. Defaults 3, 100 ms doubling, at most 5 s.
max_redirectsRedirects one request follows. Default 3.
disable_renewalTurns automatic token renewal off.
- reauthenticate() None
Renew the token on every open connection now, subscriptions’ included.
Each takes the grant the server names, keeps its session and its subscriptions, and re-arms its automatic renewal. Every connection is tried; the first refusal (a
RemoteError: a token from an untrusted issuer, expired, or naming another tenant) is raised after, and a refused connection keeps the token it had.
- ingest_candles(stream: StreamID, candles: Sequence[Candle], *, durability: Literal['acked', 'fire_and_forget'] = 'acked', mode: Literal['live', 'history', 'correction'] = 'live', overwrite: bool = False) None
Write a batch of candles.
ackedreturns once the batch is durable in the WAL of the node serving the stream;fire_and_forgetreturns once it is written to the socket, and is not redirected (no answer comes back to redirect it), so send it only to the node that serves the stream.mode="live"(the default) writes new bars and RESTATES bars the stream already stores, wherever the node keeps them: in memory they are replaced, and in a flushed chunk the node writes a patch that reads overlay. A bar identical to what is stored is skipped, so re-sending a batch rewrites nothing. A bar older than anything the stream stores is refused; send it withmode="history", the bulk back-fill.mode="correction"is the strict form of a restatement: the same routes, but a bar newer than the newest one stored refuses the whole batch, so code that means to correct history is told when it is not. Neither writes into a market closure the node has filed.A DERIVED stream (one the node makes from a source, see
mirexa-cli lineage) refuses a write withDerivedStreamErrorunlessoverwriteis set; with it, the bars land and the last one written wins against a later re-derivation of the same bar.Raises
AmbiguousWriteErrorif the connection fails with the batch on the wire.
- ingest_ticks(stream: StreamID, ticks: Sequence[Tick], *, durability: Literal['acked', 'fire_and_forget'] = 'acked') None
Write a batch of trades. Same durability and ambiguity rules as candles.
- ingest_dataframe(df: pd.DataFrame | pl.DataFrame, stream: StreamID, *, columns: dict[str, str] | None = None, time_column: str | None = None, batch_size: int = 5_000, durability: Durability = 'acked', mode: IngestMode = 'live', overwrite: bool = False) int
Write a pandas or polars DataFrame of candles; returns the number of rows written.
Times come from
time_column, else (pandas) aDatetimeIndex, else atimeortimestampcolumn: datetimes of any resolution (a naive one is taken as UTC) or integer Unix nanoseconds.columnsmaps this package’s names (open high low close volume) to the frame’s, for any that differ. Rows go in time order,batch_sizeper request; anAmbiguousWriteErrornames a batch whose fate is unknown, and every batch before it was acknowledged.
- query_columns(stream: StreamID, start: Any, end: Any, columns: str | Sequence[str] = 'close', *, limit: int | None = None, descending: bool = False) ColumnResult
Only some of each candle’s values over
[start, end): the stamps and thecolumnsnamed ("close", a sequence such as("open", "volume"), or"all"), as arrays.The node decodes and sends, and this holds, only those columns, so reading one column of a long stream moves a third of the bytes of
query_candles()and makes no candle objects. Slots without a candle are not rows: there are no gap markers in the answer. Pages until the range is exhausted orlimitrows are collected;descendingwith alimitis the LASTlimitrows, newest first.result.values["close"]is a NumPy array,result.tsthe Unix-nanosecond stamps, andto_pandas()/to_polars()build frames from them. Not a rollup, a stale read or a tick query.
- query_candles(stream: StreamID, start: Any, end: Any, *, limit: int | None = None, include_gaps: bool = True, descending: bool = False, allow_stale: bool = False, rollup: Any | None = None, from_ticks: bool = False) CandleResult
Every interval slot in
[start, end): candles and, withinclude_gaps, a marker for each slot that has none, classified.Pages until the range is exhausted or
limitslots are collected.descendingwith alimitis the LASTlimitslots, newest first.rollup(atimedelta, a timeframe like"5m", or nanoseconds) asks for bars of that length made at query time from the stream’s candles, or withfrom_ticksfrom its trades, and stored nowhere. They follow the rules a stored derivation does, marks included (CandlePoint.incomplete); only CLOSED bars are answered. From candles the length must be a whole multiple, at least twice, of the stream’s own. Not withallow_stale.
- query_ticks(stream: StreamID, start: Any, end: Any, *, limit: int | None = None, descending: bool = False) TickResult
Every trade in
[start, end).
- nodes() list[NodeInfo]
The cluster’s nodes, from the first contact point that answers. Empty for a single node with no cluster.
- list_streams(*, exchange: str = '', symbol: str = '', timeframe: str = '', match: str = '', stats: bool = False, page_size: int = 1000) list[StreamInfo]
Every stream, by id, from every node.
In a cluster this asks each serving node for the streams it is primary of, so each stream is heard once, from the node that serves it. A node that does not answer, or one that is down while still primary of partitions, raises
PartialListingErrorwith the rest attached: a listing that silently missed a node would read as streams that do not exist. NeedsLIST_STREAMS, which the default unauthenticated request does not ask for: passpermissions=or a token that grants it.
- list_gaps(stream: StreamID, start: Any = 0, end: Any = 2**63 - 1, *, open_only: bool = False, exclude_off_time: bool = False, page_size: int = 1000) GapList
A stream’s gaps as ranges, read from its gap index.
Only gaps in flushed chunks are listed; a hole still in the node’s hot cache appears after its next flush.
summarycovers the whole window.
- fill_gap(stream: StreamID, gap_start: Any, method: Literal['linear', 'forward', 'backward'] | FillMethod = 'linear', *, max_candles: int = 0, overwrite: bool = False) FillGapResponse
Fill one gap with candles made up from the real ones either side.
gap_startis a gap’s start exactly aslist_gaps()reported it.methodislinear(close before to open after),forward(carry the close before) orbackward(the open after). The node refuses a market closure (OFF_TIME) and any gap that is not fillable, writes the candles as a correction, and closes the gap once every slot holds one.has_moreon the answer saysmax_candles(0: the node’s cap) stopped it short: ask again. Safe to re-send. A derived stream needsoverwrite. NeedsWRITE_CANDLES.
- accept_gap(stream: StreamID, gap_start: Any, *, accept: bool = True) GapRange
Mark a derived bar’s INCOMPLETE mark ACCEPTED (“known incomplete, keep it”), or with
accept=Falseput an accepted mark back to OPEN.gap_startis the mark’s start aslist_gaps()reported it;GapRange.accept_actionsays which way a record can go. Returns the mark as it now stands. Safe to re-send. NeedsWRITE_CANDLES.
- get_stream_metadata(stream: StreamID) StreamMetadata
A stream’s metadata: trading calendar, gap thresholds, closures, custom fields, lineage. Raises
StreamNotFoundErrorfor a stream the node does not know. NeedsREAD_CANDLES.
- set_stream_metadata(stream: StreamID, metadata: StreamMetadata, *, create: bool = False) MetadataChange
Replace a stream’s metadata — everything but its lineage, which the node keeps (metadata carrying one is refused; use
set_stream_lineage()). The stream’s filed gaps are re-classified at once under the new calendar;refiled_nson the answer says how much.createregisters a stream the node does not know (andcreatedsays it did); without it an unknown stream raisesStreamNotFoundError. Metadata the node refuses raisesRemoteErrorwith the reason. Safe to re-send. NeedsADMIN_STREAM.
- add_stream_closure(stream: StreamID, start: Any, end: Any, note: str = '') MetadataChange
Declare that the stream’s market was (or will be) closed over
[start, end)— a holiday, a halt. It merges with closures it overlaps, and gaps inside it are re-filed as market closure, never fillable. Safe to re-send. NeedsADMIN_STREAM.
- remove_stream_closure(stream: StreamID, start: Any, end: Any) MetadataChange
Remove
[start, end)from the stream’s declared closures, cutting any closure it overlaps, and re-file the gaps they covered. Safe to re-send. NeedsADMIN_STREAM.
- set_stream_lineage(stream: StreamID, source: StreamID, kind: Literal['ticks', 'candles'] | SourceKind, *, history: Literal['from_now', 'rederive', 'clear'] | LineageHistory = 'from_now', close_grace: Any = 0, no_trade_limit: Any = 0) MetadataChange
Declare
streamderived fromsource’s"ticks"or shorter"candles": the node then writes its bars itself.historyis"from_now"(derive what arrives from now on) or"rederive"(also derive everything the source already holds).close_graceandno_trade_limitdefault to the node’s (1s, 10s). The node stampssince. Ordinary writes to the stream are refused from then on (seeoverwrite). Safe to re-send. NeedsADMIN_STREAM.
- clear_stream_lineage(stream: StreamID) MetadataChange
Make a derived stream a plain one again. Needs
ADMIN_STREAM.
- subscribe(stream: StreamID, *, ticks: bool = False, backfill: bool = False, start: Any = 0, resume: bool = True, resume_attempts: int = 5, resume_backoff: float = 0.2, follow_redirects: bool = True) Subscription
Stream new records as they are ingested, as an iterator of
Event.With
backfill, stored history fromstart(0 = the earliest the node holds) arrives first, then live data. The two overlap at the boundary, so a record ingested during the backfill can arrive twice: dedupe by timestamp. Withresume, a dropped connection is redialled and re-subscribed with a backfill from just past the last record delivered, so the hole is filled by history.With
follow_redirects, a subscription goes to the node serving the stream, and when the stream’s partition moves — the node ends the subscription with a redirect — it resumes on the new node the same way. Only a redirect at a strictly newer epoch is followed.Each subscription has its own connection.
- property fallbacks: int
Times a request restarted from the contact points after a node did not answer.
- property granted_permissions: int
What every connected node granted (their intersection; 0 before any handshake).
- route_for(stream: StreamID) Redirect | None
The node the client last learned serves
stream, orNone.
- property routing: RedirectorStats
Redirects followed, loops and behind-nodes refused, walks started.
- property seeds: list[str]
The contact points.
- async mirexa.connect_async(addr: str | Sequence[str], **kwargs: Any) AsyncClient
A connected
AsyncClient;addris onehost:portor a list of contact points.
- class mirexa.AsyncClient(addr: str | Sequence[str], **kwargs: Any)
The
asynciotwin ofClient: same constructor, same methods as coroutines, same rules. Use it from one event loop.Many requests may run concurrently (
asyncio.gather); they share each node’s connection, matched to their answers by correlation id.- async reauthenticate() None
- async connect() AsyncClient
Connect to the first contact point that answers; returns
self.
- async ingest_candles(stream: StreamID, candles: Sequence[Candle], *, durability: Literal['acked', 'fire_and_forget'] = 'acked', mode: Literal['live', 'history', 'correction'] = 'live', overwrite: bool = False) None
- async ingest_ticks(stream: StreamID, ticks: Sequence[Tick], *, durability: Literal['acked', 'fire_and_forget'] = 'acked') None
- async ingest_dataframe(df: pd.DataFrame | pl.DataFrame, stream: StreamID, *, columns: dict[str, str] | None = None, time_column: str | None = None, batch_size: int = 5_000, durability: Durability = 'acked', mode: IngestMode = 'live', overwrite: bool = False) int
See
mirexa.Client.ingest_dataframe(). Batches go one at a time, in time order, so anAmbiguousWriteErrorstill names the only batch whose fate is unknown.
- async query_columns(stream: StreamID, start: Any, end: Any, columns: str | Sequence[str] = 'close', *, limit: int | None = None, descending: bool = False) ColumnResult
- async query_candles(stream: StreamID, start: Any, end: Any, *, limit: int | None = None, include_gaps: bool = True, descending: bool = False, allow_stale: bool = False, rollup: Any | None = None, from_ticks: bool = False) CandleResult
- async query_ticks(stream: StreamID, start: Any, end: Any, *, limit: int | None = None, descending: bool = False) TickResult
- async list_streams(*, exchange: str = '', symbol: str = '', timeframe: str = '', match: str = '', stats: bool = False, page_size: int = 1000) list[StreamInfo]
- async list_gaps(stream: StreamID, start: Any = 0, end: Any = 2**63 - 1, *, open_only: bool = False, exclude_off_time: bool = False, page_size: int = 1000) GapList
- async fill_gap(stream: StreamID, gap_start: Any, method: Literal['linear', 'forward', 'backward'] | FillMethod = 'linear', *, max_candles: int = 0, overwrite: bool = False) FillGapResponse
- async get_stream_metadata(stream: StreamID) StreamMetadata
- async set_stream_metadata(stream: StreamID, metadata: StreamMetadata, *, create: bool = False) MetadataChange
- async add_stream_closure(stream: StreamID, start: Any, end: Any, note: str = '') MetadataChange
- async remove_stream_closure(stream: StreamID, start: Any, end: Any) MetadataChange
- async set_stream_lineage(stream: StreamID, source: StreamID, kind: Literal['ticks', 'candles'] | SourceKind, *, history: Literal['from_now', 'rederive', 'clear'] | LineageHistory = 'from_now', close_grace: Any = 0, no_trade_limit: Any = 0) MetadataChange
- async clear_stream_lineage(stream: StreamID) MetadataChange
- async subscribe(stream: StreamID, *, ticks: bool = False, backfill: bool = False, start: Any = 0, resume: bool = True, resume_attempts: int = 5, resume_backoff: float = 0.2, follow_redirects: bool = True) AsyncSubscription
See
mirexa.Client.subscribe(). Returns an async iterator ofEvent;async with await client.subscribe(...) as sub.
- property fallbacks: int
Times a request restarted from the contact points after a node did not answer.
- property granted_permissions: int
What every connected node granted (their intersection; 0 before any handshake).
- route_for(stream: StreamID) Redirect | None
The node the client last learned serves
stream, orNone.
- property routing: RedirectorStats
Redirects followed, loops and behind-nodes refused, walks started.
- property seeds: list[str]
The contact points.