Skip to content

Live capture

Run a live source into a directory of segments, and read back the manifest.json that records them. See Capture live data for how segments, rolls, reconnects and restarts work.

run_capture async

run_capture(
    make_source: SourceFactory, config: CaptureConfig
) -> CaptureRun

Capture live data into a directory of segments, for as long as asked.

make_source builds a fresh source for each segment: a source keeps connection and book state for one run and cannot be reused. config gives the pair, the capture directory (out_dir), the total run time (minutes), and the roll limits (roll_minutes, roll_mb).

A new out_dir (or an empty one) starts a new capture. One holding a manifest.json for the same source, pair and level is continued; any other contents are refused with :class:~ob_analytics.exceptions.ConfigError. So is a directory another capture process is writing to: the capture holds a lock on out_dir while it runs.

SIGINT/SIGTERM stop the capture: the running segment is closed with its closing rows and the manifest is finished. A second signal stops it at once: a segment still closing is cancelled and closed from its files, as one that does not stop in time is.

A source whose settings declare a :class:~ob_analytics.config.Credential that is not set raises :class:~ob_analytics.exceptions.ConfigError before out_dir is created, naming the environment variable to set. Build such settings once and pass them to each source (lambda: VenueSource(settings=settings)): a factory that builds new settings reads the key again for every segment, and fails at the next one if the key file has gone.

CaptureRun dataclass

CaptureRun(
    out_dir: Path,
    manifest: CaptureManifest,
    error: str | None = None,
)

What :func:run_capture returns.

Attributes:

Name Type Description
out_dir Path

The capture directory.

manifest CaptureManifest

The manifest as it was last written.

error str or None

Why the run stopped early, when it could not start at all (the first snapshot failed). None for a run that ended normally or was stopped by a signal -- gaps and failed segments along the way are in the manifest, not here.

CaptureConfig dataclass

CaptureConfig(
    pair: str,
    out_dir: Path,
    minutes: float = 10.0,
    keep_raw: bool = True,
    roll_minutes: float | None = None,
    roll_mb: float | None = None,
)

User-facing capture-run parameters.

Run-level knobs shared by every venue — what symbol, where to write, for how long. Per-venue settings (e.g. the CCXT exchange id) are not here; they are typed :class:~ob_analytics.config.SourceSettings carried by the source itself (CcxtSource(settings=CcxtSettings(...))), which is what replaced the former untyped extras dict.

read_manifest

read_manifest(path: Path) -> CaptureManifest | None

Read the manifest of the segmented capture at path.

path is the capture directory (or its manifest.json). Returns None when there is no manifest: a single capture made by :func:~ob_analytics.live._runner.run_capturer, or a processed output. Raises :class:~ob_analytics.exceptions.ConfigError for a manifest this version cannot read: one that is not a JSON object, lacks a key, or holds a value of the wrong kind, such as a segment name that is not one plain directory name.

CaptureManifest dataclass

CaptureManifest(
    source: str,
    pair: str,
    level: str,
    started: Timestamp,
    declarations: dict[str, Any] = dict(),
    roll_minutes: float | None = None,
    roll_mb: float | None = None,
    ended: Timestamp | None = None,
    restarts: int = 0,
    segments: list[Segment] = list(),
    gaps: list[Gap] = list(),
)

What manifest.json records about a segmented capture.

Read one with :func:read_manifest. source, pair and level identify the capture: a restart into the same directory must match them. declarations is what the source declares about its feed (the same fields a segment's meta.json carries). restarts counts the times the capture was started again into this directory.

dropped property

dropped: int

Messages the sources could not use, across every segment.

book_resyncs property

book_resyncs: int

New opening books the sources took within segments, across all.

raw_frames_skipped property

raw_frames_skipped: int

Frames raw.jsonl skipped across every segment.

unfinished property

unfinished: list[Segment]

Segments a dead capture process left open (closed by the restart).

open_segments property

open_segments: list[Segment]

Segments not yet closed: still being captured, or left by a process that died and has not been restarted. Their files have no closing rows yet, and their row counts are not in the manifest.

write

write(root: Path) -> None

Write manifest.json into root, replacing the old one atomically.

The file is written beside the old one and renamed over it, so a reader -- or a restart after a crash -- never sees half a manifest.

note_streaming

note_streaming(segment: Segment) -> None

Record the gap, if any, before segment's first live event.

The segment before it with coverage either is still streaming (a roll: the two overlap, so there is no gap) or stopped before segment started to stream, and the time between is a gap.

note_uncovered_end

note_uncovered_end(ended: Timestamp) -> None

Record a gap if the capture ended while no segment was streaming.

The last segment that streamed is looked at. If it ran to the end (finished/stopped) nothing is missing. Otherwise -- a failure, or a roll whose next segment never streamed -- the time from its last event to the end of the capture is a gap.

segment_dirs

segment_dirs(root: Path) -> list[Path]

The directories under root of closed segments that hold data, in order.

root is the capture directory, or a process output made from it (which keeps the same segment names). A segment that wrote no book rows -- its snapshot failed -- is left out: there is nothing to read. So is an open segment (see :attr:open_segments): it has no closing rows yet, so the checks would read every order still resting as a fault.

checks

checks() -> tuple[QualityCheck, ...]

The capture-level checks ob-analytics audit adds to each segment's.

Each is a :attr:~ob_analytics.quality.Severity.WARNING: a gap, a dropped message, an error or a resync is data the capture does not have, which the data on either side of it still describes correctly. dropped_messages and capture_errors are the checks :func:loss_checks makes, from every segment.

render

render() -> str

Return a fixed-width, human-readable report block.

Segment dataclass

Segment(
    name: str,
    started: Timestamp,
    ended: Timestamp | None = None,
    stream_started: Timestamp | None = None,
    stream_ended: Timestamp | None = None,
    heartbeat: Timestamp | None = None,
    end_reason: EndReason | None = None,
    error: str | None = None,
    n_book_events: int = 0,
    n_trade_events: int = 0,
    dropped: int = 0,
    diagnostics_error: str | None = None,
    book_resyncs: int = 0,
    raw_frames_skipped: int = 0,
)

One segment of a capture, as the manifest records it.

Attributes:

Name Type Description
name str

The segment's directory name (seg-0001, ...).

started, ended Timestamp or None

When the segment was opened and closed. ended is None while it runs.

stream_started, stream_ended Timestamp or None

The stretch of time the segment covers: from its first live event to the moment it was asked to stop, or its stream stopped by itself. stream_started is None for a segment that never streamed (a snapshot that failed, say), or that was asked to stop before its first live event: it wrote rows, but covered nothing.

heartbeat Timestamp or None

Last time the running capture said the segment was alive. After a crash it is the latest time the segment is known to cover.

end_reason EndReason or None

Why it ended; None while it runs.

error str or None

The error that ended it, if any.

n_book_events, n_trade_events int

Rows written to the book file and to trades.csv.

dropped int

Messages the source received but could not use (its dropped counter in meta.json).

diagnostics_error str or None

Why the source's counters are missing from meta.json, when its diagnostics() raised: dropped is then not known.

book_resyncs int

Times the source lost the venue's stream and started again from a new opening book within the segment (its book_resyncs counter in meta.json). The changes in between were missed.

raw_frames_skipped int

Frames raw.jsonl skipped because JSON cannot hold them (its n_raw_frames_skipped in meta.json).

from_dict classmethod

from_dict(d: dict[str, Any]) -> Segment

Build a segment from its manifest entry.

Raises :class:~ob_analytics.exceptions.ConfigError when name is not one plain directory name: a name such as .. or a/b would make a reader of the capture leave its directory.

Gap dataclass

Gap(
    after: str,
    before: str | None,
    start: Timestamp,
    end: Timestamp,
    cause: str,
)

A stretch of time no segment covers.

Attributes:

Name Type Description
after str

The segment the gap follows.

before str or None

The segment that ends it; None when the capture ended inside it.

start, end Timestamp

When coverage stopped and when it resumed (or the capture ended).

cause str

How the segment before it ended: "disconnect", "restart" (the capture process died), "roll" (a roll whose next segment was slow to stream, or never did), or "stopped" / "finished" (the capture was stopped and later started again into the same directory).

EndReason

Bases: str, Enum

Why a segment ended.

Attributes:

Name Type Description
FINISHED

The capture reached the end of its run time.

STOPPED

A signal (Ctrl-C, SIGTERM) stopped the capture.

ROLLED_TIME, ROLLED_SIZE

The segment reached its time or size limit. The next segment was streaming before this one stopped, so a roll loses nothing.

FAILED

The source raised: most often a lost connection.

ENDED_EARLY

The source stopped streaming before it was asked to, with no error.

UNFINISHED

The capture process died while the segment was open. The restart closed it: see :func:~ob_analytics.live.run_capture.

Built-in live sources

The bitstamp source captures Bitstamp itself, and the kalshi source captures Kalshi from its WebSocket feed (it needs the kalshi extra and an API key). The kraken source captures Kraken order by order (it needs the live extra and an API key). The ccxt and cryptofeed sources reach many venues through those libraries, and need the ccxt and cryptofeed extras. See Capture Kalshi, Capture Kraken order by order, Capture CCXT venues and Capture cryptofeed venues.

BitstampCapturer

BitstampCapturer()

The Bitstamp WebSocket capture engine, driven by :class:~ob_analytics.bitstamp.BitstampSource.

Holds the live connection and resting-order state across snapshot → stream → shutdown_synthetic_events; the public bitstamp live source delegates those three calls (and diagnostics) here. Instances are not reusable across runs -- BitstampSource builds a fresh one per capture.

snapshot async

snapshot(config: CaptureConfig) -> AsyncIterator[EventDict]

Open the WS, subscribe, fetch REST snapshot, yield created events.

While the REST round-trip is in flight, WS frames are buffered so no live events are lost. :meth:stream drains that buffer before entering the long recv loop.

The snapshot is fetched again until it overlaps the stream: some buffered live order event must be at or before its microtimestamp. A snapshot older than everything the stream has delivered leaves a gap, and an order deleted inside it would rest in the capture until the synthetic deleted at shutdown. After :data:SNAPSHOT_MAX_FETCHES tries the last snapshot is used anyway, with a warning, and diagnostics() reports snapshot_overlap: False.

stream async

stream(
    config: CaptureConfig,
) -> AsyncIterator[tuple[str, EventDict, Any]]

Drain the snapshot buffer, then recv frames until the deadline.

A closed connection before the deadline raises :class:~websockets.exceptions.ConnectionClosed: this capture cannot continue past a disconnect (see the module notes).

shutdown_synthetic_events async

shutdown_synthetic_events() -> AsyncIterator[EventDict]

Yield synthetic deleted events for every still-resting order.

diagnostics

diagnostics() -> dict[str, Any]

Return per-capturer counters for inclusion in meta.json.

With the tick_size and lot_size every written price and size sits on, so the replay reads them on that grid.

CcxtSource

CcxtSource(settings: SourceSettings | None = None)

Live-capture any CCXT venue as an L2 depth + trade stream.

Satisfies :class:~ob_analytics.live._base.LiveSource (live only — a CCXT capture's depth.csv replays offline through the generic :class:~ob_analytics.depth_csv.DepthCsvSource). Instances are not reusable across runs -- construct a fresh one per capture.

clocks property

clocks: Clocks

Which clocks this capture's depth rows carry, read from the venue's books.

A CCXT book carries the venue's time where the venue sends one. Where no book does, the rows copy the receive time into exchange_timestamp and the capture has one clock, :attr:~ob_analytics.protocols.Clocks.RECEIVE_ONLY.

preflight

preflight() -> None

Raise now if the venue cannot be built (SupportsPreflight).

Raises the install hint when ccxt is missing, :class:~ob_analytics.exceptions.ConfigError for no venue and :class:~ob_analytics.exceptions.UnknownNameError for an unknown one. A pre-built exchange object in the settings needs no check.

snapshot async

snapshot(config: CaptureConfig) -> AsyncIterator[EventDict]

Seed the book from one REST snapshot; yield absolute-size rows.

A REST snapshot works for both transports and gives a clean starting book to diff subsequent updates against.

stream async

stream(
    config: CaptureConfig,
) -> AsyncIterator[tuple[str, EventDict, Any]]

Interleave book + trade producers through a queue until the deadline.

Book and trade feeds block independently, so each runs in its own task and pushes (kind, event, raw) onto a queue that this generator drains. The run ends at config.minutes (production) or when both producers finish (finite feeds, i.e. tests).

When either producer fails -- a lost connection, most often -- the events it queued first are yielded and then its error is raised, so the run ends instead of carrying on with half its feed. :func:~ob_analytics.live.run_capture then starts a new segment.

shutdown_synthetic_events async

shutdown_synthetic_events() -> AsyncIterator[EventDict]

L2 price levels have no lifecycle to close: emit nothing.

diagnostics

diagnostics() -> dict[str, Any]

Per-run counters for meta.json (SupportsDiagnostics).

CcxtSettings

CcxtSettings(**data: Any)

Bases: SourceSettings

Typed settings for :class:CcxtSource (replaces the former extras dict).

Attributes:

Name Type Description
exchange str or object

The CCXT venue id (e.g. "binance", "kraken"), or a pre-built exchange object for tests / advanced callers. Empty by default so a source can be constructed before the venue is known; the value is required by the time a capture starts (:meth:CcxtSource._configure raises otherwise).

depth_limit int

Order-book depth (levels per side) to request. The capture records whatever CCXT then hands back, uncropped, so this is a floor rather than a cap: Kraken keeps its own subscribed window at exactly this many levels, but Coinbase, Bitstamp and OKX ignore it and always hand back their whole book, and Binance and its family are asked for at least 1,000 levels internally regardless of this value (see :data:_WHOLE_BOOK_VENUES), so their recorded depth is at least that many too.

poll_interval float

Seconds between REST polls, for REST-only venues.

market_data_mirror bool

Read from the venue's market-data-only endpoints instead of its main ones (see :data:MARKET_DATA_MIRRORS). Spot markets only. Binance's main endpoints refuse some locations; whether you may use the mirror from yours is for you to check against the venue's terms.

CryptofeedSource

CryptofeedSource(settings: SourceSettings | None = None)

Live-capture a cryptofeed venue as an L3 order stream or L2 depth stream.

level property writable

level: Level

The capture resolution, discovered from the venue's channels.

Resolved on first access rather than in __init__ because a venue given as a string id has to be looked up in cryptofeed's exchange map before its declared channels can be read -- and that import is deliberately deferred so this module loads without the extra. Once resolved the answer is cached, so a run cannot change resolution midway.

Reading this attribute never raises: it is what isinstance(src, LiveSource) touches, and a protocol check must not explode. When the venue cannot be resolved yet -- no venue chosen, or the extra not installed -- an explicitly requested level stands and anything else answers L2 provisionally, without caching. Starting a capture then resolves the venue for real and raises the install hint.

replay_source property

replay_source: str

The offline source that reads this capture, which follows its level.

An L3 capture writes orders.csv in the Bitstamp format, read by bitstamp; an L2 capture writes depth.csv, read by depth_csv.

feed_type property

feed_type: FeedType

How this capture's book can cross, which follows its level.

At L3, cryptofeed keeps the venue's book of resting orders, applying its opening book and changes, or taking each new snapshot whole. Bids never rest above asks in it, so it is a matched book. At L2 it keeps the venue's total size at each price. Until the venue is known, the level is L2 (see :attr:level), and so is this declaration.

trade_attribution property

trade_attribution: TradeAttribution

Which orders of a trade this capture's order events can name.

cryptofeed's L3 channels carry the book, and a book holds resting orders only: a taker trades on arrival and never appears. So an L3 capture names the maker only, and an L2 capture, with no order identity, names neither. Until the venue is known, the level is L2 (see :attr:level), and so is this declaration.

clocks property

clocks: Clocks

Which clocks this capture's book rows carry, read from the venue's books.

Some cryptofeed venues send no time with their book: Bitfinex and Blockchain.com at L3, Kraken at L2. Their rows copy the receipt time into exchange_timestamp, so the capture has one clock, :attr:~ob_analytics.protocols.Clocks.RECEIVE_ONLY. Independent Reserve and Coinbase send a time on every message but none on the opening book, so they keep both clocks.

note_sequence

note_sequence(book: Any, *, opening: bool = False) -> None

Record one book's venue sequence and count it if it went back.

The number only rises (:attr:sequence_kind), so a skip says nothing about loss and is not counted; cryptofeed finds a lost message itself and reconnects (see :meth:note_resync). A number lower than the one before for the same symbol is one of two things. On an opening book it is the count starting again on a new connection, as on Bitfinex and Blockchain.com: a sequence_restarts, which audit does not count as out of order because the resync already accounts for it. Anywhere else it is a reordered or repeated message, the fault :func:~ob_analytics.quality.detect_sequence_gaps reports as out of order. Counting it live too means meta.json says whether a run is clean without re-reading the capture. Venues that publish no sequence are never scored.

note_resync

note_resync(book: Any) -> bool

Count a new opening book that follows changes to the old one.

Returns whether book is an opening book, for :meth:note_sequence.

cryptofeed reconnects by itself when it finds a lost message, and starts again from a new opening book, so the capture cannot see the reconnect directly. It can see its result. cryptofeed applies each change to the book object it holds and passes that same object on, with the changes as its delta. An opening book carries no changes, and cryptofeed either builds a new object for it or, on Coinbase, refills the one it holds and passes no delta at all. So an opening book after changes to an earlier one is a resync. The full-book diff in :meth:_l3_events (or :meth:_l2_rows) brings the tracked book into line with it, but the changes between the two connections were missed, so each one is counted as book_resyncs in meta.json.

Three cases do not count. Changes that come before the first opening book: Bitstamp's L2 channel streams them for 5 s before its REST book. An update whose changes cryptofeed all skipped, which passes on the same object with an empty delta: Kraken sends deletions of prices not in the book. A venue that sends a new whole book every time and never a change: Bitstamp's L3 channel.

shutdown_synthetic_events async

shutdown_synthetic_events() -> AsyncIterator[EventDict]

Close out everything still resting, so every id has a lifecycle.

A book still held when the capture stopped is written first (see _hold_book). L2 price levels have no lifecycle to close, so an L2 capture yields nothing else here.

diagnostics

diagnostics() -> dict[str, Any]

Per-run counters for meta.json (SupportsDiagnostics).

preflight

preflight() -> None

Raise now if the capture cannot start (SupportsPreflight).

Resolves the venue, which raises the install hint when the extra is missing, :class:~ob_analytics.exceptions.ConfigError for no venue and :class:~ob_analytics.exceptions.UnknownNameError for an unknown one. A supplied feed_handler and exchange class need no import.

snapshot async

snapshot(config: CaptureConfig) -> AsyncIterator[EventDict]

Yield nothing: cryptofeed delivers the opening book as its first callback.

Unlike a REST-seeded source, cryptofeed maintains the book itself and hands over the whole opening state in the first l2_book / l3_book callback. That callback is translated by the same code as every later one -- an L3 opening book has no delta, so it diffs to one created per resting order, and an L2 opening book emits every level at its absolute size. Synthesising a second opening book here would duplicate it.

stream async

stream(
    config: CaptureConfig,
) -> AsyncIterator[tuple[str, EventDict, Any]]

Bridge cryptofeed's callbacks into the runner's async iterator.

cryptofeed pushes data by invoking async callbacks from its own tasks, while the runner pulls from an iterator. A bounded queue joins the two: callbacks await a slot, so a consumer that falls behind applies backpressure to the feed instead of dropping events (an L3 book cannot survive a gap) or growing without limit. For the same reason an L3 message that cannot be mapped ends the stream with :class:UnmappedMessageError, after the messages before it are written; at L2 it is left out and counted in dropped.

The feed handler runs on the caller's event loop (run(start_loop=False)) and never installs signal handlers -- the capture runner owns Ctrl-C. Shutdown goes through stop_async, not close, which would stop the loop out from under the runner.

CryptofeedSettings

CryptofeedSettings(**data: Any)

Bases: SourceSettings

Typed settings for :class:CryptofeedSource.

Attributes:

Name Type Description
exchange str or object

The cryptofeed venue id (e.g. "bitstamp", "binance"), or a pre-built exchange class for tests / advanced callers. Empty by default so a source can be constructed before the venue is known.

level (Level, optional)

Force the capture resolution. None (default) discovers it from the venue's declared channels.

queue_size int

Depth of the buffer between cryptofeed's callbacks and the capturer's iterator. Bounded, so a consumer that falls behind slows the feed rather than growing memory without limit.

feed_handler (object, optional)

A pre-built cryptofeed.FeedHandler for tests / advanced callers (multiple feeds, custom config). None builds one per run.

KalshiSource

KalshiSource(settings: KalshiSettings | None = None)

Live-capture one Kalshi market from its WebSocket feed, at L2.

Satisfies :class:~ob_analytics.live.LiveSource. Its depth.csv replays offline through :class:~ob_analytics.depth_csv.DepthCsvSource. Instances are not reusable across runs: construct a fresh one for each capture, as :func:~ob_analytics.live.run_capture does for each segment.

preflight

preflight() -> None

Raise now if the capture cannot run (SupportsPreflight).

Raises :class:ImportError with the install hint when websockets or cryptography is missing, and :class:~ob_analytics.exceptions.ConfigError when the private key given is not one. A key that is not set is left to the capture's own check, which names the variable to set.

snapshot async

snapshot(config: CaptureConfig) -> AsyncIterator[EventDict]

Subscribe and yield the opening book as absolute-size depth rows.

Reads the market's tick size from Kalshi's public market data first, so an unknown ticker stops the capture before it connects.

stream async

stream(
    config: CaptureConfig,
) -> AsyncIterator[tuple[str, EventDict, Any]]

Read frames until the deadline; yield depth rows and trades.

A closed connection before the deadline raises :class:~websockets.exceptions.ConnectionClosed, so :func:~ob_analytics.live.run_capture starts a new segment.

parse

parse(msg: dict[str, Any]) -> tuple[str, EventDict, Any]

Turn one frame after the opening book into (kind, event, raw).

kind is "depth" for a book change, "trade" for a trade, and "raw" (with an empty event) for anything else, which is only archived.

shutdown_synthetic_events async

shutdown_synthetic_events() -> AsyncIterator[EventDict]

L2 price levels have no lifecycle to close: emit nothing.

diagnostics

diagnostics() -> dict[str, Any]

Per-run counters for meta.json (SupportsDiagnostics).

KalshiSettings

KalshiSettings(**data: Any)

Bases: SourceSettings

The API key a Kalshi capture signs its connection with.

Both fields are read from the environment when not given: the Key ID from KALSHI_API_KEY_ID, and the private key from the file KALSHI_PRIVATE_KEY_PATH names. Kalshi issues both on the profile page of a Kalshi account; the private key is shown once, when the key is made. An Ed25519 or an RSA key works.

KrakenSource

KrakenSource(settings: KrakenSettings | None = None)

Live-capture one Kraken pair, order by order, from the level3 channel.

Satisfies :class:~ob_analytics.live.LiveSource. Its orders.csv and trades.csv replay offline through the bitstamp file format. Instances are not reusable across runs: construct a fresh one for each capture, as :func:~ob_analytics.live.run_capture does for each segment.

preflight

preflight() -> None

Raise now if the capture cannot run (SupportsPreflight).

Raises :class:ImportError with the install hint when websockets is missing, and :class:~ob_analytics.exceptions.ConfigError when the private key given is not base64. A key that is not set is left to the capture's own check, which names the variable to set.

snapshot async

snapshot(config: CaptureConfig) -> AsyncIterator[EventDict]

Get a token, subscribe, and yield the opening book as created rows.

stream async

stream(
    config: CaptureConfig,
) -> AsyncIterator[tuple[str, EventDict, Any]]

Read both connections until the deadline; yield orders and trades.

A closed connection before the deadline raises :class:ConnectionError, so :func:~ob_analytics.live.run_capture starts a new segment.

parse

parse(
    msg: dict[str, Any], received: Timestamp | None = None
) -> list[tuple[str, EventDict, Any]]

Turn one frame after the opening book into (kind, event, raw) items.

msg is the frame parsed with parse_float=Decimal, and received the time it arrived (None means now). The first item carries it as raw, for raw.jsonl, and the rest None, so the frame is archived once. kind is "order" for a book event, "trade" for a trade, and "raw" (with an empty event) for a frame with neither.

shutdown_synthetic_events async

shutdown_synthetic_events() -> AsyncIterator[EventDict]

Yield a deleted event for every order still open, parked ones too.

A delete held for an amend that never came is written first, at its own time.

diagnostics

diagnostics() -> dict[str, Any]

Per-run counters for meta.json (SupportsDiagnostics).

KrakenSettings

KrakenSettings(**data: Any)

Bases: SourceSettings

The API key and book depth of a Kraken capture.

Both key fields are read from the environment when not given: the key from KRAKEN_API_KEY, and its private key (the "secret") from KRAKEN_API_SECRET. Kraken shows both when the key is made, in the API settings of a Kraken account. The key needs the permission "WebSocket interface - On". Kraken also asks for at least one permission: one that only reads, such as "Query Open Orders & Trades", is enough. The key needs no permission to trade or to move funds.

Writing a live source

What a live source yields and what the capture runner reads from it. See The live capability.

EventDict module-attribute

EventDict = dict[str, Any]

One event a live source yields: a dict of column name to value.

The required keys are:

  • an order event (L3): id, timestamp, exchange_timestamp, price, volume, action, direction.
  • a depth event (L2): timestamp, exchange_timestamp, direction (bid or ask), price, volume. volume is the new size at that price; 0 removes the level.
  • a trade event: trade_id, timestamp, exchange_timestamp, price, volume, buy_order_id, sell_order_id, direction (the taker's side, buy or sell).

The times are tz-aware UTC :class:pandas.Timestamp values, kept to the precision the venue sent. An event may also carry venue and symbol: the capture records the first ones it sees in meta.json, and a replay puts them on every row.

CaptureSink

Bases: Protocol

Write target for a capture run.

The default implementation, :class:~ob_analytics.capture_files.FileCaptureSink, writes the capture folder :mod:ob_analytics.capture_files describes: orders.csv for an L3 source or depth.csv for an L2 one (see :attr:~ob_analytics.protocols.Source.level), trades.csv, raw.jsonl and meta.json.

CaptureResult dataclass

CaptureResult(
    out_dir: Path,
    n_order_events: int,
    n_trade_events: int,
    n_raw_frames: int,
    started: Timestamp,
    ended: Timestamp,
    extras: dict[str, Any] = dict(),
    n_depth_events: int = 0,
    n_snapshot_unconfirmed: int | None = None,
    capture_error: str | None = None,
    capture_error_phase: str | None = None,
    stream_started: Timestamp | None = None,
    stream_ended: Timestamp | None = None,
)

Summary returned to the caller once the run finishes.

SupportsDiagnostics

Bases: Protocol

Optional source capability: per-run counters for meta.json.

Kept deliberately separate from :class:LiveSource so that writing a live source never forces a diagnostics() method onto it. A source that wants to expose counters (dropped frames, reconnects, synthetic-event tallies, ...) just defines this method; the runner detects it structurally (isinstance(source, SupportsDiagnostics)) and merges the returned mapping into :attr:CaptureResult.extras (and thus meta.json).

Count the messages the source received but could not use, and left out, under dropped: the capture manifest totals that key, and ob-analytics audit fails its dropped_messages check when it is above zero. An error that ends the stream is not counted there; the runner records it as :attr:CaptureResult.capture_error.

diagnostics

diagnostics() -> dict[str, Any]

Return a JSON-serialisable mapping of per-run counters.

SupportsPreflight

Bases: Protocol

Optional source capability: check the source can run before it starts.

A source whose venue library is an optional extra imports it lazily, so a missing extra would otherwise surface only once the stream starts, after the output files exist. The runner calls :meth:preflight before it creates any output, so such a run stops with the install hint instead.

preflight

preflight() -> None

Raise :class:ImportError (with the install hint) if the source cannot run.

May also raise :class:~ob_analytics.exceptions.ConfigError for settings that cannot work (no venue chosen), or :class:~ob_analytics.exceptions.UnknownNameError for an unknown venue id.