Connecting

The two clients, their options, and how to make one.

mirexa.connect(addr: str | Sequence[str], **kwargs: Any) → Client

A connected Client; addr is one host:port or 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.

addr is one host:port or 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 asyncio use AsyncClient, 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 for permissions, which only a node with authentication off accepts.

Renewal. With token_source or token_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=True turns this off; reauthenticate() renews now. A fixed token is never renewed: it has nothing newer to offer.

Keyword options, all optional:

token, token_file, token_source

How a session authenticates, as above. A malformed token is refused here, not at first use.

permissions

What an unsigned request asks for. Default: read and write on candles and trades (DEFAULT_UNAUTHENTICATED_PERMISSIONS).

tls

True for TLS with the system’s trust store, or an ssl.SSLContext. Default: plaintext.

server_hostname

The name the node’s certificate is checked against. Default: the host of the address dialled.

connect_timeout, request_timeout

Seconds for a connect and its handshake, and for a request’s answer. Defaults 10 and 30.

max_frame_bytes

The largest answer accepted. Default 16 MiB, the node’s own; at least 4 KiB.

retry_attempts, retry_base_backoff, retry_max_backoff

Re-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_backoff

Dialling 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_redirects

Redirects one request follows. Default 3.

disable_renewal

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

connect() → Client

Connect to the first contact point that answers; returns self.

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.

acked returns once the batch is durable in the WAL of the node serving the stream; fire_and_forget returns 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 with mode="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 with DerivedStreamError unless overwrite is set; with it, the bars land and the last one written wins against a later re-derivation of the same bar.

Raises AmbiguousWriteError if 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) a DatetimeIndex, else a time or timestamp column: datetimes of any resolution (a naive one is taken as UTC) or integer Unix nanoseconds. columns maps this package’s names (open high low close volume) to the frame’s, for any that differ. Rows go in time order, batch_size per request; an AmbiguousWriteError names 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 the columns named ("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 or limit rows are collected; descending with a limit is the LAST limit rows, newest first. result.values["close"] is a NumPy array, result.ts the Unix-nanosecond stamps, and to_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, with include_gaps, a marker for each slot that has none, classified.

Pages until the range is exhausted or limit slots are collected. descending with a limit is the LAST limit slots, newest first.

rollup (a timedelta, a timeframe like "5m", or nanoseconds) asks for bars of that length made at query time from the stream’s candles, or with from_ticks from 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 with allow_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 PartialListingError with the rest attached: a listing that silently missed a node would read as streams that do not exist. Needs LIST_STREAMS, which the default unauthenticated request does not ask for: pass permissions= 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. summary covers 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_start is a gap’s start exactly as list_gaps() reported it. method is linear (close before to open after), forward (carry the close before) or backward (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_more on the answer says max_candles (0: the node’s cap) stopped it short: ask again. Safe to re-send. A derived stream needs overwrite. Needs WRITE_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=False put an accepted mark back to OPEN.

gap_start is the mark’s start as list_gaps() reported it; GapRange.accept_action says which way a record can go. Returns the mark as it now stands. Safe to re-send. Needs WRITE_CANDLES.

get_stream_metadata(stream: StreamID) → StreamMetadata

A stream’s metadata: trading calendar, gap thresholds, closures, custom fields, lineage. Raises StreamNotFoundError for a stream the node does not know. Needs READ_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_ns on the answer says how much. create registers a stream the node does not know (and created says it did); without it an unknown stream raises StreamNotFoundError. Metadata the node refuses raises RemoteError with the reason. Safe to re-send. Needs ADMIN_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. Needs ADMIN_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. Needs ADMIN_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 stream derived from source’s "ticks" or shorter "candles": the node then writes its bars itself. history is "from_now" (derive what arrives from now on) or "rederive" (also derive everything the source already holds). close_grace and no_trade_limit default to the node’s (1s, 10s). The node stamps since. Ordinary writes to the stream are refused from then on (see overwrite). Safe to re-send. Needs ADMIN_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 from start (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. With resume, 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, or None.

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; addr is one host:port or a list of contact points.

class mirexa.AsyncClient(addr: str | Sequence[str], **kwargs: Any)

The asyncio twin of Client: 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

See mirexa.Client.reauthenticate().

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

See mirexa.Client.ingest_candles().

async ingest_ticks(stream: StreamID, ticks: Sequence[Tick], *, durability: Literal['acked', 'fire_and_forget'] = 'acked') → None

See mirexa.Client.ingest_ticks().

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 an AmbiguousWriteError still 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

See mirexa.Client.query_columns().

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

See mirexa.Client.query_candles().

async query_ticks(stream: StreamID, start: Any, end: Any, *, limit: int | None = None, descending: bool = False) → TickResult

See mirexa.Client.query_ticks().

async nodes() → list[NodeInfo]

See mirexa.Client.nodes().

async list_streams(*, exchange: str = '', symbol: str = '', timeframe: str = '', match: str = '', stats: bool = False, page_size: int = 1000) → list[StreamInfo]

See mirexa.Client.list_streams().

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

See mirexa.Client.list_gaps().

async fill_gap(stream: StreamID, gap_start: Any, method: Literal['linear', 'forward', 'backward'] | FillMethod = 'linear', *, max_candles: int = 0, overwrite: bool = False) → FillGapResponse

See mirexa.Client.fill_gap().

async accept_gap(stream: StreamID, gap_start: Any, *, accept: bool = True) → GapRange

See mirexa.Client.accept_gap().

async get_stream_metadata(stream: StreamID) → StreamMetadata

See mirexa.Client.get_stream_metadata().

async set_stream_metadata(stream: StreamID, metadata: StreamMetadata, *, create: bool = False) → MetadataChange

See mirexa.Client.set_stream_metadata().

async add_stream_closure(stream: StreamID, start: Any, end: Any, note: str = '') → MetadataChange

See mirexa.Client.add_stream_closure().

async remove_stream_closure(stream: StreamID, start: Any, end: Any) → MetadataChange

See mirexa.Client.remove_stream_closure().

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

See mirexa.Client.set_stream_lineage().

async clear_stream_lineage(stream: StreamID) → MetadataChange

See mirexa.Client.clear_stream_lineage().

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 of Event; 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, or None.

property routing: RedirectorStats

Redirects followed, loops and behind-nodes refused, walks started.

property seeds: list[str]

The contact points.