Skip to content

Architecture

Pipeline stages

ob-analytics turns order event streams and authoritative trade records into structured analytics. The four middle rows are pipeline.STAGES, in order; an L2 run skips the two marked (L3).

Stage What happens
Load & normalize A source's loader reads its files into one event table (L3) or one depth table (L2). Built-in offline sources: Bitstamp CSV, LOBSTER message and orderbook files, Databento DBN market-by-order, and the L2 depth CSV. The ccxt, cryptofeed, kalshi and kraken captures write files that these sources read
Build trades Each source supplies its trades: Bitstamp and the captures read the companion trades.csv, LOBSTER takes the execution rows (types 4/5) from the message file, and Databento pairs each fill with the book event that took the size off
Classify orders (L3) set_order_types: label each order as market, resting-limit, cancelled-limit, market-limit, pre-existing (first seen mid-stream), or unknown
Price-level depth price_level_volume: track the volume at each price level. At L2 the loader reads this table directly. LOBSTER can use the official orderbook file for ground-truth depth
Depth metrics depth_metrics: best bid/ask, spread, and liquidity in configurable BPS bins; trades the venue left unlabelled are signed here
Aggressiveness (L3) order_aggressiveness: how far each new limit order sits from the best price on its own side when it arrives, in BPS
Analytics (after the run) Registered metrics (VPIN, Kyle's lambda, trade imbalance, transaction costs, …), bars, the feature table, hidden liquidity, order lifecycles and queue positions (L3), and the data-quality audit, all computed from the run's tables. The result keeps the lifecycles, queue, book snapshots, bars and feature table it builds (result.lifecycles(), result.queue(), …)
Visualize / export Depth heatmaps, event maps, trade charts, flow-toxicity plots, HTML galleries. Matplotlib (default) or Plotly backend; Bokeh draws four plots: trade_tape, depth_heatmap, book_snapshot and depth_chart. Parquet, the source formats, hftbacktest and Nautilus Trader output

Design decisions

  • DataFrames end to end. Pandas for speed; schemas.TABLES holds one contract per table the package returns, and the validate_* functions in schemas.py check frames against them.
  • The rebuild engine is separate, and holds no pandas. engine/ takes order events as numpy columns and returns book snapshots, order lifecycles, and queue positions -- nothing else -- and keeps the L2 book (PriceLevelBook) that the depth summary is built on. It knows nothing about analytics, plots, sources, or files, and its results carry a row index back into the caller's event table instead of copying columns out, so adding a column to the schema never widens the interface. _engine_frames.py is the one place that converts between pandas frames and the engine's arrays. Modules outside engine/ call the engine only through it and through engine/__init__.py; depth.py hands PriceLevelBook the depth table's columns as arrays. This is what lets the inside be replaced with a faster implementation, or fed one event at a time, without anything above it moving.
  • Two API levels — Pipeline for one-line runs; individual classes (BitstampLoader, BitstampTradeReader, etc.) for step-by-step control.
  • Pluggable everything — any object with the right method signature works; no inheritance required (structural typing via Protocol).
  • One Source shape, file or live. Every data source states its level (L2/L3) and feed_type, carries typed settings, and implements one or both capabilities — OfflineSource (replay stored files) and LiveSource (capture a venue). Both register in the one SOURCES registry (register_source), and third-party sources load through the ob_analytics.sources entry-point group. The built-in sources stay in this package, each behind an optional extra (live, ccxt, cryptofeed, databento), so a core install pulls in no venue client. A source for another venue can ship as its own package and register through that group, with no change here.
  • Optional methods are separate protocols. An offline source must have only create_loader and create_trade_reader. Writing its own format (SupportsWriter), supplying its own depth (SupportsComputeDepth) and naming the RunContext fields it needs (SupportsRequiredContext) are each a protocol of their own, found with isinstance. A live source works the same way with SupportsDiagnostics and SupportsPreflight.
  • Per-run parameters live on RunContext, not Source. Construction-time parameters (typed settings, fixed venue config) belong on the source; per-session parameters (trading date, time zone, symbol, venue) live on RunContext. Give one to Pipeline(source=..., ctx=...) as the default for every run, or to Pipeline.run(path, ctx=...) for that run alone. The pipeline builds each run's loader and trade reader from that run's config and context, and a source keeps nothing from a run, so one source serves many runs, and many pipelines, at once.
  • A loader knows its own feed format. How a file encodes prices and timestamps (LOBSTER's ten-thousandths of a dollar, Databento's fixed-point nanodollars, Bitstamp's millisecond epochs) is a constant of its loader, or a field of the source's typed settings where the format leaves it open (DepthCsvSettings). PipelineConfig holds the instrument and pipeline settings only. A source states the grid its data is usually on as grid (InstrumentGrid), and the run's config starts from it.
  • Every plot is declared once. visualization/_concepts.py lists each plot concept, the levels it has and the backends that draw it. The backend modules only draw, and the gallery, plot_result and plot all read the same table.

Scale envelope

ob-analytics keeps the full event, depth, and trade tables in memory (pandas), so the working set scales with the event count. Peak RSS grows roughly linearly, by a little under 1 GiB per 1M events, with the depth stages (price_level_volume → summarize_depth) holding most of the memory:

events peak RSS depth stages
314 k ~0.53 GiB ~0.5 s
628 k ~0.78 GiB ~1.0 s
942 k ~1.03 GiB ~1.5 s
1.26 M ~1.26 GiB ~2.1 s

(Measured on 2026-11-23 with scripts/bench_scale.py --envelope on one Linux x86_64 desktop: the bundled ~314k-event sample tiled to each size, each size run in its own process, peak RSS via getrusage. The slope is about 0.8 GiB per 1M events, and a linear extrapolation gives about 4.2 GiB at 5M events. Slightly conservative — tiling adds some transient overhead. About 110 MiB of each figure is numba and the compiled loops, a fixed cost that does not grow with the event count. Compiling the queue engine as well did not raise the peak. That figure is with numba's disk cache already written. A process that compiles the loops itself, as the first one in a new environment does, peaks about 60 MiB higher. The seconds depend on the machine; the memory does much less.)

Where the time goes

Per stage, measured on one desktop on 2026-11-23, before and after in the same session, with scripts/bench_scale.py (the fastest of three passes) for the bundled 314k-event sample, and with one pass of bench_scale.measure_run for a full day of Databento AAPL MBO data (XNAS.ITCH, 2026-11-10, 3.7M events). "Before" has the depth replay compiled and the queue engine in Python; "after" has both loops compiled with numba (ADR 0003). The shape holds on other machines; the seconds do not.

stage sample before sample after AAPL day before AAPL day after
load 0.45 0.44 14.76 15.02
set_order_types 0.14 0.14 2.78 2.85
price_level_volume 0.16 0.15 2.70 2.71
summarize_depth 0.38 0.36 6.85 6.60
order_aggressiveness 0.11 0.10 1.29 1.30
queue_positions 0.70 0.12 7.02 1.14
total 1.94 1.31 35.40 29.62

Compiling the queue engine made queue_positions about 6 times faster on the sample and on the AAPL day, with the same output, bit for bit. It is now 9% of a run on the sample and 4% on the AAPL day. Before either loop was compiled, the depth replay took 7.15 s of the sample and 61.9 s of the AAPL day, and a whole run took 8.6 s and 90 s. The depth replay is now the largest stateful stage, at 27% of the sample and 22% of the AAPL day. On the AAPL day, reading the DBN file is the largest stage, at 51%.

Reading and the frame stages (load, set_order_types, price_level_volume and order_aggressiveness) are now 74% of the AAPL day. ADR 0002 names 30% of a run at 5M events or more as one of its two conditions for looking at a second dataframe library again. This day has 3.7M events, so it does not settle that test.

bench-baseline.json, which CI compares against on every pull request, was recorded on the ubuntu-24.04 GitHub runner. Read it for CI's own numbers. A fresh runner has no numba cache, so every CI run compiles the loops, and its peak memory is 155 to 270 MiB above a run without numba. Compiling both loops in one process costs about 30 MiB more at its peak than compiling one.

Comfortable ceiling ≈ 5M events (about 4–5 GiB) on a typical 16 GB machine — i.e. session-scale data, a few hours of a single liquid instrument. For larger inputs (a full NASDAQ MBO day is 10–100M events, well past this), use Pipeline.run_windows: it cuts one input into time windows, runs the depth stages on one window at a time, and writes each window's rows to Parquet as it finishes, so peak memory is set by the largest window. With one-hour windows, ten days of Databento AAPL MBO data (38.7M records) peaked at 1.43 GiB, and one day at 1.25 GiB; a single run of one day peaks at about 3.8 GiB. Files that are already split by time window can each go through Pipeline.run. Scale and chunking gives the measurements and the limits of a windowed run.

Reading a saved run is not bound by its size. ob_analytics.scan reads one table of a saved folder one batch at a time, so its memory does not grow with the file; only the result it returns has to fit. On the machine above, aggregate_by_time reduced a 50M-row depth_summary (17.2 GiB as a pandas frame, more than the machine's 15 GiB) to one-minute buckets in 11 seconds with a peak of about 1.1 GiB, about 130 MiB more than on 5M rows, and summarize_depth_file rebuilt the summary from a 5M-row depth table in 0.8 GiB, the same as from 314k rows. (Measured on 2026-11-23 with scripts/bench_scale.py --out-of-core; see Reading a saved run in parts.)


Known limitations

These are known and not yet fixed. Each one is a decision still to make, not a wrong number.

  • The depth heatmap hides lasting levels on a dense book. On a book with thousands of one-cent price levels (an L2 capture can have about 17,000), many levels share one pixel row, and the linear colour scale draws most of them in the same dark colour. Zoom in to a narrow price range (price_from, price_to) and set col_bias to a value in (0, 1), or to 0 or less for a log scale, to see them.
  • The feature table does not carry the metric diagnostics. vpin and kyle_lambda each return a result with significant and diagnostics beside the table. The vpin and kyle_lambda columns of features() do not carry these checks. To check a thin tape, call the two functions directly.
  • Colour scales do not follow the theme. PlotTheme and its Palette set the side, aggressor, outcome and neutral colours on every backend. The continuous colour scales are fixed: Viridis on the depth heatmap, and Blues on the cancellations and liquidity-at-touch plots. The Matplotlib heatmap's gray background is fixed too.
  • Databento: a lost queue priority is not modelled. Databento's modify (M) can move an order to another price or make it bigger. At the venue both lose queue priority. The shared schema has no event for that, so the loader writes a changed event, and the queue rebuild keeps the order's old place. See Orders that move or grow.

Class diagram

The package combines protocol-based components with sources that bundle venue-specific defaults and capabilities.

classDiagram
    class Pipeline {
        +config: PipelineConfig
        +run(path, ctx) PipelineResult
        +run_windows(path, boundaries, output, carry, ctx) Path
        +from_source(name, **kwargs)$ Pipeline
    }

    class PipelineConfig {
        +tick_size: float
        +price_decimals: int
        +lot_size: float
        +volume_decimals: int
        +track_sequence: bool
        +depth_bps: int
        +depth_bins: int
    }

    class Source {
        <<Protocol>>
        +name: str
        +level: Level
        +feed_type: FeedType
        +settings: SourceSettings
        +grid: InstrumentGrid
    }
    class OfflineSource {
        <<Protocol>>
        +create_loader(config, ctx) EventLoader | DepthLoader
        +create_trade_reader(config, ctx, loader) TradeReader
    }
    class SupportsWriter {
        <<Protocol>>
        +create_writer(config, ctx) DataWriter
    }
    class SupportsComputeDepth {
        <<Protocol>>
        +compute_depth(events, config, path, ctx, loader) tuple | None
    }
    class SupportsRequiredContext {
        <<Protocol>>
        +required_context() list
    }
    class LiveSource {
        <<Protocol>>
        +snapshot(config) AsyncIterator
        +stream(config) AsyncIterator
        +shutdown_synthetic_events() AsyncIterator
    }

    class RunContext {
        +trading_date: object | None
        +session_tz: str | None
        +symbol: str | None
        +venue: str | None
    }

    class BitstampSource
    class LobsterSource
    class DatabentoSource
    class DepthCsvSource
    class CcxtSource
    class CryptofeedSource

    class EventLoader {
        <<Protocol>>
        +load(path) DataFrame
    }
    class DepthLoader {
        <<Protocol>>
        +load(path) DataFrame
    }
    class TradeReader {
        <<Protocol>>
        +load(events, path) DataFrame
    }
    class DataWriter {
        <<Protocol>>
        +target: WriteTarget
        +write(data, dest, **kwargs)
    }

    class PipelineResult {
        +events: DataFrame
        +trades: DataFrame
        +depth: DataFrame
        +depth_summary: DataFrame
        +config: PipelineConfig
        +level: Level
        +declarations: FeedDeclarations
        +metric(name, **settings) DataFrame
        +plot(concept, level, **kwargs)
        +audit() DataQualitySummary
    }

    Pipeline --> PipelineConfig
    Pipeline ..> EventLoader : one per run (L3)
    Pipeline ..> DepthLoader : one per run (L2)
    Pipeline ..> TradeReader : one per run
    Pipeline --> PipelineResult
    Pipeline ..> OfflineSource : source=
    Pipeline ..> RunContext : per-run params
    SupportsWriter ..> DataWriter : create_writer
    Source <|-- OfflineSource
    Source <|-- LiveSource
    OfflineSource <|.. BitstampSource
    LiveSource <|.. BitstampSource
    OfflineSource <|.. LobsterSource
    OfflineSource <|.. DatabentoSource
    OfflineSource <|.. DepthCsvSource
    LiveSource <|.. CcxtSource
    LiveSource <|.. CryptofeedSource

BitstampSource, LobsterSource, DatabentoSource and DepthCsvSource also implement SupportsWriter; LobsterSource implements SupportsComputeDepth and SupportsRequiredContext too.


Data formats

Source Level Entry point Trades
Bitstamp (CSV replay + live capture) L3 Pipeline() (default) · capture bitstamp Companion trades.csv next to orders.csv (e.g. from capture bitstamp)
LOBSTER L3 Pipeline(source=LobsterSource(), ctx=RunContext(trading_date=...)) Embedded execution rows (types 4/5) in the message file
Databento (DBN market-by-order) L3 Pipeline(source=DatabentoSource()) · process --source databento Fill records, paired with the book event that took the size off
L2 depth CSV L2 Pipeline.from_source("depth_csv").run(...) Optional companion trades.csv (signed via trade-sign classification)
CCXT (live L2 capture) L2 capture ccxt --venue <venue> Public trade tape (taker side)
cryptofeed (live capture) L2 or L3, discovered from the venue capture cryptofeed --venue <venue> Public trade tape (taker side)

The bundled sample under ob_analytics/_sample_data/ is a modern BTC/USD capture (orders.csv + trades.csv).

L2 vs L3: the resolution axis

A source declares a level (Level.L2 / Level.L3), orthogonal to its FeedType crossing invariant:

  • L3 (market-by-order) — the per-order model above. Events carry order IDs, so set_order_types, order_aggressiveness, and queue reconstruction run.
  • L2 (market-by-price) — price-level feeds (Binance, Kalshi, Polymarket, most CCXT sources) publish [price, quantity] levels and diffs with no order IDs. The loader (a DepthLoader) yields the depth frame directly and the pipeline skips the per-order stages: PipelineResult.events comes back empty (schema-valid) and PipelineResult.level is Level.L2. DepthSummaryEngine already consumes an absolute price-level book, so depth / spread / trade analytics run unchanged. See the Process L2 feeds how-to.

Module map

Every file in the package is listed here; tests/test_module_map.py fails when one is missing or when an entry names a file that is gone.

ob_analytics/
├── __init__.py           # Public API surface + source registration + sample_csv_path()
├── __main__.py           # `python -m ob_analytics` runs the CLI
├── py.typed              # marks the package as typed (PEP 561)
├── _sample_data/         # Bundled Bitstamp sample
│   ├── README.md         # what the capture is, its known faults, and its source and terms
│   ├── meta.json         # the capture record
│   ├── orders.csv.gz     # order events (gzip)
│   └── trades.csv        # trades
├── pipeline.py           # Pipeline (run, run_windows), PipelineResult
├── _windows.py           # windowed runs: window bounds, the carry of resting orders, ParquetAppender
├── sources.py            # SOURCES registry: register_source, list_sources, get_source, entry-point discovery
├── _registry.py          # Registry and load_plugins: the one lookup and plug-in loader every registry uses
├── config.py             # PipelineConfig, InstrumentGrid, SourceSettings, Credential (frozen Pydantic models)
├── protocols.py          # EventLoader, DepthLoader, TradeReader, DataWriter, Source, OfflineSource, RunContext, WindowedLoader
├── schemas.py            # TABLES (one contract per table: columns, dtypes, price/size tags), unit metadata, validators
├── display.py            # display_result: ticks and lots to display units, read from the contracts
├── exceptions.py         # ObAnalyticsError hierarchy
├── _secrets.py           # removes loaded credentials from files and logs
├── _quality_checks.py    # QualityCheck, Severity: the record of one data-quality check (quality re-exports them)
├── cli.py                # CLI entry point (process, audit, gallery, bitstamp-demo, lobster-demo, capture, sources)
├── _demos.py             # the runs behind bitstamp-demo and lobster-demo
│
├── bitstamp.py           # BitstampLoader, BitstampTradeReader, BitstampWriter, BitstampSource (offline + live)
├── lobster.py            # LobsterLoader, LobsterTradeReader, LobsterWriter, LobsterSource
├── databento.py          # DatabentoLoader, DatabentoTradeReader, DatabentoWriter, DatabentoSource (DBN MBO)
├── depth_csv.py           # DepthCsvLoader, DepthCsvTradeReader, DepthCsvWriter, DepthCsvSource (price-level)
├── capture_files.py      # a capture folder's file names and columns, FileCaptureSink, repair_files
├── capture_record.py     # a capture's meta.json: read_record, write_record, CaptureRecord
├── synth.py              # synthetic L3 sessions: generate_session, SynthLoader, SynthTradeReader
├── datasets.py           # tiny hand-checkable toy datasets for teaching and tests
├── engine/               # Order-book engine: events in, book snapshots + lifecycles out
│   ├── __init__.py       # the interface: order_book, order_lifecycles, queue_positions, queue_age_grid, PriceLevelBook, crossed_prefix_counts
│   ├── _events.py        # OrderEvents -- the shared schema as numpy columns
│   ├── _book.py          # point-in-time rebuild + crossed-book eviction
│   ├── _lifecycles.py    # placement -> outcome, one row per order
│   ├── _queue.py         # FIFO queue position and touch composition
│   ├── _queue_replay.py  # Compiled (numba) loop of the FIFO queue reconstruction
│   ├── _price_levels.py  # PriceLevelBook: the L2 book, one depth row at a time
│   ├── _depth_replay.py  # Compiled (numba) loops of the depth replay, and the crossed-touch rule (crossed_prefix_counts)
│   └── _compiled.py      # the one numba helper both replays compile through
├── _engine_frames.py     # pandas <-> engine arrays (the only place the two are converted)
├── book.py               # frame faces of the engine: order_book, order_lifecycles
├── analytics.py          # order_aggressiveness, trade_impacts, maker_resting_times, cancelled_orders, set_order_types
├── quality.py            # data_quality_summary, detect_sequence_gaps, detect_stale_orders
├── queue.py              # frame faces for the engine's queue reconstruction
├── depth.py              # DepthSummaryEngine, price_level_volume, summarize_depth, get_spread, micro_price
├── trade_sign.py         # trade-sign classification: tick rule, Lee-Ready, bulk volume classification
├── hidden_liquidity.py   # detect_icebergs, hidden_trades
├── data.py               # save_data, load_data, load_result, writer registry
├── scan.py               # read and aggregate a saved run in parts: scan_table, read_table, aggregate_by_time, summarize_depth_file
├── interop.py            # export to hftbacktest and Nautilus Trader
├── flow_toxicity.py      # vpin, kyle_lambda, trade_imbalance, VpinResult, KyleLambdaResult
├── metrics.py            # METRICS registry: register_metric and the built-in metrics
├── bars.py               # bars, BAR_RULES registry, register_bar_rule
├── cost.py               # transaction_costs, cost_summary, amihud, roll_spread, CostSummary
├── features.py           # features, FEATURES registry, register_feature
├── _utils.py             # Validation, numerics, timestamp conversion helpers
│
├── live/                 # Optional live-capture machinery ([live] / [kalshi] / [ccxt] / [cryptofeed] extras)
│   ├── __init__.py       # live-source registration (ccxt, cryptofeed, kalshi, kraken) + re-exports
│   ├── _base.py          # LiveSource protocol, CaptureConfig, CaptureResult, CaptureSink
│   ├── _runner.py        # run_capturer: the asyncio driver for one segment
│   ├── _supervisor.py    # run_capture: a capture of many segments, with reconnects, rolls and restarts
│   ├── _manifest.py      # manifest.json: the segments of a capture and the gaps between them
│   ├── bitstamp.py       # Bitstamp WebSocket engine (driven by BitstampSource)
│   ├── ccxt_source.py    # CcxtSource, CcxtSettings (any CCXT venue, L2)
│   ├── cryptofeed_source.py  # CryptofeedSource, CryptofeedSettings (L2 or native L3)
│   ├── kalshi.py         # KalshiSource, KalshiSettings (Kalshi WebSocket, L2, needs an API key)
│   ├── kraken.py         # KrakenSource, KrakenSettings (Kraken level3 WebSocket, L3, needs an API key)
│   └── _cryptofeed_venues.py # corrected cryptofeed venue feeds (Independent Reserve)
│
└── visualization/        # Plotting subsystem
    ├── __init__.py       # plot() dispatcher, PlotTheme, save_figure, public re-exports
    ├── _concepts.py      # every plot concept, declared once: its levels and the backends that draw it
    ├── _renderers.py     # RENDERERS registry and loading of backend modules
    ├── gallery.py        # plot_result, available_concepts, HTML gallery generation
    ├── prepare.py        # public data-preparation functions
    ├── _data.py          # Shared data prep for plot backends
    ├── _theme.py         # PlotTheme
    ├── _palette.py       # Palette: the colours every backend draws with
    ├── _matplotlib.py    # Matplotlib renderers
    ├── _plotly.py        # Plotly renderers
    └── _bokeh.py         # Bokeh renderers (four plots: trade_tape, depth_heatmap, book_snapshot, depth_chart)

Live capture is optional (install with pip install "ob-analytics[live]", [ccxt], or [cryptofeed]), is supported on Linux and macOS only, and writes into the same CSV schema the pipeline reads. Give your Source the live capability -- the three LiveSource async-iterator methods (snapshot, stream, shutdown_synthetic_events) -- and register_source it; a source can add the offline factories too and do both. The runner (run_capturer) handles persistence, raw-frame archival, signal handling, and meta.json finalisation so source authors only write the per-venue parser. run_capture runs it once per segment of a long capture: a disconnect, a time or size roll, or a restart closes the current segment and starts the next from a fresh snapshot, and manifest.json records the segments and the gaps between them.