Changelog¶
All notable changes to ob-analytics are documented in this file.
The format is based on Keep a Changelog.
[Unreleased]¶
Moving from 0.1¶
The package keeps no aliases for old names before 1.0. Each table below maps a name that 0.1.0 shipped to its name now. A name that 0.1.0 did not have is not listed here: the sections after this one describe it.
Sources and the pipeline
| 0.1 | Now |
|---|---|
Format |
OfflineSource |
BitstampFormat, LobsterFormat |
BitstampSource, LobsterSource |
register_format(name, fmt), list_formats() |
register_source(name, source_cls), list_sources() |
Pipeline(format=...) |
Pipeline(source=...) |
Pipeline.from_format(name) |
Pipeline.from_source(name) |
Pipeline(trade_source=...) |
Pipeline(trade_reader=...) |
TradeSource |
TradeReader |
Pipeline.run(source=...), EventLoader.load(source), TradeSource.load(events, source) |
the argument is path; positional calls are unchanged |
PipelineConfig(timestamp_unit=..., price_divisor=...) |
removed; each loader knows its feed's units. PipelineConfig now refuses a field it does not know |
PipelineConfig.price_multiplier, PipelineConfig.bps_labels |
removed |
LobsterWriter(price_divisor=...) |
removed |
ob_analytics.live.LiveCapturer |
ob_analytics.live.LiveSource |
ob_analytics.live.register_capturer, get_capturer, list_capturers |
register_source, get_source, list_sources |
Measures
| 0.1 | Now |
|---|---|
compute_vpin(trades, bucket_volume, n_buckets), a DataFrame |
vpin(trades, *, bucket_volume, n_buckets), a VpinResult; the table is fit.table |
compute_kyle_lambda(trades, window) |
kyle_lambda(trades, *, window) |
KyleLambdaResult.regression_df |
KyleLambdaResult.table |
order_flow_imbalance(trades, window), columns net_volume and ofi |
trade_imbalance(trades, *, window), columns signed_volume and trade_imbalance |
depth_metrics(depth, bps, bins) |
summarize_depth(depth, *, depth_bps, depth_bins) |
DepthMetricsEngine |
DepthSummaryEngine |
get_spread(depth_summary) |
get_spread(quotes) |
filter_depth(d, from_timestamp, to_timestamp) |
filter_depth(depth, *, start_time, end_time) |
order_aggressiveness(events, depth_summary) |
order_aggressiveness(events, quotes) |
analytics.order_book(events, tp, max_levels, bps_range, min_bid, max_ask), a dict |
book.order_book(events, *, at, max_levels, bps_range, uncross), a BookSnapshot: book["bids"] is book.bids, and the same for asks and timestamp. min_bid and max_ask are removed |
analytics.order_lifecycles |
book.order_lifecycles |
ages, times, max_rank = queue_age_grid(events) |
grid = queue_age_grid(events), one row per queue rank and one column per sample time: ages is grid.to_numpy(), times is grid.columns, max_rank is len(grid) |
order_book, order_lifecycles, vpin, kyle_lambda and trade_imbalance
are also at the package root.
Saving and loading
| 0.1 | Now |
|---|---|
save_data(lob_data, path) |
save_data(data, path) |
save_data(data, "run.pkl", fmt="pickle"), load_data("run.pkl") |
removed, since a pickle runs code when it is loaded. Save a Parquet folder: save_data(data, "run"). To move an old pickle you wrote yourself, read it with pandas.read_pickle and save it with save_data |
save_data(data, "run.parquet") made a folder of that name |
refused: the Parquet format takes a folder name with no file extension |
save_data(data, "out/orders.csv", fmt="bitstamp") |
save_data(data, "out", fmt="bitstamp"), which writes out/orders.csv and out/trades.csv |
load_data(file) raised ValueError |
raises ConfigError, which is also a ValueError |
the order type flashed-limit |
cancelled-limit. load_data and load_result convert it in a saved run, with a warning |
Plots and the gallery
| 0.1 | Now |
|---|---|
plot("order_flow_imbalance", ...) |
plot("trade_imbalance", ...) |
plot("ofi_horizon", ...) |
plot("trade_imbalance_by_window", ...) |
plot("volume_percentiles", ...) |
plot("depth_bands", ...) |
plot("cancellations", "L2", ...) |
removed: a price level cannot tell a cancel from a fill, so cancellations is an L3 plot only |
plot("hidden_executions", "L2", ...) |
plot("hidden_executions", "L3", ...) |
plot("time_series", "L2", ...) |
plot("time_series", ...): it has no level |
plot_result(result, concept) for a concept drawn at L2 and L3 drew the L2 plot |
raises ConfigError: pass level="L2" or level="L3" |
plot_result(..., level=None) picked the level |
leave level out. None now means a plot with no level, such as a metric |
volume_scale= of plot_result, PipelineResult.plot, build_gallery_model and generate_gallery |
removed: sizes are drawn in the instrument's units |
infer_volume_scale |
removed |
vpin_panel, ofi_panel |
removed: every gallery has the VPIN and trade imbalance cards |
ofi_horizon_panel |
trade_imbalance_by_window_card |
kyle_panel |
kyle_lambda_card |
trading_halts_panel |
trading_halts_card |
prepare functions
Each prepare function now has the name of its plot concept and takes
level= by the rule of plot(). Every volume_scale argument is removed, and
the arguments after it move up one place. The payloads no longer hold a
volume_scale key.
| 0.1 | Now |
|---|---|
prepare.trades(...) |
prepare.trade_tape(..., level="L2") |
prepare.trade_tape_l3(...) |
prepare.trade_tape(..., level="L3") |
prepare.price_levels(...) |
prepare.depth_heatmap(...) |
prepare.event_map(events, ...) |
prepare.order_activity(depth, ..., level="L2"), which reads the depth table |
prepare.order_activity_l3(...) |
prepare.order_activity(..., level="L3") |
prepare.volume_map(...) |
removed, with the L2 cancellations plot |
prepare.cancellations_l3(...) |
prepare.cancellations(...) |
prepare.liquidity_at_touch(...) |
prepare.liquidity_at_touch(..., level="L2") |
prepare.liquidity_at_touch_l3(...) |
prepare.liquidity_at_touch(..., level="L3") |
prepare.order_outcome_l3(...) |
prepare.order_outcome(...) |
prepare.queue_position_l3(...) |
prepare.queue_position(...) |
prepare.ofi(ofi_df, trades) |
prepare.trade_imbalance(imbalance_df, trades) |
prepare.ofi_horizon(trades, horizons=...) |
prepare.trade_imbalance_by_window(trades, windows=...) |
prepare.volume_percentiles(...) |
prepare.depth_bands(...) |
prepare.book_snapshot(book), prepare.book_snapshot(book, per_order=True) |
prepare.book_snapshot(book, level="L2"), prepare.book_snapshot(book, level="L3"), with a BookSnapshot |
prepare.vpin(vpin_df) |
prepare.vpin(vpin_result), with a VpinResult |
Command line
| 0.1 | Now |
|---|---|
ob-analytics process PATH -f bitstamp (--format) |
ob-analytics process PATH -s bitstamp (--source). --format now names the output format |
ob-analytics formats |
ob-analytics sources |
ob-analytics capture VENUE --out DIR |
ob-analytics capture SOURCE -o DIR (or --output DIR) |
ob-analytics capture bitstamp read btcusd |
--pair has no default: ob-analytics capture bitstamp --pair btcusd -o DIR |
ob-analytics gallery --volume-scale |
removed |
ob-analytics bitstamp-demo --input PATH |
ob-analytics bitstamp-demo PATH |
Other changes a 0.1 user meets
- Prices are whole numbers of ticks and sizes whole numbers of lots. The price
in the quote currency is
price * tick_size, anddisplay_result(result)(orresult.display()) gives every table in the instrument's units. - Every timestamp is tz-aware UTC, in nanoseconds.
- A Parquet folder saved by 0.1 has no schema version.
load_datareads it with a warning, and leaves its float prices and sizes as they are. - A capture writes its CSV files in format version 2: times in nanoseconds,
and
directionandvolumein place ofsideandamount. The package's readers read both versions. - An unknown name, such as a format, plot backend or source, raises
UnknownNameError, which is also aKeyError. 0.1 raisedValueError, soexcept ValueErroraroundsave_data(fmt=...)orplot(backend=...)->except UnknownNameError. Every other mistake the package reports raisesConfigError, which is also aValueError.
Added¶
- Plots of the spread, the volume profile and the cumulative signed
volume (#583). The new concepts
spread,volume_profileandcumulative_signed_volumeare L2 faces, drawn on Matplotlib, Plotly and Bokeh, on L2 and L3 runs. - New functions for those plots (#583).
depth.quoted_spreadgives the spread's width through time, in the quote currency and in basis points, optionally as time-weighted means per window.bars.volume_profilegives the traded volume per price bin, by aggressor side.flow_toxicity.cumulative_signed_volumegives the running sum of signed trade volume.book.fill_rate_by_distancegives how orders ended, per placement-distance bin. - Bokeh draws
order_outcomeandtrade_size(#583). - Display units from the package root (#577).
from ob_analytics import BookSnapshot, display_resultworks.PipelineResult.display()returns the result in display units, and is kept after the first call; the gallery shares it.display_result(frame, table=..., config=...)converts any table with a contract inschemas.TABLES(lifecycles, queue, bars, costs, book), anddisplay_result(book, config=...)converts aBookSnapshot.PipelineResult.plottakestheme=. schemas.TURNOVER(#577), a column kind for a price times a size. The bars'turnovercarries it, anddisplay_resultscales it by both steps, soturnover / volumestays thevwap.bars()copiestick_sizeandlot_sizefrom the trades'attrsonto the bars.- A capture records whether the venue stated its tick and lot (#578).
meta.jsonholdstick_size_statedandlot_size_stated, andob-analytics auditreports them.CaptureRecordreads both; a capture without them reads as fitted. The Kraken capture reads the pair's tick and lot from Kraken'sinstrumentchannel, so a BTC/USD capture records a tick of 0.1, not 0.01. The cryptofeed capture states the tick when cryptofeed knows it for the venue.RecordedGrid.state()lets a live source state the steps its venue gives. scripts/render_face_images.py(#585) writes one image per Plotly and Bokeh face of the sample gallery.- A page that says what is stable (#584). The new docs page "Stability" lists what 0.2.0 promises to keep, what may still change, and what is internal.
- Read and aggregate a saved run in parts (#206). The new module
ob_analytics.scanreads one table of a saved Parquet folder one batch at a time, throughpyarrow.dataset, so a run larger than memory can be used.scan_tablegives the batches as pandas frames, andread_tablegives the selected rows as one frame; the columns and time range you give go to the Parquet reader.aggregate_by_timereduces a table to one row per fixed time bucket (first, last, min, max, sum, count or mean), andsummarize_depth_filebuilds a newdepth_summaryfrom a saveddepthtable, for example with otherdepth_bpsanddepth_bins. Both give the same numbers as the in-memory computation. Parquet files are now written in row groups of at most 131,072 rows, so a time range skips the rest of a file. Arun_windowsfolder now records the run's config in each file, assave_datadoes, soload_resultgives it back.scripts/bench_scale.py --out-of-coremeasures the memory. - A source can say its trades come on another connection (#555).
TradeOrder.VENUEtells the stale-order check to put trades and order events in order by the venue's time (exchange_timestamp), not by the time the capture received them. A live capture records it inmeta.jsonastrade_order.detect_stale_ordersanddata_quality_summarytake atrade_orderargument, and the summary reports the clock it used asstale_orders_clock. The trades table has an optionalexchange_timestampcolumn, which the reader of Bitstamp-format captures now fills fromtrades.csv. Bitstamp, LOBSTER and Databento keep the receive time. - A test draws every face in the concept table (#504).
tests/test_every_face.pydraws each face on the bundled sample, with each backend that has it. A face must draw marks, or show the reason its data gives for drawing none, such as "Too few trades". Its time and price axes must stay near the run's times and traded prices. Its size axes must not draw sizes larger than the sizes the plot was given. A new face in the table is tested without a new test.tests/test_golden_sources.pypins the output of a small LOBSTER day and the toy price-level session, beside the synthetic and Bitstamp baselines. processandauditread a capture without--source(#502). A live capture writeslevelandreplay_source, the offline source that reads it back, tometa.jsonandmanifest.json, soob-analytics process <ccxt capture> -o outworks. A live source can setreplay_source; one that does not is read by itself when it also replays files, and otherwise bybitstamp(L3) ordepth_csv(L2). A capture made before this is read by the source for its level, or bybitstampwhen it records no level.--sourcethat reads another level than the capture records stops the command with both named.-
processandaudittake the settings of the source that reads the data (#502), one flag per field, ascapturedoes: for example--instrument-id,--publisher-id,--raw-symboland--trades-fromfordatabento, and--price-divisorand--timestamp-unitfordepth_csv.ob-analytics process <path> --source <name> --helplists them. New--symboland--venueset theRunContextfields of the same name. -
Kalshi capture from its WebSocket feed (#240).
ob-analytics capture kalshi --pair <ticker>records every change to a Kalshi market's book, not one poll a second. It needs a Kalshi API key, read fromKALSHI_API_KEY_IDand the private key fileKALSHI_PRIVATE_KEY_PATHnames; an Ed25519 or RSA key works. Each book row carries Kalshi'sseq, soauditfinds a lost change, and a lost change starts a new segment from a new opening book. Book rows carry Kalshi's time. The book is the Yes book, as in the ccxt capture. The source needs the newkalshiextra (pip install "ob-analytics[kalshi]").KalshiSourceandKalshiSettingsare inob_analytics.live. - Kraken capture, order by order (#555).
ob-analytics capture kraken --pair BTC/USDrecords Kraken's per-order (level3) book: each order with its Kraken id, written ascreated,changedanddeleted, plus the public trades. It needs a Kraken API key with "WebSocket interface" on, read fromKRAKEN_API_KEYandKRAKEN_API_SECRET; a normal account can make one. The capture checks Kraken's checksum after every message, and a mismatch starts a new segment (--on-checksum-failure countonly counts it). An order that leaves the--depthwindow (1000 levels by default) is kept open rather than written as a cancel. An amend (adeleteand anaddof the same id) is written as onechangedrow, or as a cancel and a new order under<id>#1when it shrinks the order. Checked live on BTC/USD.KrakenSourceandKrakenSettingsare inob_analytics.live. - Every exported name has an API page entry (#421). New Reference pages
cover synthetic data (
ob_analytics.synth), the sample and toy data (ob_analytics.datasets,sample_csv_path), queue positions (ob_analytics.queue) and the backtester writers (ob_analytics.interop). The existing pages gained thepreparefunctions, the ccxt and cryptofeed sources and their settings, the capture-file helpers, the engine's code constants,BarRule,Feature,OutputTables,ParquetWriterand the instrument columns. A new test,tests/test_api_pages.py, fails when a name in a public module's__all__has no:::entry on a docs page. - A CLI flag reference (#421). The "CLI flag reference" page lists every
flag of every subcommand, and of
capturefor each built-in live source.scripts/cli_reference.pymakes it from the command's own parser, andtests/test_cli_reference.pyfails when the page is out of date. - The gallery commands take the same options, and CLI errors are one
line (#510).
process --gallery,gallery,bitstamp-demoandlobster-demoall take--view,--backendand--title; the demos had only--view, and onlygalleryhad--title.processrefuses each of them without--gallery, as it did--backend. AnObAnalyticsErroror a missing input file from any subcommand prints one line on stderr and exits ob-analytics process /nonexistent/orders.csv -o outended in a pandas traceback.- An "Export to a backtester" how-to (#421). The hftbacktest and Nautilus Trader exports moved there from "Extending ob-analytics".
- A security policy, issue forms and a list of known limitations (#422).
SECURITY.mdsays how to report a security problem privately. New bug and feature forms under.github/ISSUE_TEMPLATE/ask for what a report needs. The Architecture page has a "Known limitations" section: the depth heatmap on a dense book, the feature table without the metric diagnostics, colour scales that do not follow the theme, and Databento's lost queue priority. The bundled sample's README names the data's source and terms. - The Architecture page lists every package file (#422). A new test,
tests/test_module_map.py, fails when a file is missing from the module map or the map names a file that is gone. The class diagram, the stage table and the stage timings (from the speed baseline) are brought up to date, the scale envelope is measured again (about 0.8 GiB per 1M events), and for larger inputs the page points toPipeline.run_windows. - The command line sets what the Python API sets (#411).
processandaudittake--tick-size,--lot-size,--depth-bins,--depth-bpsand--session-tz. Without--tick-sizeand--lot-sizea capture's own still come from itsmeta.json.process --formatsaves in any formatsave_datawrites, such as--format bitstampor--format hftbacktest -o run.npz.process --cut TIMEruns one time window at a time, asPipeline.run_windowsdoes; give it once for each cut, and--no-carryto start each window from an empty book.gallery --backendandprocess --gallery --backendpick the plot backends; give it once for each.-
capture <source>has one flag for each field of the source's settings class, so a plug-in source can be set up from the command line. A field marked with the newob_analytics.sources.CliOptiongets its help text, flag name or value type from the marker; aCredentialfield never gets a flag. -
The docs code runs in CI (#420).
scripts/check_doc_examples.pyruns the Python blocks of every docs page outside the tutorial, page by page and in order, and a newexamplesjob in the docs workflow runs it. A block that cannot run as written, such as one that needs an API key, the network or the reader's own file, carries adocs-test: skipcomment with the reason. Quoted outputs, such as theauditreport and the bar and feature tables, are compared with what the code prints, so a change that moves a figure fails the job. The examples that did not run are fixed: theuncross=example on Data quality, the custom metric that called aResampler.skewpandas does not have, the custom source that took no settings, and blocks with missing imports or undefined names. The quotedauditreport, episode counts, the bar and feature tables, and the quickstart's table shapes are brought up to date. -
CI tests what a user installs, and a release waits for CI (#416). A new
wheeljob installs the built wheel with no extras and runsscripts/smoke_wheel.py: the sample pipeline, a Matplotlib plot, and aConfigErrornaming the extra for a Plotly or Bokeh plot. The release workflow runs the same script on the wheel it publishes, and refuses a commit whose CI run did not pass. New jobs also run the tests on Python 3.14 (now in the classifiers), on Windows (core and offline tests only), with each direct dependency at its lowest allowed version, and with thebacktest-enginesgroup, so the hftbacktest and Nautilus Trader parity tests run. The lowest versions found floors that were wrong. Thebokehextra no longer allows Bokeh 3.0, which does not import with NumPy 2; it now needs 3.2 (#597). Theccxtextra needs ccxt 4.5.90 and thecryptofeedextra cryptofeed 2.4.1, the oldest versions CI tests: ccxt 4.0 has no Coinbase inccxt.pro, and cryptofeed 2.0 has no Independent Reserve. The dev group needs nbmake 1.5.1, the first that loads under pytest 9. Coverage now counts the CLI tests' subprocess runs. CONTRIBUTING lists the checks to mark as required onmain; the speed check still only reports. CI onmainno longer cancels or replaces a commit's run when a newer commit lands, and the docs build runs on every pull request, skipping itself when no site input changed, so it can be a required check. -
Every registry loads plug-ins from entry points (#403). Bar rules, features, writers and plot backends now load from the entry-point groups
ob_analytics.bar_rules,ob_analytics.features,ob_analytics.writersandob_analytics.plot_backends, as sources and metrics already did. One loader serves all six groups, andload_bar_rule_plugins,load_feature_plugins,load_writer_pluginsandload_plot_backend_pluginsre-scan a group. A plug-in that fails to load is now skipped with aUserWarning, not a log message that is off by default. The renderer registry moved tovisualization._renderers, which removes an import cycle that depended on line order. -
InstrumentGridandDepthCsvSettings(#348). A source states the tick and lot size its data is usually on asgrid, anInstrumentGrid, read withprotocols.grid_of; a run's config starts from it, and a field the caller sets wins.DepthCsvSource(settings=DepthCsvSettings(...))sets thetimestamp_unitandprice_divisorof a price-level CSV, which werePipelineConfigfields.Pipeline.run_windowstakesctx=, asrundoes. -
auditcompares the rebuilt book with the venue's own book. The newvenue_bookcheck rebuilds the book from the LOBSTER messages and compares it with the orderbook file, row by row, on every price and size of the levels the file states. Each event is matched with the row of its own message, byoriginal_number. The report gives the number of rows that differ and the first difference (aBookDifference); the summary has the fieldsvenue_book_price_levels,venue_book_rows,venue_book_differing_rowsandvenue_book_first_difference.data_quality_summarytakes the venue's book asvenue_book, read byLobsterSource.venue_bookorlobster_venue_book. A source with no book of its own shows the check as skipped.QualityCheckhas a newskippedfield: a skipped check is info, never fails a run, and is not counted as passed, as the clock checks on data with one clock now are too. On the AAPL samples the two books differ in 99.81% (50 price levels) to 100% (10 price levels) of rows, because the message file does not cover the orders resting before it starts or outside the requested levels; see the LOBSTER how-to (#392). -
auditreports how long the per-order book is crossed. A LOBSTER run with an orderbook file reads its depth table from that file, so thecrossed_bookcheck passed even when the book rebuilt from the messages was crossed: 99.2% of the time on the 10-level AAPL sample. The summary has two new fields,per_order_crossed_pctandper_order_crossed_episodes, a per-order book crossed line, and aper_order_book_crossedwarning when that book is crossed for longer than the depth table. -
One dtype map for the events and trades tables (#351).
ob_analytics.schemasnow holdsEVENT_DTYPESandTRADE_DTYPES, the pandas dtype of every column, next to the column names, with the four ordered categoricals they use,UTC_NS_DTYPE, and two helpers,cast_columnsandempty_frame. The empty frames, the toy datasets and the synthetic session are built from the maps, and every trade reader (Bitstamp, LOBSTER, L2, Databento) casts its output throughTRADE_DTYPES.load_datacasts a current-versiontradesfile back through it._utils._EMPTY_EVENT_DTYPESandEMPTY_TRADES_COLUMNSare removed;UTC_NS_DTYPEis still importable from_utils. -
load_result(path)reads a saved run back as aPipelineResult(#346). It is the inverse ofsave_data(result, path): the four tables come back, and so does the run'sPipelineConfig.save_datanow takes the result itself, and each Parquet file records the run's whole config under the new keyob_analytics_config. A folder that records only the tick and lot size (a windowed run, or one saved by an older version) gets those two, with the display precision that shows one step of each; a folder of whole-number prices or sizes that records neither is warned about.load_resultreads Parquet folders only, and refuses a pickle, which keeps no config. The key is optional, so the schema version stays4.0and older readers ignore it. - A saved run records its level (#510).
save_data(result, path)writes the run's level,"L2"or"L3", under the new keyob_analytics_level, andload_resultreads it back. Before,load_resulttook L2 from an empty events table, so a per-order run with no events came back as L2. A folder without the key, written by an older version, still gets its level from the events table. The key is optional, so the schema version stays4.0. ob_analytics.capture_recordowns a capture'smeta.json(#346).read_record(path)returns a typedCaptureRecord: the source that made the capture, its feed type, trade attribution, sequence kind and clocks, the sequence restarts, and the instrument's tick size and lot size.read_instrument(path)returns only the tick and lot size, as config fields.write_recordandsource_declarationsare what the capture runner and the segment supervisor write it with. The module is outsideob_analytics.live, so code that only replays files does not import the live package.- A replayed capture keeps the venue's time and names its instrument
(#494). A capture writes times in nanoseconds, so Bitstamp's microseconds
are kept, and cryptofeed's times are kept to the microsecond.
meta.jsonrecords the format version (capture_format) and the instrument (venue,symbol), and the loaders put the venue and symbol on every row, so a replay needs noRunContext.read_format(path)returns them. A capture made earlier records no version and still loads, in milliseconds; one made by a later version is refused with a message to upgrade. -
A ccxt capture records the venue's size step as
lot_size(#346), from ccxt's market data, beside the tick size. If a size arrives between two steps, the capture makes the step finer until the size fits, as it does for the tick, and counts the changes inlot_size_changes. The recorded lot is never finer than 1e-8, the default grid. -
auditcounts trades matched by order id (#352). A new summary field,trades_matched_by_order, counts the trades whose taker is an order created with size 0. Bitstamp sends an instant order bought by quote amount that way and never reports what it bought, so its trades are matched to it by its order id, not by size.auditprints the count asmatched by orderand reports it as information; it never fails a run. A feed that does not show takers printsnot checked. The bundled Bitstamp sample has 2.schemas.unsized_order_ids(events)returns the ids of orders created with size 0; the trade reader andauditboth use it. -
A source can take an API key (#239). A source declares each key it needs as a
SecretStr | Nonefield of its settings, marked withCredential(env=..., issued_at=...). The settings read an unset key from that environment variable; withfrom_file=Truethe variable holds the path of a key file. A key is never a command-line option.run_capturestops before it writes anything when a key is missing, and names the variable and where the venue issues keys; a key shorter than eight characters is refused. No file a capture writes holds a key, and neither does the CLI log: a key that reaches one, in a venue's message or an error, is replaced with**********.ob-analytics sourceslists the variables each source needs. No built-in source needs a key yet. See "Use an API key". - Exercises and an editable toy book in the tutorial (#121). Chapters 2,
4 and 6 end with exercises: where a new order queues and which order keeps
the Bitstamp book crossed (chapter 2), what happens if Eve does not cancel
(chapter 4), and how the VPIN bucket size changes the result (chapter 6).
Each solution is collapsed until the reader opens it, and runs when the
documentation is built, so a wrong answer fails the build. The toy session
page now has a book replay to step through, and shows how to rewrite the
session:
toy_orders()returns its twelve orders asToyOrders keyed by actor, andmatch_toy_orders(orders)matches an edited script by price–time priority and returns its events and trades in the layout oftoy_events()andtoy_trades(). - Run a large input one time window at a time (#116).
Pipeline.run_windows(source, boundaries, output)cuts one input at the given times and runs the depth stages on one window at a time, so their peak memory is set by the largest window. Each window is written tooutputas it finishes, as one Parquet file per table, the same foldersave_datawrites;load_datareads it back. Withcarry=True, the default, each window starts from the book the previous one ended with, and the output matches a single run row for row. The one exception is depth where the Databento loader already warns that it is off. A run that fails part-way leaves the output folder as it was. On 1.26M events, eight windows peak at 771 MiB against 1,507 MiB for a single run. The loader still reads the whole input. See "Scale and chunking". - The flow-toxicity faces and the L1 quote are built-in metrics (#118).
vpin,kyle_lambda,order_flow_imbalanceandofi_horizonare now registered metrics, soavailable_conceptslists them andresult.plot("vpin")computes and draws VPIN with the defaults ofcompute_vpin. A keyword goes to the calculation or to the picture, whichever names it:result.plot("vpin", n_buckets=20, threshold=0.8).result.metric(name, **settings)takes the calculation's settings too. The newl1_tickermetric is the Level 1 quote — best bid, best ask and last trade. It draws the three prices over time, or the quote card for one instant withat=;plot("l1_ticker", bid=99, ask=101, last=100)draws a card from plain numbers. Each built-in metric gets a gallery card.ofi_by_horizonis the multi-horizon order flow imbalance that theofi_horizonface draws, now a function inflow_toxicity. - Three measurements that only the plots made are now functions (#493).
Each returns a DataFrame in the instrument's units, and its plot data
function calls it.
analytics.cancelled_orders(events)gives the age and distance from the touch of each cancelled order, read fromorder_lifecycles.analytics.maker_resting_times(events, trades)gives how long the maker of each trade had rested.depth.depth_bands(depth_summary, interval=)gives the volume in each distance band over time, which thevolume_percentilesface stacks. Who is in the queue at the touch was alreadyqueue.queue_age_grid. The pictures do not change. -
A book replay (#117). The
book_replayconcept steps through the book over part of a run, on Plotly: the ladder at one instant per second beside the trades and the mid, with a slider and play buttons at 1×, 5× and 20× real time. Click a trade to move to it: the price level it took is marked in the trade's colour. The L2 face replays the depth table, so its touch equals the depth summary's at every frame; the L3 face shows each order, with stale crossed orders removed so both faces show the same market. The gallery shows it for the zoom window, andprepare.book_replaybuilds it directly. The price-level book the depth summary is built on is now its own class,ob_analytics.depth.PriceLevelBook, andprice_level_snapshotsreturns that book at many instants in one pass. -
A page on what each feed shows (#288). "What each feed shows" describes 16 properties that decide what a capture can tell you, such as depth shown, what can be missed, sequence, clocks and taker side. It gives each property's value for every source and venue, checked with live captures. Every source's how-to page now opens with its values and when to use it.
FeedType.PRICE_LEVELS, the crossing value for L2 feeds (#288). The ccxt source, cryptofeed at L2 anddepth_csvdeclare it instead ofMATCHED_BOOK. The venue does not publish a crossed price-level book, soauditscores a crossed one as an error, as for a matched book: most often, the capture kept a level the venue removed. Captures made before this recordmatched_bookand are scored the same way. In theSourceprotocol,levelandfeed_typeare now read-only, so a source can work either one out, as the cryptofeed source does from its venue.-
A live capture can run for days (#150).
ob-analytics capturenow writes a directory of segments with amanifest.json. A lost connection ends the segment; the capture waits (1 s, doubling to 60 s) and starts a new one from a fresh snapshot.--roll-minutesand--roll-mbstart a new segment by time or size, and the new segment is streaming before the old one stops, so a roll loses nothing. Running the same command again continues the capture, and closes a segment a crashed process left open; a lock on the directory stops a second process from writing to it at once. The manifest records every segment, why it ended, and every gap with its cause.processandauditread the whole capture, andauditadds the checkscapture_gaps,unfinished_segmentsanddropped_messages. From Python:ob_analytics.live.run_captureandread_manifest. -
Each source declares which orders of a trade it can name (#284). The new
Source.trade_attribution(TradeAttribution.BOTH,MAKER_ONLYorNONE) says whether a feed's order events show the trade's maker, its taker, or neither.bitstampnames both.lobster,databentoandcryptofeedat L3 name the maker only: their feeds show resting orders, and a taker trades on arrival. The L2 sources name neither. Theunmatched_tradescheck now counts only the orders the feed can name, and says which. Before, a Databento run could only report every trade as unmatched, and LOBSTER's guessed takers counted as matches. A source that does not declare it is read asBOTH, the old check. - A capture records what its source declares, and
auditholds it to that (#284).meta.jsonnow recordssource,feed_typeandtrade_attribution.ob-analytics processcopiesmeta.jsoninto its output.auditchecks a capture against the declarations of the source that made it, even when--sourcenames another: a cryptofeed L3 capture is read with--source bitstamp, whose feed shows more. Read the record withrecorded_source,recorded_feed_typeandrecorded_trade_attribution. -
A cryptofeed reconnect is counted (#309). cryptofeed reconnects by itself when it loses a message and starts again from a new opening book. The capture counts each new opening book as
book_resyncsinmeta.json, as the ccxt source already did. On Bitfinex and Blockchain.com the venue's count starts again too; the capture counts that step back assequence_restarts, andauditleaves it out ofsequence_out_of_order, so a reconnect is scored the same on every venue. Read it withrecorded_sequence_restartsand pass it todata_quality_summary(sequence_restarts=...). -
A Bokeh plot backend (#123).
result.plot(concept, backend="bokeh")renders the core concepts —trade_tape,depth_heatmap,book_snapshot,depth_chart— as interactive Bokeh figures, alongside the static Matplotlib default and the Plotly backend. Suited to Bokeh / Panel server dashboards and streaming views. Ships in the newbokehextra:pip install "ob-analytics[bokeh]". -
Binance venue notes and a market-data mirror (#101). A new how-to page covers capturing Binance spot through ccxt: the location block, the
binanceusalternative, the depth a 100-level book reaches, and trade sides.capture ccxt --market-data-mirror(CcxtSettings.market_data_mirror) reads Binance spot from Binance's market-data-only endpoints. NewSequenceKindandrecorded_sequence_kind(), akindargument ondetect_sequence_gaps(), and asequence_kindargument ondata_quality_summary(). -
Find hidden liquidity (#111).
detect_icebergs(events, trades)finds iceberg orders from their refills: a resting order filled out, then a new order at the same side and price within one millisecond. It chains refills into one suspected iceberg and gives each aconfidence.hidden_trades(events, trades, depth_summary)returns the trades that printed strictly inside the visible spread. On one day of LOBSTER AAPL it finds 85% of the type-5 hidden executions, with no false ones. The synthetic generator now labels its iceberg slices inSynthSession.icebergs, so the detector can be scored exactly. See the hidden liquidity how-to. -
Iceberg refills and hidden trades drawn on the depth heatmap and order activity map (#272). Both L3 faces now overlay
detect_icebergsandhidden_trades: a diamond marks each refill, joined by a line per iceberg (opacity =confidence); a star marks a hidden trade, with a thin line to the standing best bid and best ask so the print reads as inside that spread. A filled star is a confirmed hidden order; an open star is a trade to check, where the maker order was actually visible or its maker identity did not resolve at all — the diff-feed case the how-to guide describes. Both overlays clip to the gallery's zoom window, and are absent without error when a run has neither. Newprepare.hidden_liquidity_overlaybuilds the same overlay for a custom plot.hidden_tradesnow returnsbest_bid_price/best_ask_priceindepth_summary's own dtype instead of always casting toint64, so a caller already holding display-unit floats gets floats back rather than a silently truncated value. -
A feature table for models (#149).
features(trades, quotes)returns one tidy table: a point in time on each row and a microstructure feature in each column — the shape a model or a study wants. It replaces a join per measurement.
Two decisions make the table, and they are separate. Where the rows fall is
a bar rule, so features() takes the same sampling arguments bars() does
and the same arguments give the same cut in both; a time grid is the time
rule. What each column measures is a Feature, and ten ship: price,
returns, flow, spread, mid_price, micro_price, imbalance,
depth, vpin and kyle_lambda, writing 20 columns between them.
register_feature adds one of your own, usable by name with no edit to the
package.
Every row is stated as of the close of its bar. The trade columns hold what happened inside the bar, and the book columns hold the book as it stood at the close, a backward as-of join. Nothing from after that instant reaches the row, so the table carries no look-ahead — which is tested by truncating the inputs and checking that the rows that survive are unchanged, for every rule and every feature. The table holds no target either: a target looks forward, and building one is a shift the caller makes deliberately.
Two quote states are not books anything could have traded against, and both
would otherwise arrive as ordinary numbers: a side with nothing resting on
it, which the depth engine marks with a price of 0, and a crossed book,
which a diff feed can genuinely hold. readable_quotes() drops them from
the reference series, so a row reaches back to the last quote it could read
— the same test transaction_costs already applied before measuring against
a mid. A locked book, bid equal to ask, is a real state at a spread of zero
and is kept.
Without a quotes frame the five book features are skipped and the table
holds the trade features alone; naming one explicitly raises instead. Two
features that would write the same column are an error rather than a silent
overwrite, and so is a name listed twice in include; a trailing window a
feature cannot use is refused when the feature is built. See the "Build a feature table"
how-to,
which ends in a baseline model.
- Databento market-by-order files (#100).
DatabentoSourcereads Databento's DBN files in the MBO schema, which is a per-order feed: every record carries an order id, so a file replays through the full L3 path with order lifetimes, queue position and order classification. It reaches many venues that no other source in the package does, US equities and futures among them.
Databento reports an execution as a fill record that does not change the
book, followed by the cancel or modify that takes the size off it. The loader
pairs the two, so fill tells an execution apart from a cancel the trader
asked for, and each trade names the resting order it hit. The aggressor's
side comes from the venue rather than a classifier. A book clear deletes the
orders still resting, and the record's two clocks are kept apart: Databento's
receive time orders the events, the venue's own becomes
exchange_timestamp.
A modify that moves an order to another price or makes it bigger is recorded
as a changed event with the new price and size, and the depth follows it
(see Changed). The loss of queue priority is not modelled. The one modify the
depth still cannot follow is one that carries a fill and also moves the order
or changes its size by more than the fill; the loader says how many rows the
depth will be off by.
A feed the loader does not understand is refused: a publisher that only sends top-of-book or price-level data, because its order ids mean nothing; a price-level schema; a file covering more than one book; an action outside DBN's own alphabet; an order id too big for the schema's signed 64-bit id. A malformed record inside a feed it does understand — no price, or no side on a book action — is dropped and counted in a warning, because refusing a whole session over a handful of them would be worse.
Trades are built from the fill records by default, so each names the resting
order it hit. A trade the publisher sent no fill for — an auction, a trade
against a non-displayed order, an off-exchange print — is then left out, and
the loader warns with the volume. DatabentoSettings(trades_from="prints")
builds the trades from the whole tape instead, without makers; use it for
VWAP, bars, flow toxicity and costs. DatabentoWriter
writes an events frame back out as DBN. scripts/databento_window.py sizes a
query against the in-memory envelope before downloading it, then runs one
window at a time. databento is an optional extra
(pip install "ob-analytics[databento]"). See the "Process Databento MBO
files"
how-to.
- Flow-toxicity results say when they rest on too little data (#119). VPIN
and Kyle's λ were designed for markets that trade thousands of times a
minute, and on a thin tape they used to return a number with no sign that it
meant little.
KyleLambdaResultnow hassignificantanddiagnostics: λ is flagged when there are fewer than 30 regression windows (KYLE_MIN_WINDOWS), when|t|is below 2 (KYLE_MIN_T_STAT), or when the fit is undefined. It also carries a confidence interval,ci_low/ci_high, from a block bootstrap over the windows (1000 resamples by default, under a millisecond on the bundled sample, seeded withseed=0so the same trades give the same interval;n_boot=0skips it).
compute_vpin records how it ran in the frame's attrs: bucket_volume,
bucket_volume_rule, n_buckets, and diagnostics, which flags a result
with fewer complete buckets than n_buckets. bucket_volume is now
optional. Left out, it is picked by the new vpin_bucket_volume(trades),
which applies the common rule of average daily volume ÷ 50; a session
shorter than a day is scaled up to a day at the rate it traded
(trading_day="24h" by default). Existing calls are unchanged.
On the bundled sample, λ at 5-minute windows is flagged on both counts (7 windows, t = 1.45) and its interval spans zero; VPIN with the default bucket fills one bucket and says so. Tutorial chapter 6 and the flow-toxicity how-to now show these checks in place of the hand-written caveats.
- Bars: the trade stream resampled into OHLCV rows (#148).
bars(trades, rule, threshold)cuts a trades frame into bars and returns one row each with open, high, low, close, volume, turnover, VWAP, and the buy/sell split of that volume. Five rules ship with it:time(a fixed span of the clock),tick(a fixed number of trades),volumeanddollar(a fixed amount of size, or of price × size), andimbalance(signed size drifting a set amount from where the bar opened). Leave the threshold out and the rule picks one aiming at about 50 bars.
What differs between bar types is only where the boundaries fall, so that is
all a rule decides: BarRule states a name, how it reads its threshold,
and which bar each trade belongs to. register_bar_rule adds one of your
own, usable by name with no edit to the package. Feeds that don't label the
aggressor are classified the same way the flow-toxicity metrics do.
Bars draw as a "bars" plot face on both backends — candles over a strip of
volume coloured by the net aggressor — and bars_panel() puts them in a
gallery. The demos show a clock cut and a volume cut side by side. See the
"Build bars from trades"
how-to.
- Transaction cost and price impact (#110). A new
costmodule answers what trading cost, rather than what the book advertised.transaction_costs(trades, quotes)returns one row per trade with the effective spread — what the taker paid to cross — split into the realized spread the liquidity provider kept and the price impact the trade caused, in price units and in basis points. The three add up exactly, trade by trade.cost_summary()reduces that to volume-weighted session figures and reports how many trades each one could be measured on.
amihud() and roll_spread() read liquidity from the trade prices alone,
so they run on a tape with no quotes and no aggressor side: the price move a
unit of turnover buys, and the spread implied by bid-ask bounce. Roll also
returns the lag-1 autocorrelation of the price changes, which its model
puts at exactly -0.5; how far the number sits from that is how little of
the price movement the bounce explains. On the bundled capture it is
+0.197 and the estimate has no real root, so it is NaN rather than a
number the model does not support. The diagnostic matters in the other
direction too: when the autocovariance lands negative by chance Roll returns
a spread that is not there, and the autocorrelation is what catches it.
The mid a trade is measured against is the last quote strictly before it,
skipping crossed quotes: on a frame built from the same event stream, the
quote sharing a trade's instant is the book after that trade took the touch,
and a crossed book has no midpoint at all. A trade in the last horizon of
the capture has no future mid, so its realized spread is NaN rather than
the final quote reused.
transaction_costs takes mid_column to measure against a reference other
than the plain mid — "micro_price" for the size-weighted mid, which on the
bundled capture reads 1.24 bps against the plain mid's 1.45.
The decomposition draws as a level-less transaction_costs face on both
backends — two lines with the impact as the band between them — and
transaction_costs_panel() puts it in a gallery. Both demos now include it.
See the "Measure transaction costs"
how-to.
- Polymarket prediction markets, through the ccxt source (#103).
ob-analytics capture ccxt --exchange polymarket --pair <token id>streams one outcome's order book and trades over Polymarket's public websocket, with no account or API key.--pairis Polymarket's token id for the outcome, which the Gamma API lists asclobTokenIds. Each outcome is its own book, and its trades are priced in that outcome.
Polymarket makes a market's tick finer as the price nears 0 or 1, so a ccxt
capture now makes its recorded tick size finer when a price arrives between
two ticks, and counts each change in tick_size_changes in meta.json. The
replay then reads every price exactly. See the "Capture Polymarket
prediction markets"
how-to.
- Kalshi prediction markets, through the ccxt source (#102).
ob-analytics capture ccxt --exchange kalshi --pair <market ticker>records a Kalshi market's order book and trades from Kalshi's public API, with no account or API key, andob-analytics processreplays it through the L2 path. The ccxt source now looks up CCXT's prediction markets (ccxt.prediction: Kalshi, Polymarket and others) as well as its crypto exchanges; before,--exchange kalshifailed with "Unknown CCXT exchange".binanceandhyperliquidare in both lists, so the plain id keeps meaning the crypto exchange andprediction/<id>picks the prediction market.
The captured book is the market's Yes book: a bid to buy No at p is
recorded as an offer to sell Yes at 1 - p, and a trade is priced in Yes
and signed from the Yes side. A ccxt capture also records its market's tick
size in meta.json, which process and audit use. See the "Capture
Kalshi prediction markets"
how-to.
- A capture records which rows came from its opening snapshot (#237).
orders.csvanddepth.csvgain anorigincolumn:snapshotfor the opening book,streamfor a live message,shutdownfor a synthetic close-out. The capture runner fills it in, so every live source gets it without a change, and the loaders carry it through toevents. Before this, the only way to tell a snapshot row from a live one was to compare itsexchange_timestampwithsnapshot_microtimestampinmeta.json.
meta.json also reports n_snapshot_unconfirmed: how many orders in the
opening book no later order event or trade mentioned. The bundled Bitstamp
sample has 6,294 of 6,512. Almost all of them sit far from the touch and did
not trade, but two stale asks among them held the best ask for most of the
session. See "Capture live
data".
-
auditnames stale resting orders (#234). A trade above a resting ask, or below a resting bid, shows that the order has gone. An order the venue then does not report again within one second is now reported as astale_orderswarning, and the worst one is named with its id, side, price and how long it held the touch. On the bundled Bitstamp sample this names ask2002347646152704, which held the ask touch for 27 minutes and causes almost all of the 91.6% crossed time. The crossing note no longer calls a diff feed's crossing normal when the run has stale orders. Nothing is removed:order_book()still replays what the feed said. New public names:detect_stale_orders,StaleOrder,DataQualitySummary.stale_orders, and atick_size=argument ondata_quality_summary. -
A metric registry, so a user metric runs and plots with no core edit (#140). A metric is a plain object with a
name, atitle, thelevelsit applies to,compute(result)andprepare(frame)— no base class to inherit, the same structural typing sources and writers use. Register it withregister_metric(metric), or ship it in your own package under theob_analytics.metricsentry-point group andload_metric_plugins()finds it atimport ob_analytics.
A registered metric is a level-less plot concept under its own name, so a
renderer at (name, None, backend) is its face. It then appears in
available_concepts(result), renders through result.plot(name), and gets
its own gallery card with no extra_panels=. Metrics run when asked for, not
during Pipeline.run: result.metric(name) computes one and
result.metrics() computes every metric whose levels include the run's
resolution — so an L3-only metric is skipped on an L2 run instead of failing
on its empty events table, and a metric that raises is logged and its card
dropped, so one broken metric cannot stop the gallery being built. New public
names: Metric,
register_metric, list_metrics, get_metric, load_metric_plugins,
PipelineResult.metric / .metrics. See the "A new metric"
how-to.
ob-analytics audit, a data-quality gate (#108). The oldvalidateverb is nowaudit(the old name still works), it scores the run against named checks, and it exits non-zero when one fails — so a script can stop before trusting a feed. Five checks are new: orphan orders (changed or deleted with nocreatedrow), non-positive prices, negative volumes or fills, and the two clock-order defects — a venue timestamp later than the receive timestamp, and messages that arrived out of venue order.auditalso loads withtrack_sequenceon, so the dropped-message check (#146) reads a venue sequence whenever the feed carries one.
Each check carries a Severity: an error fails the run, a warning
fails it only under --strict, and info never does. A crossed resting
book is scored by feed type, not by size — an error on a matched book, a
faithful replay on a diff feed. --json emits every check plus an ok
verdict; --from-parquet audits a saved process output without re-running
the pipeline. New public names: Severity, QualityCheck, and
DataQualitySummary.ok / .errors / .warnings / .checks. See the
"Check data quality with audit" how-to.
PipelineResult.to_arrow()andPipelineResult.to_polars()(#104). Both return the run's four tables —events,trades,depth,depth_summary— keyed by name, with the same keys on every run: on an L2 runeventsis an empty table, not a missing key. The Arrow tables carry the schema version and tick size in their metadata, the same key-value metadata the Parquet files carry, so a reader handed tables in memory is no worse off than one reading files. Polars is not a dependency and is not installed;to_polars()raisesImportErrorwith an install hint when it is missing, and Polars keeps no schema metadata, so the version and tick size do not survive that conversion.- The result keeps the tables built from it (#498). New accessors on
PipelineResult:result.lifecycles(),result.queue(levels=...),result.book(at, ...),result.bars(...)andresult.features(...). Each builds its table on the first call and returns the same table on a later call with the same settings.result.bookkeeps one snapshot per instant and settings. The display-unit tables and the gallery's view of the run are kept the same way, so a secondresult.plot(...),plot_result(...)orbuild_gallery_model(...)on one result does not convert the tables or find the busiest window again. One gallery now builds the order lifecycles once (it built them four times) and the queue once.save_data(result, path, extra_tables=["lifecycles", "queue"])saves the two per-order tables beside the four core tables, andload_resultreads them back, so the accessors of the loaded result do not build them again.cancelled_ordersand the per-orderpreparefunctions take an optionallifecycles=(and the queue facequeue=) so they can reuse a table you already have. - The frame-type contract is written down in
Frame types: pandas in, pandas out:
public functions take and return pandas, plug-ins are handed pandas, and the
versioned Parquet is how other tools read the output. The reasoning is in
adr/0002-dataframe-library.md. - cryptofeed source for live L2 and L3 capture (
ob-analytics capture cryptofeed --exchange <venue> --pair <symbol>). The per-order complement to the CCXT source: venues publishing an order-by-order book recordorders.csvwith the venue's own ids and replay through the full reconstruction pipeline; the rest recorddepth.csvfor the L2 path. The level is discovered from the venue's declared channels rather than a hardcoded list, and--levelforces it — except L3 on a venue that publishes none, which raises. Ships as the optional[cryptofeed]extra, imported lazily. See the new "Capture cryptofeed venues" how-to. -
sequenceis now written toorders.csv. The capture sink dropped the venue sequence on the L3 path, sodetect_sequence_gapshad nothing to read; L2 already kept it. cryptofeed captures also reportsequence_gaps/sequence_missinginmeta.json. -
L2 (price-level) depth-native ingestion path. Price-level feeds (Binance, Kalshi, Polymarket, most CCXT sources) publish
[price, quantity]levels and diffs with no order IDs; ob-analytics now ingests them as a first-class L2 resolution instead of faking per-order state. A format declares itsresolution(Level.L2/Level.L3, exposed asob_analytics.Level); an L2 format's loader is aDepthSourcethat yields the depth frame directly, andPipeline.runtakes the price-level path — depth metrics / spread and trade-sign classification run, while the per-order stages (set_order_types,order_aggressiveness, queue reconstruction) are skipped.PipelineResultgains aresolutionfield and, on an L2 run, returns an empty (schema-valid)eventsframe. Ships thedepth_csvformat (L2DepthLoader,L2TradeReader,DepthCsvWriter,DepthCsvFormat) for the canonical L2 CSV schema, atoy_l2_depth()/toy_l2_trades()synthetic snapshot+delta fixture, anddata_quality_summary+ the gallery degrade gracefully (L3-only faces skipped, not errored).ob-analytics process|validate --format depth_csvworks from the CLI. Unblocks the aggregated venue connectors. Documented in a new "Process L2 feeds" how-to. - Trade-sign classification (
ob_analytics.trade_sign) for feeds that don't label the aggressor side.tick_rule(last-price-change sign),lee_ready(quote-midpoint test with a tick-rule fallback), andbulk_volume_classification(BVC — the buy fraction of a volume bar via the standardized-price-change normal CDF).classify_trade_sign(trades, method=..., quotes=...)is the per-trade entry point.compute_vpinandorder_flow_imbalancegainsign_method/quotesarguments and now synthesizedirectionautomatically when the trades frame has none — so VPIN and OFI run on L2 / aggregated captures, not just L3. A nativedirectionis still honored unchanged (sign_method=None). On the bundled Bitstamp L3 sample the classifiers agree with the true maker/taker side ~0.83 (tick) / ~0.79 (Lee–Ready) — validated by a test harness. - Feed classification. Every format declares a
FeedType(matched_bookvsdiff_feed) through afeed_typeattribute —BitstampFormat→diff_feed,LobsterFormat→matched_book— so downstream code reasons about crossed books by coordinate, not by format name. Exposed asob_analytics.FeedType. order_book(..., uncross=True)evicts crossed resting orders for display, mirroring the depth engine's crossed-level eviction. The default stays faithful, so a diff feed's genuinely crossed resting orders are replayed as-is. Threaded throughprepare.book_snapshot(..., uncross=True)(also drivesdepth_chart) and available frame-level asanalytics.uncross_book_sides.- Per-run data-quality summary.
data_quality_summary()and the newob-analytics validate <source>CLI verb report the crossed-resting %, unmatched-trades %, duplicate ids, and pre-existing-order count. A new "Data quality: matched book vs diff feed" explanation page and avalidatehow-to document the distinction.
Changed¶
order_outcomedraws the fill rate per placement-distance bin (#583), not one point per order.prepare.order_outcometakesdistance_binsandmin_bin_orders;bps_quantiles,min_positive_bpsandbinsare removed, and the payload is new.trade_sizedraws the number of trades per size range (#583), buys up and sells down, on a log axis with plain labels, not a jittered strip.prepare.trade_sizetakessize_binsandmin_trades, and the payload is new.- The Databento loader and trade reader warn about data they drop (#579).
A
UserWarningreports orphan cancels, oversized cancels, fills with no book record, andtrades_from='prints'with no prints. A gallery panel that fails also warns. PriceLevelBookand the compiled depth replay are inob_analytics.engine(#580), beside the queue replay.ob_analytics.depth.PriceLevelBookis the same class, exported from both modules.engine.crossed_prefix_countsis compiled with numba (#580) and is the one copy of the crossed-touch rule. It takes numpy arrays, as its signature says; a pandas Series no longer works.- The plots read the result's per-order tables (#580). They take the
lifecycles and the touch queue from
PipelineResult.lifecycles()and.queue(), so a table the result already holds, built or loaded from disk, is not built again for a plot. - The gallery runs the iceberg and hidden-trade detectors only for a face
that draws them (#580). A failed detector run now warns at that point,
not in
build_gallery_model. - The
bokehextra needs bokeh 3.2 or later (#597), not 3.1. The spread and cumulative signed volume plots usefigure.varea_step, which bokeh 3.2 added. - The docs say a wrong-type error is a plain
TypeError(#579), outsideObAnalyticsError. They no longer say Bokeh suits streaming views (#583): a Bokeh figure is drawn once and does not update as new data arrives. - A metric returns what the function it wraps returns (#577).
result.metric("vpin")returns aVpinResultandresult.metric("kyle_lambda")aKyleLambdaResult, asvpin()andkyle_lambda()do; they returned a DataFrame with the fit inattrs. Each value ofresult.metrics()is whatresult.metric(name)returns.Metric.computereturns the function's result (a table or a result object), andMetric.prepare(computed, /)takes it. - Settings are keyword-only after the input tables (#577). For example
bars(trades, "volume", 0.5)->bars(trades, rule="volume", threshold=0.5). This coversbars,features,result.bars,result.features,result.book(at),summarize_depth,book_imbalance,book_levels(num_levels),filter_depth,price_level_snapshots(times),classify_trade_sign,bulk_volume_classification(bucket_volume),resolve_direction,mid_before,prevailing_midandvolume_buckets(context), andcheck_bucket_count. quotesanddepth_summaryname two inputs (#577). A parameter isquoteswhen the function reads only the touch, anddepth_summarywhen it reads the depth bins too.features(trades, quotes=...)->features(trades, depth_summary=...);get_spread,micro_price,hidden_tradesandorder_aggressivenesstakequoteswhere they tookdepth_summary.ob_analytics.engine.BookSnapshot->ob_analytics.engine.BookSides(#577), so only the user-facingBookSnapshothas that name.from ob_analytics.visualization import display_result->from ob_analytics import display_result; the visualization re-export is gone.- The
scanfunctions takepath, andaggregate_by_timetakes its settings by keyword (#584).scan_table(folder, ...)->scan_table(path, ...), the nameload_datauses, and the same forread_table,aggregate_by_timeandsummarize_depth_file.aggregate_by_time(path, table, "1min", "mean")->aggregate_by_time(path, table, every="1min", how="mean").summarize_depth_filereads the run's level and declarations asload_resultdoes, and warns when it cannot read them. - A windowed run deletes the working folders an earlier run left (#584).
run_windowsworks in a.run_windows-*folder inside the output folder. A run stopped hard cannot delete it, so each run first deletes any such folder it finds there. - A ccxt or Kalshi capture whose venue gives no tick records one fitted to
its prices (#578), instead of none. Every built-in live source names its
reader (
replay_source), andprocessandauditwarn when--sourcenames a different reader of the same level. The recorded grid attribute of the live sources isrecorded_grid; it wasgridon the cryptofeed source and the Bitstamp capturer, andgrid_seenon Kraken. LobsterTradeReaderno longer builds dicts over every event (#203). It looked up each execution'stakerandtaker_ogin two Python dicts of all event ids, one execution at a time. One pandas index lookup now does the same. The output is the same, value for value. On one desktop the reader fell from 0.79 s to 0.33 s at 5M events, and from 2.82 s to 1.39 s with 2.5M executions.BitstampTradeReaderno longer builds a dict over every event (#203). It looked up each trade'smaker_og/taker_ogin a Python dict of all event ids, so its time grew with the events, not the trades. A pandas index lookup now does the same. The output is the same, value for value. On one desktop the reader fell from 1.78 s to 0.38 s at 5M events (the bundled sample tiled 16 times), about 11% of a whole run, and from 0.096 s to 0.019 s on the sample.- A windowed Databento run no longer grows with the input (#569).
Pipeline.run_windowsused to decide order types over the whole run in memory, so its peak grew by about 0.78 GiB per day of AAPL MBO data. It now writes the values the rule reads to the run's working folder and decides the types one group of orders at a time, and it keeps the trades on disk while the depth stages run. With one-hour windows, ten days of AAPL (38.7M records) peak at 1.43 GiB, and one day at 1.25 GiB. The output is the same, row for row. Loaders other than Databento still read the whole input. - The Bitstamp and L2 CSV loaders read one window at a time (#569). In
Pipeline.run_windows,BitstampLoaderandDepthCsvLoadernow read the file in parts and sort its rows on disk, in the run's working folder, so the file need not be in time order. This covers the bundled sample, the Bitstamp, Kraken and cryptofeed captures, and every ccxt or Kalshi capture. On the bundled sample repeated eight times, the peak fell from 1,269 MiB to 477 MiB (Bitstamp) and from 794 MiB to 401 MiB (L2). The output is the same, row for row.WindowedLoader.load_windowstakes a keyword-onlyworkingfolder. In a windowed run, a warning about values rounded to the grid comes once per part read, and a bad row's number counts from the start of its part, with a note giving the file row the part starts at. A run with text order ids stops with an error if two ids share a 64-bit hash. LOBSTER still reads its whole file. - The depth replay is compiled with numba (#138).
summarize_depth,DepthSummaryEngineandPriceLevelBooknow apply the depth rows in a loop that numba compiles to machine code, in place of a dozen small numpy calls per row. The outputs are the same, value for value: on the bundled sample, the synthetic session and a full Databento AAPL day of 3.7 million events. On one desktop,depth_metricsfell from 7.15 s to 0.37 s on the sample, and from 61.9 s to 6.3 s on the AAPL day, where a whole run fell from 90 s to 35 s. numba is now a required dependency (adr/0003-numba-for-the-rebuild-loops.md). It adds about 110 MiB to a process's memory. The first call in a new environment compiles the loop, which takes a few seconds and about 60 MiB more at its peak; numba caches the result on disk for later processes.bench-baseline.jsonis recorded again on the CI runner, where every run compiles and peak memory rises by 160 to 210 MiB per stage.PriceLevelBook's array attributes are now views of the book's storage, so a laterupdatecan change them.scripts/bench_scale.pyruns the loop once before it times anything, so no stage's seconds include the compile. - The queue engine is compiled with numba (#138).
queue_positions, inob_analytics.queueand in the engine, now rebuilds the FIFO queues in a loop that numba compiles, in place of the dictionaries, heaps and Fenwick trees it walked in Python. The outputs are the same, bit for bit: on the bundled sample, the synthetic session, the AAPL day, and random event streams checked against a plain model of the rules. On one desktop, thequeue_positionsstage fell from 0.70 s to 0.12 s on the sample, from 0.82 s to 0.11 s on the synthetic session, and from 7.0 s to 1.1 s on the AAPL day, where a whole run fell from 35 s to 30 s. Peak memory did not rise. The compiled loop is part of the engine, which may now import numba as well as numpy (ADR 0003). The first call in a new environment compiles it, which takes about four seconds.scripts/bench_scale.pycompiles it before it times anything. The engine'squeue_positionsnow raisesValueErrorfor a visible row with a side code other than bid or ask, aNAT_NStime or a NaN resting price, which the compiled loop cannot queue.bench-baseline.jsonis recorded again on the CI runner. Every CI run compiles both loops, which puts peak memory 155 to 270 MiB above a run without numba. - One contract per table (#499).
ob_analytics.schemas.TABLESholds a contract for every table the package returns: events, trades, depth, depth_summary, order lifecycles, queue positions, book snapshots, bars and transaction costs. Each column has its dtype and says whether it is a price, a size or neither.EVENT_COLUMNS,EVENT_DTYPES,BAR_COLUMNS,COST_COLUMNS,QUEUE_COLUMNSand the other column tuples are now taken from the contracts, with the same contents as before.display_resultreads the price and size tags instead of keeping its own column lists and finding size columns by the letters "vol".schemas.depth_binsreturns the side and distance of eachdepth_summarybin column, so no module reads those names with a pattern of its own.docs/schema.mdnow also describes the queue, bars and costs tables, and a test checks the page against the contracts. - Four helpers moved down a layer (#522). Each was the only reason for an
upward import, so ADR 0001 and the layer test no longer allow those imports.
QualityCheckandSeveritynow live in the shared layer, andob_analytics.qualitystill exports them, so a capture manifest no longer importsquality. The windowed-loader types moved toprotocols, so the Databento loader no longer imports_windows. The "no level given" marker of the plot functions moved to_utils, so plot data no longer importspipeline.price_level_volumehas a newwarn_overdrawnoption, and the privatedepth._book_levelsis now the publicdepth.book_levels, so the LOBSTER loader uses no privatedepthfunctions.book_levelschecks its columns and refuses a depth table in display units. It still importsdepthandquality, as ADR 0001 allows.quality.book_crossingandquality.CROSSED_TOLERANCE_PCTare now inquality.__all__and on the Data quality API page. - A test checks every layer's imports (#495). Before, only the engine's
imports were checked against ADR 0001.
tests/test_layer_imports.pynow puts every module in a layer and fails when a module imports from a layer above it. ADR 0001 lists the upward imports that stay, and why:Metric.prepareby design, and a few small helpers for now. The LOBSTER loader no longer imports a private name fromquality. The function it uses is nowquality.book_crossing. - seaborn 0.13.2 or later is required. seaborn 0.13.0 and 0.13.1 draw an empty events histogram when the direction column has pandas 3's string type.
- The README and Getting started describe the current package (#422):
every source, the plot backends and all six extras. Both say that live
capture is supported on Linux and macOS only, and that the docs follow
main, not the newest release. - The glossary uses the code's names (#423). It now defines the package's terms by the same names the code uses: the venue, resolution and L1/L2/L3, order type, depth bin, rank, and the order events, queue, capture, data quality and plot terms, with the column or function name where there is one.
-
Every measure reports in the instrument's own units (#400). VPIN, Kyle's λ, order flow imbalance,
transaction_costs,cost_summary,amihud,roll_spread,trade_impactsand thel1_tickerandbook_signalsmetrics readtick_sizeandlot_sizefrom the frame'sattrsand return prices in the quote currency and sizes in BTC, shares or contracts, whether they are given a run's integer ticks and lots or a display-unit frame.result.metric(name),result.plot(name)and the bare function now give the same numbers:result.plotand the gallery compute a metric on the run as stored instead of ondisplay_result, which made Amihud differ by 10^10 between the two. A frame with integer prices or sizes and notick_sizeorlot_sizeon itsattrsnow raisesConfigError.amihud,roll_spread,transaction_costsandbook_signalsare registered metrics, soresult.metric("amihud")andresult.plot("transaction_costs")work and each is a gallery card; the demos no longer add their own cost card.compute_kyle_lambdatakessign_methodandquoteslikecompute_vpinandorder_flow_imbalance, so it no longer needs adirectioncolumn. -
Each core helper is written once (#402). Datetimes become int64 nanoseconds through one
epoch_ns, and the loaders parse timestamp columns through oneto_utc_ns. Onevalidate_columns, inschemas, checks required columns, sovalidate_events_df,validate_trades_dfandvalidate_depth_dfnow name the missing columns sorted, followed by the columns available. Each tick helper shares its body with its lot twin.trade_sign.volume_bucketscuts trades into the equal-volume buckets ofcompute_vpinandbulk_volume_classification.depth.imbalance_levelsclamps a depth level count to the bins a summary carries. The newPipelineResult.tables()returns the four core tables, and the demos andprocesssave a result through it.Pipeline.runandPipeline.run_windowsload their inputs through one path, andscripts/bench_scale.pytimes the pipeline's own stages (pipeline.STAGES). Outputs are unchanged, except that a sign-based VPIN can differ in the last bit of a float, because a bucket's volume is now added up from its parts. Acompute_vpin(sign_method="bvc")call with a badbucket_volumenow reports the error undercompute_vpin. -
The mid-price formula is written once (#510). The feature table, the trade signs, the book signals and the depth heatmap's mid line use one helper in
depth.py. The Plotly backend has one colour converter, and a helper that only a test used has moved into that test. No output changes. -
Every event loader casts through
EVENT_DTYPES, and the validators check dtypes (#379). The Bitstamp, LOBSTER and Databento loaders build their events through the newschemas.cast_events, which keeps text order ids (UUIDs) asobject.validate_events_dfandvalidate_trades_dfnow also fail a column whose dtype differs from the map, and the message names the column and both dtypes, so a floatvolumeor anobjectdirectionno longer passes. A custom loader must return the canonical dtypes. LOBSTER'sraw_event_typeis nowobject, as the map says. The side, action and order-type category lists are written only inschemas.py. -
A loader knows its own feed format (#348).
PipelineConfigno longer hasprice_divisorortimestamp_unit, and refuses an unknown field rather than dropping it. LOBSTER's ten-thousandths of a dollar (lobster.LOBSTER_PRICE_DIVISOR), Databento's fixed-point scale and Bitstamp's millisecond epochs are constants of their loaders and writers. A saved run whose config records either field still loads. A LOBSTER or Databento loader or trade reader takes the grid fields its config does not set from that source's grid, a cent tick and whole shares, as a pipeline run does; a writer built with no config uses that grid. ALobsterWriterrefuses a tick that is not a whole number of ten-thousandths of a dollar. -
The source factories take the run's loader (#348).
OfflineSource.create_trade_source(config, ctx, loader)andcompute_depth(events, config, source, ctx, loader)are handed the loader that read the run's events. A plug-in source adds the parameter. -
A price-level (L2) run's gallery has the book snapshot and depth chart (#344). They were skipped as per-order faces. Their L2 faces now read the depth table, so
build_gallery_modelandavailable_conceptsincludebook_snapshotanddepth_chartat L2 for every L2 source. -
The L3 book snapshot and depth chart are cut as the L2 face is (#344). The L3 face showed only the orders within 150 bps of each side's best price, then the 40 price levels nearest the touch. It now shows the 40 price levels nearest the touch, as the L2 face does, so the two faces of one concept cover the same levels. On a thin book or a coarse tick the L3 face can now reach further than 150 bps.
-
Every time window starts from the Unix epoch (#350).
order_flow_imbalanceandcompute_kyle_lambdacounted their windows from the start of the first day, while time bars andofi_by_horizoncounted from the epoch, so a window that does not divide a day cut different windows: on the bundled sample,"7s"gave 92 OFI rows against 94 bars. Both are now built onbars(trades, "time", window), and_utils.fixed_windowand_utils.window_startare the one place a window is read and cut.amihud,roll_spread, the transaction-cost plot data, the clock bar rule andofi_by_horizonuse the same helpers. Windows that divide a day ("30s","1min","5min") give the same values as before. At"7s"on the bundled sample, OFI has 94 rows and Kyle's λ moves from 1.0007e-05 to 1.0746e-05. Also: order_flow_imbalancenow needs apricecolumn.- A window whose trades all have size zero is kept, with
ofiNaN; it was dropped. "1W"is 7 days counted from the epoch, not a calendar week. A calendar step such as"1ME", or a bare number (pandas reads5as 5 ns), raisesConfigErrornaming the function.- Windows are cut in UTC, so a frame in a local time zone, or a daylight-saving change, gives the same windows as in UTC.
amihud'sfirst_price/last_priceand the OFI metric'slast_pricestayint64ticks; they turnedfloat64when a window had no trades.-
Trade event ids are nullable
Int64(#351).maker_event_id,taker_event_id,maker_ogandtaker_ogwereint64,float64orobjectdepending on the reader, and a column with a gap could be saved asdouble. They are nowInt64everywhere and are saved as Arrowint64with a null mask.makerandtakerstayobject, because an order id can be text (Independent Reserve uses UUIDs). No value changed. -
Pipeline.runreads a capture's tick and lot size (#346). Given a capture folder or a file in one,Pipeline.runandPipeline.run_windowsuse thetick_sizeandlot_sizein itsmeta.jsonwhen the config does not set them. SoPipeline.from_source("depth_csv").run(capture)andob-analytics process capture --source depth_csvgive the same result; the first used to raiseConfigErroron a capture with a 0.001 tick. A tick size or lot size you set still wins, and a pipeline given its own loader or trade source does not use the record. - The
recorded_*readers inob_analytics.depth_l2are gone (#346). This can break code that imports them. Useob_analytics.capture_record.read_record(path)and its fields instead:recorded_tick_size(p)isread_record(p).tick_size,recorded_sequence_kind(p)isread_record(p).sequence_kind, and so on forsource,feed_type,trade_attribution,clocksandsequence_restarts. A declaration with a value this version does not know is now left out with a warning, where the old readers raisedValueError. -
Bar
turnoveris a float (#346). It was the integer product of ticks and lots on a pipeline result. -
The quote helpers in
trade_signchanged (#345). This can break code that called them directly: prevailing_midis the mid at an instant, the instant included, from the readable quotes only. Itsallow_exactandskip_crossedsettings are gone. For the mid a trade arrived into, use the newmid_before(rows, quotes); for the row position of that quote,quote_before(rows, quotes).readable_quotesmoved fromob_analytics.featurestoob_analytics.depth.classify_trade_signandresolve_directionreturn the orderedbuy/sellcategorical of the trades schema.-
resolve_directiontakesfallback="tick"(the default) orfallback=None, which leaves the unlabelled trades empty when there are no quotes. -
A plot drawn on your own axes leaves your figure's layout alone (#120). With
ax=, a matplotlib face used to calltight_layout()on the figure that holds the axes. That moved panels you had placed, and warned when the figure held axestight_layoutcannot place, such as a gridspec strip or a colorbar. A face now lays out only a figure it creates. If you draw panels withax=, callfig.tight_layout()yourself once every panel is drawn. On your axes, thecancellationscolorbar now shares your gridspec, so yourtight_layout()can place it. -
A metric is computed when its plot is drawn (#118). Building the gallery model,
available_conceptsandresult.plotof another concept no longer run every registered metric. A metric that raises now keeps its gallery card, which says why it has no plot, instead of being left out. -
A plot concept is level-less or drawn at a level, on every backend (#302). Registering a concept at
Nonewhen it is registered at a level on any backend, or the reverse, raises aValueErrorthat says which to use. So does a renderer key that is not(concept, level, backend).RENDERERS.placements(concept)lists how a concept is registered. This can break code that worked before: - Code that registered one plot both ways fails at the second registration.
- A metric plug-in that does so is skipped when
ob_analyticsis imported, with a logged warning. - A backend module loaded with
register_plot_backendthat registers a built-in concept as the other kind fails to load, so no plot on that backend draws until it is fixed. - A metric named like a built-in plot drawn at a level, such as
trade_size, cannot register its level-less renderer; give it another name. - A built-in renderer is registered by its coordinate, not its name
(#510). Each renderer in the matplotlib, Plotly and Bokeh modules now
carries a decorator that names its
(concept, level). The concept table no longer stores a renderer name, and no code builds a function name from a concept or a level. A renderer the table names and no backend registers now fails a test instead of failing when its backend is imported. Plug-in plots and backends still register withRENDERERS.register; nothing changes for them. - Renderers only draw what the payload holds (#501). Each number a
renderer used to work out is now in the face's payload, built once in
visualization/_data.py, so the matplotlib, Plotly and Bokeh pictures of one payload agree. A test checks that every backend of a face reads the same payload keys. - Depth heatmap:
color_limits(the volume range of the colours, used by every backend) andprice_ticks(fromprice_by, now drawn by Plotly and Bokeh too). - Order activity:
price_ticksat both levels, now drawn by Plotly too. At L2 each change has amarker_area, one size rule for every backend; Plotly sized dots from the raw volume, so its dots changed size. - Cancellations: both backends draw one grid of counts (
age_edges,distance_edges,bid_counts,ask_counts,counts,count_range), 30 by 30 cells on log axes, set by the newbinsargument. Matplotlib drew hexagons; it now draws the same square cells as Plotly. - Events histogram: both backends draw the payload's
edges,bid_countsandask_counts. Matplotlib's bins changed to the ones Plotly drew. - Kyle's lambda: the fitted line is the payload's
fit_line. - Book snapshot:
bar_thickness, which Plotly now uses too. Book replay:size_max. - Queue position:
ends, the last row of each filled and each cancelled order. Plotly now draws the end marks and the rank range (show_markers,max_rank), as matplotlib does. - Order activity at L3: Plotly now draws the end marks (
show_markers). - Volume percentiles: Plotly now draws the band edges only when
perc_lineis on. - Bars:
volume_top, the top of the volume axis. - Iceberg overlay:
iceberg_chains, one chain per iceberg with its side and opacity. - Liquidity at the touch: Plotly draws the event rug at fixed heights at the bottom of the chart, as matplotlib does, not below zero.
- The capture directory layout (#150). A capture's files are now in
seg-0001/,seg-0002/, ... under--out, next tomanifest.json. Read one segment as before, from itsorders.csvordepth.csv; giveprocessandauditthe capture directory to read them all.--outmust be new, empty, or a capture of the same venue and pair. - Live sources no longer reconnect by themselves (#150). The Bitstamp
source reconnected without a new snapshot, so an order deleted while it was
disconnected stayed on the book to the end of the run, and only a
reconnectscount (now removed) recorded it. The ccxt source stopped its book or trade loop on a network error and ran on with half its feed. Both now end the stream with the error, and the capture starts a new segment. -
manifest.jsoncounts resyncs, not missing sequence numbers (#309). Each segment, and the capture as a whole, recordsbook_resyncsin place ofsequence_missing, andauditwarns about them in a newbook_resyncscheck.droppednow counts only the messages a source could not use.recorded_sequence_kindreturnsNonewhen a capture records no kind, asrecorded_feed_typedoes, in place of taking adefault. -
The price-level depth follows an order that moves or grows.
price_level_volumeused to count every one of an order's rows on the price of its first row, and ignored a rise in its size. It now reads achangedrow that reports no execution and carries a new price as a move: the order's volume leaves the old level and joins the new one. Achangedrow that reports no execution and a larger size adds the difference where the order rests. Deletes and rows that report an execution are still taken off where the order rests, whatever price they carry, so the fix for Bitstamp's deletes at the wrong price is kept. The price-level rebuild now agrees with the per-order rebuild (book_state) on these orders. This matters for Databento, whose modify can move an order or make it bigger. The Bitstamp and LOBSTER outputs are unchanged: neither feed moves or grows an order this way. -
A trade the venue left unlabelled is now classified on the L3 path too.
Pipeline.runlabels any trade with no aggressor side against the reconstructed quotes, filling one subset at a time instead of all or nothing, and never overwriting a side the venue did state. This was already what the price-level path did; it now also covers a per-order feed that states the aggressor on most trades but not all, which is what Databento does for auctions, non-displayed orders and off-exchange prints. No change for a feed that labels every trade, which is every other source in the package. -
depth.bin_volume_columns()is public. It returns the per-bps depth-bin volume columns a depth summary carries, ordered from the touch outward, and it was already the answerbook_imbalanceanddepth_signalsneeded. The feature table needs the same answer, and so does anyone writing a depth feature of their own, so it is no longer private. Behaviour is unchanged. -
trade_sign.resolve_direction()now makes the guarantee its docstring already claimed: thedirectioncolumn it returns holds only"buy"and"sell". A native column was previously passed back untouched however it was filled, and every consumer reads it as== "buy"and takes the rest as a sell — so a partly-labelled feed did not lose its unlabelled trades, it counted them on the wrong side.compute_vpin,order_flow_imbalance,barsand the cost metrics were all affected. Rows that are neither side are now inferred the same way a wholly unlabelled feed is, with a warning saying how many. A feed that labels every trade is passed through unchanged.compute_kyle_lambdareaches the same guarantee: it still requires adirectioncolumn rather than inferring one, but a column being present no longer means every row in it is trusted. -
trade_sign.prevailing_mid()is now public, and takesallow_exact,skip_crossed,mid_columnandrequire_covered— the last quote strictly before an instant, crossed books skipped, a named reference column such asmicro_price, andNaNrather than the final quote reused once the quotes stop reaching. All four default to the previous behaviour, soclassify_trade_signis unchanged. An empty quote frame now returns allNaNinstead of raising a pandasMergeError. -
Sizes are integer lots plus a
lot_size, not floats (issue #226). Breaking: the on-disk schema goes 3.0 → 4.0. Everyvolumeandfillcolumn is now a whole number of lots (int64) instead of adoublein the base asset. The base-asset size islots * lot_size, wherelot_sizeis the instrument's minimum size increment (PipelineConfig.lot_size, default1e-8; LOBSTER sets1, whole shares). This is the size half of the integer-tick decision (issue #155) and it fixes a real defect rather than only re-expressing the data.
A price level is a running sum of adds, cancels and fills. A float sum does
not return to exactly zero when the last order leaves, so a level landed on
residue such as 5.55e-17, stayed live, and was reported as the best bid or
ask ahead of the real one. On the bundled Bitstamp sample that corrupted the
reported best bid on 25,611 of 313,565 rows (8.2%) and the best ask on 30,096
(9.6%) — the spread on about one row in eleven. Integer lots cancel exactly,
so a level empties or it does not, and those counts are now zero.
It was found by the new cross-check against hftbacktest (issue #224), and
that is what confirms the fix: replaying an exported session through
hftbacktest's own L3 reconstruction now agrees with depth_summary on the
best bid and ask for every row across five synthetic seeds, and Nautilus'
book agrees too. Before the fix the two disagreed on up to 78 rows a seed.
The change reaches every size-valued column — depth_summary's per-bin
volumes, placed_vol and filled_vol, the book snapshot's liquidity, and
the queue's ahead_volume and remaining — so their sums are exact as well.
Three float-era workarounds went with it: the Kahan compensation behind
filled_vol, the simulator's _vol_eps exhaustion tolerance, and the
LOBSTER book replay's 1e-12 level cutoff. Loaders convert on the way in;
the plots and the round-trip and export writers convert back, so what a user
sees and what another tool reads are unchanged. lot_size travels in each
Parquet file's key-value metadata under ob_analytics_lot_size, next to
ob_analytics_tick_size, and load_data surfaces it as
df.attrs["lot_size"]. Files written at 1.0–3.0 still read, as the
float-size frames they are. Golden outputs were re-baselined on purpose.
-
The export writers leave out orders that never rested (issue #224). A marketable order is recorded as a transient add on its own side at the touch, then the fill, then a delete;
ob_analytics.depthhas always excluded these from the book, but the hftbacktest and Nautilus writers were sending them. A backtesting engine reads an add as real liquidity, so its book crossed at the touch and dropped the resting level the order traded against — its reconstruction drifted permanently thinner than ours. Both writers now exclude them, which is what makes the two books agree. -
The order-book engine is its own module (issue #136). The rebuild (
order_book), the per-order lifecycles, and the FIFO queue reconstruction moved out ofanalytics.py/queue.pyintoob_analytics/engine/, behind one input and one output: order events in, book states and order lifecycles out, and nothing else. The engine imports no pandas — everything crosses its interface as NumPy arrays, with the shared schema (issue #112) as the input, timestamps as int64 UTC nanoseconds (issue #154) and prices as integer ticks (issue #155). Results carry a row index back into the caller's event arrays instead of copying columns out, so adding a column to the schema does not widen the interface and the engine never learns a vocabulary — order types, venue names — belonging to the layer above.ob_analytics/_engine_frames.pyis the one place pandas and the engine meet;analytics.order_book,analytics.order_lifecycles, and theob_analytics.queuefunctions are now its frame adapters and keep their exact signatures, dtypes, column order, and index behaviour. Output is unchanged byte for byte — the golden-output gates from issue #143 pass on their recorded fingerprints. Two things did move: the display window (max_levels,bps_range) and the queue sampling window are set by the frame adapters rather than the engine, which reconstructs the whole book and replays to the instants it is given. A new import test (tests/test_engine_boundary.py) keeps the engine free of pandas and of every layer above it. This is what lets the inside be replaced with a faster implementation (#138) or fed one event at a time (#139) without touching anything else.Direction,Action, andOutcomeareIntEnumcode vocabularies that derive their schema strings from their own member names, so a code and its label cannot drift apart. Two details of the frame code are reproduced deliberately rather than rewritten: an order's executed total is accumulated with compensated (Kahan) summation, as the pandas aggregation it replaced did, and placement values are taken per column as the first non-null among an order'screatedrows. The lifecycle table is now covered bytests/test_golden_synth.py, which it was not before. -
order_book,order_lifecyclesandqueue_positionsare exported from the package root (#498):from ob_analytics import order_book, order_lifecycles, queue_positions. This reverses part of #414, which left them inob_analytics.bookandob_analytics.queueonly. They are still there too. -
BitstampTradeReaderno longer requires integer order ids. It keyed its maker/taker lookup onint(order_id), which crashed on a public trade tape carrying no ids (int(NaN)) and on venues publishing UUIDs. Integer ids behave exactly as before; other ids match on their string form, and a missing id resolves toNaNinstead of raising. -
One
Sourceshape for every data source, file or live (issue #137; settled #145 as "optional extras plus entry-point plug-ins"). File loaders and live capturers were two separate designs with two registries; they are now oneSourceprotocol with two capability refinements —OfflineSource(replay stored files: the loader / trade-source / writer / depth factories) andLiveSource(capture a venue:snapshot/stream/shutdown_synthetic_events). A source states itslevel(L2/L3) andfeed_type, carries typedsettings, and registers in the singleSOURCESregistry viaregister_source. A source can be both:BitstampSourcenow covers offline replay and live capture in one descriptor. This is a breaking API change with no back-compat shims:Format→OfflineSource;LiveCapturer→LiveSource;BitstampFormat/LobsterFormat/DepthCsvFormat→BitstampSource/LobsterSource/DepthCsvSource;CcxtCapturer→CcxtSource.Pipeline(format=...)→Pipeline(source=...);Pipeline.from_format→Pipeline.from_source.- The
FORMATS/CAPTURERSregistries and theirregister_format/register_capturer/list_formats/list_capturers/get_capturerhelpers are replaced bySOURCES/register_source/list_sources/get_source(inob_analytics.sources). PipelineResult.resolution→PipelineResult.level(one coordinate name across the codebase;Source.level, matching the visualization layer).CaptureConfig.extras(the untyped settings dict) is removed. Per-source settings are now typedSourceSettingson the source itself, e.g.CcxtSource(settings=CcxtSettings(exchange="binance", depth_limit=100)).- CLI:
process/validatetake--source(was--format), and theformatsverb is nowsources(it also shows each source's capability and required context).
- Third-party sources load through entry points. A source can ship in its
own package and advertise itself under the
ob_analytics.sourcesentry-point group;ob_analytics.sources.load_source_plugins()discovers and registers it at import time, with no edit to ob-analytics. The built-in sources (bitstamp, lobster, depth_csv, ccxt) self-register on import and stay behind today's[live]/[ccxt]extras. - Prices are now integer ticks, not floats (issue #155). Every
pricecolumn — events, trades, depth, depth_summary, book snapshot, and order lifecycles — is a whole number of ticks (int64); the quote-currency price isticks * tick_size, wheretick_sizeis the instrument's minimum price increment (PipelineConfig.tick_size, default0.01). Loaders convert a raw price to ticks on load; the plots and the round-trip writers convert back for display, so figures and CSV output are unchanged. Storing the exact integer removes the float rounding that made small-tick and 0-1 instruments show crossed levels that were not real, and the depth engine now bins and compares levels on exact integers instead of multiplying and rounding each event — LOBSTER'sprice_divisoris now just the raw-feed encoding scale.tick_sizeis written to each Parquet file'sob_analytics_tick_sizekey-value metadata (a JSON map keyed by instrument, ready for per-(venue, symbol)ticks in #147) and surfaced onload_dataframes'attrs. Breaking: the dtype of everypricecolumn changed fromdoubletoint64and the stored numbers changed (prices re-expressed as ticks; price-valued analytics such astrade_impactsVWAP and Kyle's λ are now in tick units — multiply bytick_sizefor the quote currency; scale-free metrics such as bps depth and order-book imbalance are unchanged). The canonical Parquet schema version is now3.0(a1.0/2.0file still reads — Parquet is self-describing — as the float-price frame it stored, whose prices are not directly comparable to a3.0file's ticks; re-save it to move it onto the tick model). Golden-output baselines were re-recorded behind the correctness gate (#143). - Timestamps are now tz-aware UTC nanoseconds (
timestamp[ns, tz=UTC]) on both clocks —timestamp(receive) andexchange_timestamp(matching engine) — across every table, loader, the synthetic generator, and the toy datasets (issue #154). Before, they were tz-naive and in each venue's native clock (millisecond-resolution UTC for Bitstamp, US/Eastern for LOBSTER), and frames from different venues were declared not comparable. Now every frame sits on one UTC clock, so cross-venue frames can be joined or concatenated directly. LOBSTER's seconds-after-midnight are converted to UTC from the session date and a venue time zone (RunContext(session_tz=...), defaultAmerica/New_York); Bitstamp / CCXT keep their wall-clock instants and only gain the zone and the nanosecond unit, so their values do not move. The schema also documents a same-instant total order —timestamp, thensequence, thenevent_id, theningest_seq(ob_analytics.schemas.time_order_keys), which the per-order reconstructions sort by. Breaking: the dtype of every timestamp column changed, so the canonical Parquet schema version is now2.0(a1.0file still reads — Parquet is self-describing — as the tz-naive frame it stored; re-save it to move it onto the UTC clock). Consumers that compared pipeline timestamps against tz-naivepandas.Timestamps must now use tz-aware (UTC) ones.
Removed¶
-
The
sortedcontainersdependency, three dev tools and three scripts (#415). Nothing importedsortedcontainers, and the dev group no longer installssafety,codecovorpytest-mock, which nothing ran.scripts/bitstamp_demo.pyandscripts/lobster_demo.pycopied thebitstamp-demoandlobster-demoCLI commands and had fallen behind them; runpython -m ob_analytics bitstamp-demofrom a clone instead.scripts/parse_bitstamp_log.shwrote a format that the Bitstamp loader now reads 10^8 times too large. The README and the docs home page share one hero image,docs/assets/hero-depth-heatmap.png, whichscripts/make_hero.pywrites. The unusedvolume_marker_areashelper inob_analytics.visualization._datais gone. -
The compiled-engine compare tests (#416).
tests/test_compare_backends.pywaited for a compiled depth engine behind a factory that no plan names, and always skipped. A faster engine, if one comes (#138), must pass the golden tests, which already fix the output. -
The pandas-vs-Polars compare tests (#390). Three tests in
tests/test_compare_backends.pywaited for a Polars analytics backend and always skipped. ADR 0002 keeps the public API on pandas and does not add Polars, so they could never run. The module docstring now describes only the compiled-engine gate. -
Source.config_defaults(),Pipeline.loader,Pipeline.trade_source,Pipeline.writerandLobsterWriter(price_divisor=...)(#348). A source's grid replacesconfig_defaults(). The pipeline builds a loader and trade source for each run, so it holds none; to read LOBSTER's trading halts, build aLobsterLoader, pass it asPipeline(loader=...)and read it after the run. For a writer, callsource.create_writer(result.config, ctx). -
scripts/collect_bitstamp_btcusd.py(#349). It failed on import since #137. Useob-analytics capture bitstamp; the error messages and documents that named the script now name the command. -
The "check" category for hidden trades (#343). It worked around the depth summary dropping crossed levels, which is fixed.
prepare.hidden_liquidity_overlayno longer takesevents(call it ashidden_liquidity_overlay(icebergs, slices, hidden)), its output loses thecategorycolumn, andPalettelosescheck_trade. -
analytics.uncross_book_sides(#342). It uncrossed a book a second way and broke a tie at one price differently fromorder_book(..., uncross=True), so the book snapshot and the book replay could show different books for one instant.prepare.book_snapshotloses itsuncrossoption with it: it draws the book it is given, so pass itorder_book(..., uncross=True)for an uncrossed ladder or depth chart. order_book(min_bid=, max_ask=)(#342). Neither setting was ever applied. Usebps_rangeormax_levels, or filter the returned frames.
Fixed¶
maker_resting_timesraisesConfigErroron an events table with no rows (#579).- The Bokeh heatmap legend on bokeh 3.4 and before (#597). Moved below the plot, the legend also stayed over the data. It is now taken out of the plot area first.
- A saved run that holds the order type
flashed-limitloads with the current name (#584).load_data,load_resultand thescanfunctions convert it tocancelled-limit, with a warning, and give the column the dtype a current run has. A type this version does not know is kept, with a warning. - Plotly and Bokeh plots read better (#585). Plotly figures show prices
and sizes without SI prefixes (
78,432.5, not78.4k), and a legend no longer covers a colour bar, the toolbar or an axis on the right. The Plotly cancellations plot uses a log colour scale, so cells other than the densest one show. The Plotly book replay's slider labels no longer overlap. The Plotly liquidity-at-the-touch plot names its event marks in the legend, and its bid line shows under the ask line. The Plotly trade-imbalance price line is dark enough to read on a white background. The Bokeh depth heatmap has its legend outside the data and draws levels under one unit faint, as the other backends do. - The L3 book snapshot and depth chart leave out crossed orders (#585) on
the wrong side of the touch, in the gallery and in
plot_result. The gallery card says how many. grid_of(CryptofeedSource())no longer raisesTypeError(#578).- A US-equity day with orders under $1 loads on the default Databento
tick (#558). A US equity may quote under $1.00 in steps of $0.0001, so on
2026-11-10 AAPL on Nasdaq held six bids at $0.0001. Since #500,
DatabentoLoaderrefused the whole day on its default cent tick; before #500, it rounded these bids to $0.00 with no warning. An order that enters the book under $1.00 at a price on the $0.0001 grid but off the tick grid is now set aside: every record of it is left out until the next clear, and oneUserWarninggives the number of orders and records and namesPipelineConfig(tick_size=0.0001, price_decimals=4), which keeps them.DatabentoLoader.set_aside_ordersholds the count. An order already on the book that moves to such a price raisesConfigErrorand names the same setting. Every other off-grid book price is still refused. Only the Databento loader does this; the other loaders are unchanged. - The audit reports the orders set aside under $1 (#562). The count
was only in a warning while the file loaded and on the loader. It is now
on
events.attrsunderSET_ASIDE_ORDERS_ATTR("set_aside_orders"), saved with the run and read back, and reported bydata_quality_summaryasset_aside_ordersand byauditas theset_aside_orderswarning, which namesPipelineConfig(tick_size=0.0001, price_decimals=4). A source that cannot set orders aside reports the check as not checked. - Coinbase trade sides stay the taker's with ccxt 4.5.93 (#560). ccxt
4.5.93 reverses Coinbase's maker side to the taker's itself, so the ccxt
source's own reversal would have turned it back to the maker's. The source
no longer reverses it, and the
ccxtextra now needs ccxt 4.5.93.meta.jsonstill recordstrade_side_reversedfor a Coinbase capture. - The matplotlib queue-position face draws in about 1 s, not 25 s (#539). It drew one line for each order. It now draws one line collection for each fate, with one path for each order. The paths keep the line caps and joins of the old lines, so the picture is the same, pixel for pixel.
- The Plotly bars card titles its volume axis "Volume" (#504). It was titled "Price", like the price axis.
- The Plotly bars card colours a flat bar as rising (#543). Plotly
coloured a bar that closes where it opened by the close before it, so it
could be drawn in the sell colour. Each candle now takes its colour from
close >= open, as on the matplotlib card. The legend names the colours as the matplotlib legend does: "close up / net buying" and "close down / net selling". - The order flow imbalance and VPIN cards count taker orders (#532).
On an L3 feed, one taker order that fills many resting orders makes many
trades, so a window could pass the 10-trade floor with one order in it.
order_flow_imbalance,vpinandbulk_volume_classificationnow add ann_takerscolumn next ton_tradeswhen the trades have taker ids. It counts the distinct taker orders; a trade with no taker id counts as one. The cards applyMIN_TRADESton_takerswhen it is there and ton_tradeswhen it is not, and say which they counted. L2 tables are unchanged. On the bundled sample, the imbalance card now keeps 4 of 30 one-minute windows, down from 10. - Five gallery cards are readable on a short capture (#497). On the bundled sample, these cards showed little or nothing true.
- Book signals: an empty side of the book has a price of 0, and the price axis started there. The axis and the spread now use only quotes that can be read as a price, so the mid and the micro-price sit inside the axis.
- Roll spread and Amihud: each measures the whole session by default, so each has one value. The card now shows that value as a number, not as a point on a time axis. With no value, the card says "No value".
- VPIN: the gallery fits about 100 buckets to the capture. On the sample a bucket holds about three trades, nearly always on one side, so VPIN sat near 1. When the median bucket holds fewer than 10 trades, the card now says "Too few trades to draw" in place of the chart.
- Order flow imbalance: a window with fewer than 10 trades is left out, and the card says how many were. When no window holds 10 trades, the card says "Too few trades to draw".
vpin,order_flow_imbalanceandbulk_volume_classificationreturn a new column,n_trades: the number of trades in each bucket or window.prepare.vpinandprepare.order_flow_imbalancetakemin_trades(default 10), and so doresult.plot("vpin")andresult.plot("order_flow_imbalance").- Every L2 face draws on an L2 run (#492). Each face declares the data it
needs in a new
Needs: the tables that must have rows, the tables it reads when they have rows, and whether the events must be classified or carry a given column.available_conceptschecks a result against these needs, so it no longer builds the gallery model. A gallery card for a face the run cannot draw now says what the face needs, where before the card was left out with no reason. A run shorter than a minute keeps its whole depth summary, so the depth-summary faces draw on it. - The Plotly gallery of the bundled sample is 28 MiB, not 231 MiB (#491).
Each line carried every row of
depth_summary, sobook_signals.htmlalone was 82 MiB. The data functions now thin a long series to 1,000 time steps. Each step keeps its first, last, lowest and highest value, so every spike is still drawn. Matplotlib gets the same rows. Passtime_bins=Noneto apreparefunction to keep every row. - The Plotly depth heatmap draws its levels as one image, not one marker per row (32 MiB to 0.3 MiB). Its cells no longer show the volume on hover.
- The L2 order event map keeps one event per spot of the screen, the largest (19 MiB to 3 MiB). The liquidity rug keeps one tick per time step. The Plotly events histogram sends counts, not every event.
- A gallery card says when its plot shows thinned data, and how many rows it shows.
-
A test builds the Plotly gallery of the sample and fails when a page is larger than its size budget.
-
A failed rollback no longer hides the first error (#524).
save_dataandrun_windowsmove their files into place all or none. When a move fails, they put back the files already moved. Before, if putting back one file also failed, that new error replaced the first one, and the files after it were not put back. Now every file is put back that can be, and the first error is raised. It carries a note for each file that could not be put back, with the path of its backup. An interrupt such as Ctrl-C during the moves now puts the files back too. A backup that cannot be removed after every file is in place now gives a warning instead of an error. The backup of a replaced file is now a hidden.<name>.bakfile beside it, or.<name>.<n>.bakwhen that name is taken. Before,save_datakept it in a temporary folder that it deleted on exit. - Three more Plotly pages of the sample are under 2.5 MiB (#533). They sent every point to the page.
- The L2 cancellations map keeps the largest order of each side on each spot of the screen (6.7 MiB to 0.9 MiB). On a log volume axis, the spots are cut on the log of the volume.
- The order outcome plot keeps the largest order of each outcome on each spot of the screen (5.3 MiB to 0.1 MiB). Many orders had the same distance and size. Where they were stacked, the faded points looked darker. The plot no longer shows how many orders are stacked on a spot.
- The queue position plot keeps each order's lowest, highest and last rank in each of 1,000 time steps (3.4 MiB to 1.9 MiB). Most orders at the touch had two rows on the same spot, so the plot looks the same.
- Pass
time_bins=Nonetoprepare.cancellationsorprepare.queue_position, orbins=Nonetoprepare.order_outcome, to keep every row. - A settings flag works before the path (#523).
processandauditread the arguments twice. The first read finds the source that reads the data, and it did not know the settings flags. So when a settings flag came before the path and--sourcewas not given, its value was read as the path:ob-analytics process --instrument-id 42 capture/looked for a capture named42. The first read now knows the settings flags of every registered offline source and skips each flag with its value. An on/off flag takes no value. The second read still refuses a flag that the reading source does not have. - Every loader refuses an order price between two ticks (#500). Only the
price-level CSV loader checked prices. The Bitstamp, LOBSTER and Databento
loaders rounded a price to the nearest tick and gave no warning, so on the
default 0.01 grid 0.036 became 0.04 and landed on another level. Every
loader now converts prices and sizes through one function,
_utils.to_grid. A price that is not a whole number of ticks raisesConfigError, which names the column, gives an example value and gives the tick size. A value within float error of a whole tick still passes. A size between two lots is rounded with aUserWarning, as the price-level CSV loader already did. It is not refused, because a capture records a lot size no finer than1e-8: a venue that quotes finer sizes would give a capture that cannot be read. Bitstamp's 8-decimal sizes and LOBSTER's and Databento's whole sizes are on their default lot grids, so they do not warn. Only prices of book levels are checked: an order's price, and every price in the LOBSTER orderbook file. An execution can print between two ticks (a hidden order filled at the midpoint, as in LOBSTER's type 5 rows, or a Bitstamp or Databento trade), so execution prices are rounded to the nearest tick as before. A LOBSTER halt's price is a code and a Databento clear's price is never read, so they are not checked either. - Bitstamp and cryptofeed captures record their tick and lot size (#500).
Neither feed gives a tick or lot size, so these captures wrote none to
meta.json, and the replay used the default grid of 0.01 and1e-8. A cryptofeed L3 capture is read by the Bitstamp loader, so a venue with a finer tick was rounded to cents. Each capture now starts from the default grid and makes each step ten times finer until every price and size it writes sits on it, as a ccxt capture does. It recordstick_size,lot_size,tick_size_changesandlot_size_changes. A capture made before this change has no such fields and still loads on the default grid. If that capture has a price finer than a cent, it is now refused instead of rounded: pass the real tick, e.g.PipelineConfig(tick_size=0.001, price_decimals=3). queue_positionsno longer scans every live level per event (#489). To find the touch, the engine tookmaxorminover all non-empty price levels of a side for every event. On a real capture in time order thousands of levels are live, soqueue_positions(result.events)took about 9 s on the bundled sample. The live levels now sit in a heap, and the same call takes about 0.65 s on the same desktop. The output is unchanged, byte for byte.queue_age_griduses the same heap.queue_positionsno longer walks a long queue to find an order's rank (#520). For each event, the engine counted the orders ahead of the order and added up their sizes, one by one. On the synthetic session a queue holds about 620 orders on average, so this was most of the stage's time. A level with 32 or more orders now keeps two Fenwick trees (binary indexed trees) over its orders in arrival order: one counts the orders, one sums their sizes. The rank and the volume ahead are then a short sum, not a walk. The synthetic queue stage inscripts/bench_scale.pywent from about 2.7 s to 0.9 s on one desktop. The bundled sample's queues are short, so the trees rarely help there, and the extra upkeep makes it up to a tenth slower. The output is unchanged, byte for byte. The trees need exact sums, so they are used only for integer sizes, as a canonical stream has. Float sizes are still added one by one.- The speed test times
queue_positionsas a user calls it (#489).scripts/bench_scale.pypassed the events to the engine in the order the Bitstamp loader leaves them, by order id, where few levels are live at once. It understated the stage about ten times. It now calls the publicob_analytics.queue.queue_positions, which sorts the events into time order first. - The speed baseline is recorded again after the queue fixes (#521).
bench-baseline.jsonand the stage timings on the Architecture page come from a new run on the CI runner, after #489 and #520. On the sample,queue_positionstakes 1.01 s, 7% of a run. Before the two fixes, the same call took about 9 s on one desktop, about 40% of a run, not the 6% the old table gave. Runner speed varies from run to run, so the baseline comes from a run of typical speed: the check fails a stage at twice its baseline, and a baseline from a fast runner would fail on a slow one. - The speed check allows for the runner's speed (#536).
scripts/bench_scale.pytimed each stage once and failed it at twice its baseline. GitHub runners differ in speed by up to about three times, so a slow-down of up to twice passed, and a baseline from a fast runner failed on a slow one. Now each stage is timed three times and keeps its fastest time. Each run also times a small fixed numpy and pandas workload, and a stage's seconds are scaled by it before they are compared. The margin is now one and a half times the baseline.bench-baseline.jsongains areference_secondsfield. A baseline without it still works, at the old margin of twice the baseline, until a new one is recorded on the runner. Thebenchjob takes about a minute longer. - No negative depth bins at low prices (#488). With the default
depth_bps=25anddepth_bins=20, a best price under about 100 ticks, as on every cent-priced prediction market, could give a negative size in the last depth bin. The bin boundaries went backwards when the window held fewer ticks than bins. Now they never go backwards: a bin left with no tick stays at zero, and a side's bins add up to its size in the window. The columns and their names do not change, and neither do the values when the window holds at least as many ticks as bins. A property test intests/test_depth_engine.pychecks best prices from 1 tick up. - A saved run keeps the loader's counts (#503). The Databento loader
counts the records the venue flagged after a gap (
F_MAYBE_BAD_BOOK), andauditwarns when there are any. Arun_windowsoutput lost the count, soob-analytics audit --from-parquetskipped the check. A normal saved run kept it only through pandas' own metadata. Now every Parquet file records its loader's counts as a JSON object under the new metadata keyob_analytics_loader_counts(schemas.LOADER_COUNTS_KEY), andload_dataandload_resultput them back on the frame'sattrs. A windowed run records the sum over its windows.to_arrow()records them too. The key is optional, so the schema version does not change, and older files still load. run_windowsmoves its files into place all or none (#503). It replaced the four output files one at a time, so a failed move left a folder with some new files and some old ones. It now uses the same step assave_data: each old file is kept until every new one is in place, and a failed move puts the folder back as it was. The old file is kept as a hard link where the file system allows, so a large output is not copied.- Docstrings carry no issue numbers (#421). Published docstrings,
#:attribute comments and thetick_size/price_decimalsfield descriptions named GitHub issues or plan labels, which mean nothing to a reader. A new test,tests/test_docstrings_no_issue_refs.py, fails on an issue number (#NNN) or a plan label (WS-n,Phase n, an audit label such asA7-1) in any string or#:comment underob_analytics/. The package docstring now lists every built-in source, andprepare.hidden_liquidity_overlaydocuments its four window parameters. - The
run_windowscaveat aboutaggressiveness_bpsis gone (#421). A windowed Bitstamp run gives the sameaggressiveness_bpsas a single run, andtests/test_run_windows_aggressiveness.pychecks it. Therun_windowsdocstring and the "Scale and chunking" page no longer say it can differ. - One text on adding a live venue (#421). "Capture live data" now links to
"The live capability" in "Extending ob-analytics", which holds the rules
for a
streamthat were only on the capture page. - The gallery asks a backend only for the plots it draws (#463). Without
Plotly installed,
ob-analytics process ... --gallerylogged a failure for the book replay, which only Plotly draws. Now that card says which backend draws the plot, and nothing is logged. A plot that fails to draw or save still logs a warning, and its card now gives the reason. - The gallery's VPIN card plots a short capture (#464). VPIN's default
bucket, a day's volume ÷ 50, filled one bucket on the bundled half-hour
sample, so the card showed one point and
compute_vpinwarned. The gallery now passesbucket_volume="fit", a newcompute_vpinsetting: when the default would fill fewer thann_bucketsbuckets, each bucket is the total volume ÷ (2 ×n_buckets). The card says when it did so.compute_vpin,result.metric("vpin")andresult.plot("vpin")keep the default and still warn when a bucket size fills too few buckets. - The Matplotlib
book_signalsplot no longer runs out of memory (#462). It drew the touch OBI strip as one bar per depth-summary row, about 313,000 bars on the bundled sample, and went past 3 GB. The strip is now two stepped fills, buy above zero and sell below, each reduced to the highest and lowest value in each of 4,000 time columns. On the sample the plot peaks at about 675 MiB, andob-analytics process ... --galleryfinishes under a 3 GB cap. - Data problems reach a Python user (#399). The package turns its loguru
logger off, so these went unseen; each is now a
UserWarning: Databento records dropped for no price or no side, Databento fills that do not account for all the printed trade volume, ordersset_order_typescannot classify, Bitstamp duplicate cancellations, a LOBSTER run with no orderbook file, and a Parquet file with no schema version. - Plot warnings reach a Python user (#510). Three plot warnings still went
to the logger the package turns off. Each is now a
UserWarning: a theme that a renderer cannot take, a hidden-liquidity overlay that fails and is left out of the gallery, and a book replay whose frame interval is widened to fitmax_frames. - A run with no trades offers no trade metric (#399).
available_conceptslisted VPIN, Kyle's λ, order flow imbalance and the cost metrics, which cannot be drawn, andresult.metrics()raised.result.metrics(), the gallery andplot_resultnow use one test of whether a metric applies (ob_analytics.metrics.skip_reason), andresult.plot("vpin")on such a run says that it needs trades. - The Bitstamp-format loader numbers events in time order (#456). It
numbered them by order id, so rows of two orders at one instant came in the
order their ids sort. Bitstamp's ids rise with time; Independent Reserve's
UUIDs do not, and the order of those rows then changed the rebuilt depth
and the icebergs found (the bundled sample with its ids
hashed lost one of its two icebergs). Rows of different orders at one
instant now follow the venue's
sequencewhen the file has one, then their file order. Each order's own rows are unchanged. detect_icebergsno longer stops on UUID order ids (#314). On an Independent Reserve capture, a refill madedetect_icebergsraiseValueError, and the gallery left out its hidden-liquidity overlay. The slices now keep each orderidas the feed writes it.detect_icebergsreads a result in display units (#510). On a result fromdisplay_result, whose sizes are floats, it raisedTypeErrorwhen it cast the slice sizes to integers. The gallery then left out its hidden-liquidity overlay without a word; the new plot warning showed it. Float sizes now stay floats.- The Bokeh depth heatmap draws the hidden-liquidity overlay (#410).
With
backend="bokeh", the iceberg chains and refill markers and the trades against hidden orders were left out without a word. Bokeh now draws them as Matplotlib and Plotly do. BitstampWriterkeeps a capture'soriginandsequencecolumns (#401). It wrote only the order columns, so a capture read, run and written again lost which part of the capture wrote each row, and the clock checks then counted the opening book's rows.DepthCsvWriterkeepssequencetoo, as it already keptorigin. The capture's file names and columns are now inob_analytics.capture_files, which the capture, the crash repair, the readers and both writers share.- A wheel holds only the package (#415). The wheel and sdist
includepatterns now start with/, so hatchling no longer packs anob_analyticsfolder found below the root, such as one in an agent worktree, and they leave out hidden files and__pycache__. A wheel built from a checkout with agent worktrees under.claude/held 45 MB of them;.claude/is now ignored by git too. CI fails when a wheel holds a file outsideob_analytics/and its metadata, or a hidden file or cache inside the package (scripts/check_wheel_contents.py). -
CI lints and type-checks
scripts/(#415), as the pre-committyhook now does too, and the scripts pass.build_gallery.py,build_tutorial.py,check_links.pyandsmoke_wheel.pyread their arguments withargparse, so--helpprints usage instead of running the script;build_gallery.pytakes--output. Ruff now checks for broadexcept Exception,except: passandexec(BLE001,S110,S102), so eachnoqacomment for those rules marks a reviewed case and a new one fails the lint. A registry'sincheck now catches only theTypeErrorof an unhashable key. -
Every reader refuses a bad file with
ConfigError(#418). The Bitstamp, LOBSTER,depth_csv, DBN and Parquet readers andread_manifestreturned a frame built from some bad files, or raised an error from pandas, pyarrow, databento orjson. Each now raisesConfigErrorwhen a file is not text, is not laid out as its format says, ends part way through a row or record, or has a required cell that is empty or holds something other than a number, a time, a side or an action where one belongs. Some of these the readers used to take: a LOBSTER row with an unknown event type was left out, a Bitstamp order with no time read asNaT, a trade side that was notbuyorsellread as unknown, and a DBN file cut inside a record gave the records before the cut. An empty side, venue time or Bitstamp trade order id is still allowed, and an emptytrades.csvreads as no trades. -
A Bitstamp order message that cannot be parsed ends the segment. The Bitstamp capture left such a message out and carried on with a book that no longer matched the venue's, as cryptofeed did before #398. A snapshot row or live order event it cannot parse, or one with an unknown
order_type, now raisesUnmappedMessageError, so the segment ends and the next one starts from a fresh snapshot. A trade it cannot parse is still left out and counted indropped.UnmappedMessageErrormoved toob_analytics.live, so a plug-in L3 source can raise it too. -
A segment that closes by itself after a second signal has no error. When a second Ctrl-C or SIGTERM arrived just as a segment was finishing on its own, the manifest still said a second signal had stopped it, and
capture_errorsfailed. A segment that is late to stop after the time limit is still recorded as such. -
Reading a
.dbn.zstfile closes it on Python 3.14 (#416). From 3.14 databento decompresses with the standard library, whose reader leaves the file it wraps open, soread_mbo_frameleaked one file handle per compressed file. It now closes the file itself. -
The gallery page is written as UTF-8 on every platform (#416). The page declares UTF-8, but it was written in the locale's encoding, so on Windows a non-ASCII title could show wrongly or fail to write.
-
Live capture reports what it lost, and stops on a second signal (#398).
- ccxt and cryptofeed counted lost messages as
errors, but the manifest andauditreaddropped, sodropped_messagespassed a capture that lost frames. cryptofeed now counts them indropped, as Bitstamp does. ccxt'serrorsonly counted the error that ends the stream, which is alreadycapture_error, so it is gone, and the runner no longer adds a stream error toerrors. audithas a newcapture_errorswarning for a segment that ended on an error or was slow to stop, and runsdropped_messagesandcapture_errorson a single capture from itsmeta.jsontoo.- A source whose
diagnostics()raises lost its counters with only a debug message. The capture now warns and recordsdiagnostics_errorinmeta.jsonand the manifest, anddropped_messagesfails, since the count is not known.auditalso warns, not only logs at debug level, when it cannot read the sequence kind a capture's source declares. - A cryptofeed source with no venue said L2 but declared an L3 feed type and trade attribution. All three now say L2 until the venue is known.
- An L3 cryptofeed message that cannot be mapped ends the segment, as in ccxt, so the next segment starts from a new opening book. Before, the message was left out and the capture went on with a wrong book.
-
A second SIGINT or SIGTERM stops a capture at once: a segment still closing is cancelled and closed from its files. Every file is closed even when one fails to flush (recorded as
capture_errorwith the phaseclose), andmeta.jsonis written last. The row counts inmeta.jsonalso survive a cancelled segment. -
A Databento file with records after an unrepaired gap warns, and
auditsays so. Databento marks the records after a gap it could not repair withF_MAYBE_BAD_BOOK. The loader counted them in a loguru message, which the package switches off, so a user never saw it andauditpassed the file. The loader now callswarnings.warn, keeps the count asDatabentoLoader.maybe_bad_book_recordsand on the events'attrs(underschemas.MAYBE_BAD_BOOK_ATTR), anddata_quality_summaryreports it asmaybe_bad_book_records, with a records after a gap line and amaybe_bad_bookwarning when it is above zero. A source whose feed has no such flag shows the check asnot checked(#389). -
"What each feed shows" says why Kraken book drift is not noticed (#391). Kraken sends a checksum of its book, but the checks in ccxt and cryptofeed are both off by default, and the package turns on neither. Kraken sends no sequence number, so the only sign of drift is a crossed book, which the
crossed_bookcheck reports. -
A source keeps nothing from a run, and
run(ctx=...)reaches the loader (#348).LobsterSourceandDatabentoSourcekept the last loader they built, and LOBSTER read its depth from that loader's orderbook file. With oneLobsterSource()serving two pipelines, a run near $100 came out with a best bid of 150.0, from the other run's file. The loader and trade source were built when the pipeline was, so atrading_date,symbolorvenuegiven torun(ctx=...)was dropped, and the LOBSTER how-to'sPipeline(source=LobsterSource()).run(path, ctx=ctx)raisedtrading_date is required. Both are now built for each run, from that run's context. ALobsterLoaderbuilt by hand read prices 10,000 times too large (100000000 ticks for $100.00); it now reads the prices and sizes a pipeline run reads. -
The L2 book snapshot and depth chart read the depth table (#344). Both faces of the gallery's
book_snapshotanddepth_chartwere built fromorder_book(events), the book rebuilt from the per-order events. The L2 face is now built from the depth table withprice_level_snapshots, as the L2 book replay already was, and only the L3 face reads the per-order book. On a LOBSTER file with few levels the per-order book keeps orders the file lost sight of and is crossed: on the 10-level AAPL sample of 21 June 2012 the L2 snapshot showed a best bid of 587.85 over a best ask of 582.39, and now shows 582.28 and 582.39, as the orderbook file does. On a diff feed such as Bitstamp, the L2 face now leaves out a stale crossed level, as the depth summary does. - A LOBSTER run warns when the book rebuilt from its message file is
crossed (#344). A message file holds only the events inside the requested
price levels, so an order cancelled or filled outside them keeps resting in
that book. When it is crossed for more than 0.05% of the session time,
LobsterSourcewarns withwarnings.warnand gives the share and the cause. The 10-level AAPL sample is crossed 99.2% of the time and warns; the 50-level sample is never crossed and does not. The depth table, read from the orderbook file, is not affected, so thecrossed_bookcheck ofauditdoes not count this crossing;auditreports it separately asper_order_crossed_pct. Without an orderbook file the depth table is rebuilt from the same messages, and the warning says so. The LOBSTER how-to and "What each feed shows" now state the limit: the per-order views are complete only when the requested levels cover every price an order reaches. - The matplotlib OFI horizon face no longer crashes (#349). Its time axis
came only from the filled bands, so a grid of zeros drew none and saving
failed with
RuntimeError: ... raster overflow; one non-zero value widened the axis to about four years. The axis now spans the grid's own times (one second each side when the grid has one step), and an all-missing grid shows the "no data" title. processandauditbuild their pipeline in one place (#349). The two copies had drifted:processprinted a literal%sinstead of the source name when--trading-datewas missing, andcaptureprinted%rinstead of the source name for an offline-only source. Both messages now name the source.-
A quote that cannot be read as a price gives no mid anywhere (#355).
depth.readable_quotesdecides when a quote can be read: both sides are above zero and the bid is not above the ask. Some readers still used their own test or none.micro_price, and so themicro_pricecolumn ofdepth_signals, gave0for a quote with an empty side, and themid_pricecolumn gave a mid halfway to zero. The price view and the book signals face drew those mids, and the trade tape hung its stems off them. Now each of these isNaN(no line is drawn) for a quote with an empty side or a crossed book, and the trade tape takes its mid from the nearest quote that can be read. A locked book (bid equal to ask) is still read. The imbalance columns are unchanged, since all the volume on one side is a true imbalance. The Level 1 quote table reads an empty side with the same test, and blanks only the empty side. On the bundled Bitstamp sample 16 of the 313,561 depth summary rows cannot be read; the transaction-cost numbers are unchanged. -
The Bitstamp-format loader puts an order's rows in time order (#354). It put the
createdrow first and the rest by size, largest first, which assumed an order's size only falls. Some captures in this format raise an order's size, so the rows came out of order and the fills were wrong: an order of 5 lots that fell to 3 and then rose to 8 showed its 8 before its 3. The loader now keeps thecreatedrow first and puts the rest in order bytimestamp. Rows that share an instant follow the file'ssequencecolumn when it has one; adeletedrow then goes last, and the rest keep their order in the file. A row with no sequence number, such as a fill a cryptofeed capture took from the trade tape, keeps its place after the row before it in the file.fillis still taken only from drops in size, so a rise hasfill0. The bundled Bitstamp sample gives the same events, trades,depthanddepth_summaryas before. -
The depth summary keeps crossed price levels (#343). When a new quote crossed a level on the other side,
PriceLevelBookdeleted that level for good, so the depth summary lost it for the rest of the run while the depth table kept it. It now keeps every level, as the depth table does, and leaves crossed levels out only of the touch it reports, by the rule oforder_book(..., uncross=True): the level updated less recently is left out until the newer quote leaves. A locked touch is uncrossed the same way.PriceLevelBook.quoted_bids()andquoted_asks()give the levels the touch is read from; the depth summary,price_level_snapshotsandLobsterWriterread them. On the bundled Bitstamp sample the summary's touch now matchesorder_book(uncross=True)at 299 of 300 sampled instants on each side (241 and 165 before), no row is locked (53,498 before),hidden_tradesflags 0 trades where it flagged 29 that all had a visible maker, and 48 trades have a negative effective spread (73 before). A matched book (LOBSTER, Databento) is never crossed and does not change.depth_metricsis also faster: 9.35 s against 11.44 s on the sample. -
The empty
eventsandtradestables have a loader's dtypes (#351). The emptyeventstable of an L2 run hadvolumeandfillasfloat64anddirection,actionandtypeasobject, sosave_datawrotedoublesize columns for every L2 run, andpd.concatof an L3 and an L2 run's events turned every L3 size into a float. The emptytradestable, which a trade reader returns for a capture with no trades, had every column asobject. Both now match the maps. - The Databento loader writes one row per kind of change (#353). A cancel
or modify that follows a fill and leaves the order resting can also take off
more than the fill, move the order, or make it bigger. The loader wrote that
as one
changedrow that was both an execution and a reduction, which the schema does not allow, so the depth took off only the fill and kept the rest on the level. On an order of 8,F 3thenC 5left 2 lots on the level after the order had gone. The loader now writes two rows for such a record: one with the fill and the size left after it, at the price where the order rests, then one with no fill and the record's own price and size. Both share the record'soriginal_number, and the trade names the first as its maker. The warning that a modify with a fill left the depth off is gone, since the depth now follows it. A cancel that takes off less than the fill charged to it, or a fill larger than the order had resting, is warned about; the book keeps the size the cancel or modify leaves, and an oversized fill is capped on the execution row. -
read_mbo_framecloses the DBN file it opens (#353). A store the caller opened is left open. Therun_windowsdocstring no longer mentions the removed warning. -
Every rebuild puts an order at one price (#342). An order rests at the price of its
createdrow, and after that only achangedrow with no fill moves it. The depth table followed this rule, but the per-order book (order_book) and the queue tables put an order at the price of its latest row. Bitstamp reports a taker's fill at the price it traded at, so an order that crossed and then rested showed at one price on the L2 faces and at another on the L3 faces. The rule is now worked out in one place,_engine_frames.resting_price, andorder_book,queue_positions,queue_age_grid,price_level_volume, the windowed run's carry andDatabentoWriterall read it. An id that is cancelled and placed again now rests at its new price in every rebuild; the depth table kept it at its first price. Achangedrow with no fill and a new price (a Databento modify) now moves the order to the back of its new queue inqueue_positionsandqueue_age_grid, as it already moved it in the depth table.queue_positionsreports the move as adeletedrow at the old price and acreatedrow at the new one.order_book,queue_positionsandqueue_age_gridnow need thefillcolumn, and the two queue functions also needtype: classify the events withset_order_typesfirst. -
The touch-queue faces leave market orders out (#342).
queue_age_gridandqueue_positionskept market orders, which never rest. A Bitstamp taker is created at its limit and fills at other prices, so the grid added it and never removed it. On the bundled sample one such order was theliquidity_at_touchL3 bid queue from 02:36 to the end: the grid's touch queue differed from the book at 184 of 200 bid samples and 173 of 200 ask samples. It now matches the book at every sample. On the synthetic golden session,queue_positionsloses the 251 rows of its 92 market orders and no other row changes. -
A saved run reloads with its own units (#346).
ob-analytics galleryandaudit --from-parquetrebuilt a saved run with the default lot size and price decimals, so a LOBSTER or Databento run (lot size 1) showed every size 10^8 times too small, and a 0.001 tick was rounded to the cent. They now useload_result. - The L2 loaders warn about a size between two lots (#346). Such a size is
rounded to the nearest lot, which is not the venue's size; the warning names
lot_size. - A large price or size on its grid is no longer read as off it (#346). The grid test allowed a fixed 1e-6 of a step, but dividing a large value by a small step misses a whole number by more: 1251.81488791 at a lot of 1e-8 is 125181488790.99998 lots. The allowance now grows with the number of steps.
- A size too large for
int64lots is refused (#346). Converting a size to lots wrapped a level above about 9.2e10 units (at the default lot of 1e-8) to a negative number, and the L2 loader then dropped the level. It now raisesConfigErrorthat nameslot_size. -
Bar turnover and VWAP, and
trade_impacts' VWAP, no longer wrap (#346). Price in ticks times size in lots passedint64on a busy day: four trades of 4,000 BTC at 78,000.00 gave a negative turnover and VWAP. They are computed as floats, asamihudalready was. -
Every Bitstamp trade finds its taker (#352). An instant order bought by quote amount is created with size 0 and then shows 0 or one lot, never what it bought. The trade reader matched a trade to a row only by its fill size, so these trades had no taker and their orders were classed
unknown. When no row shows the trade's size and the taker is an order created with size 0, the reader now takes that order'sdeletedrow, else its latest row. Every other trade is still matched on size only: an order with no row of the trade's size has lost a message, and the trade stays unmatched sounmatched_tradesreports it. On the bundled sample all 284 takers resolve (282 before), and orders 2002354918830080 and 2002351232385027 are classedmarket. As market orders they no longer rest in the price-level rebuild, sodepthanddepth_summarylose their 4 rows (313,565 to 313,561), including the one row whose best bid was a single lot from one of them. -
A trade is read against the quote it arrived into, everywhere (#345). Lee–Ready read the quote stamped at the trade's own instant. On a feed whose trades and book events share one clock (LOBSTER, Databento) that quote is the book after the trade took the touch, which pulls the mid toward the trade price and flips signs. With quotes 99/101, then 99/104 at the trade's instant, an unlabelled buy at 101 was labelled
sell, andtransaction_coststhen gave it an effective spread of -2.0. It is now abuyat +2.0. Lee–Ready,transaction_costs,hidden_trades,order_aggressivenessand the windowed run all use one rule,trade_sign.quote_before: the last quote strictly before the row, in event order. On a LOBSTER AAPL hour (30 levels), Lee–Ready now agrees with the feed's own side on 95.9% of trades, against 85.2%; on the bundled Bitstamp sample it is 72.9% against 73.2%. The pipeline's own tables do not change on the bundled Bitstamp sample or the synthetic session, where every trade is labelled by the venue. hidden_tradesreads the spread just before the maker's fill in event order (#345). It read the spread before the fill's whole instant, so a visible order placed or filled earlier in that instant was missed. On the LOBSTER AAPL day (10 levels) it now flags 11,304 of the 11,332 executions against hidden orders, against 9,645, still with none that is not one. On the bundled Bitstamp sample it flags 29 trades, against 41: the 12 it drops each had a visible maker placed at the trade price earlier in the same instant.- One test of a quote that can be read (#345).
prevailing_midand the effective spread kept a quote with an empty side, so a buy at the ask just after the bid side emptied cost 20,000 bps; it is now measured against the last quote with both sides.depth.readable_quotes(moved fromfeatures) is the one test: both sides above zero and the bid not above the ask.prevailing_mid,mid_before,hidden_trades, the feature table and the depth heatmap's spread line all use it. - The pipeline fills a missing trade direction by the same rule as the
metrics (#345). The pipeline and
resolve_directiondisagreed on which trades needed a direction (missing, against neitherbuynorsell) and on the dtype (ordered against unordered). The pipeline now callsresolve_direction(..., fallback=None), and both write the trades schema's orderedbuy/sellcategorical. A run with no quotes still leaves the unlabelled trades empty, now with aUserWarningrather than a log line. - LOBSTER depth is stamped with the right event after a cross trade or a
halt (#340). The orderbook file has a row for every message, type 6
(cross trade) and type 7 (halt) included, but the events keep only types 1
to 5.
lobster_depth_from_orderbookpaired the two by position, so after the first type 6 or 7 message every book state carried a later event's time andevent_id, and the last states were lost. Each event now reads the orderbook row of its own message, named byoriginal_number. ALobsterSourcerun raisesConfigErroron an orderbook file with more or fewer rows than the message file, where before it logged a warning a Python user never saw.lobster_depth_from_orderbookcalled on its own checks the count only when givenmessage_rows. - LOBSTER depth sizes are
int64lots (#340). Sizes read from the orderbook file werefloat64share counts, sodepth.volumeand every size column ofdepth_summarywere floats, against the schema, and with alot_sizeother than 1 they were in different units from the events. They are now converted withlot_size, as the message sizes are. LobsterWriterwrites the run's own book (#340). The writer rebuilt the orderbook file from the events with rules of its own that only fitted frames read from LOBSTER. On a frame from any other source it raisedTypeError(the missingraw_event_type), and without that column it wrote a book that differed from the run's depth. It now writes the book after each event from thedepthtable it is given, or fromprice_level_volumewhen there is none, throughPriceLevelBook, the book the depth summary is built on. Reading the files back gives the run's book after every event: the depth summary read back equals the run's, as far as the written levels reach. Both files are written in time order, and an empty level's dummy price is no longer multiplied by the price divisor. The writer refuses, withConfigError, a run with no events, repeatedevent_ids, events or depth in display units, and aprice_divisortoo coarse for the tick (with a cent tick, a divisor of 1 wrote 100.01 and 100.02 as the same price). Events with nodepthtable now need thetypecolumn thatset_order_typesadds, so events straight fromLobsterLoader.loadare refused: pass the run'sdepth, or runset_order_typesfirst. Prices are encoded as exact integers, and a writer built with no config uses LOBSTER's own grid (price_divisor=10_000, whole shares) instead of the general defaults.- One rule for a
deletedrow, and the loaders and writer that broke it (#341). The schema now says what adeletedrow holds when its order also traded:fillis the executed part,volumethe part removed without trading, and the two add up to what the order had resting. An order filled in full ends withvolume0. See "Volume and fill" in the schema page. - The Databento loader put the size in both columns, so an order filled in
full came off its price level twice and other orders at that price lost
their size from
depthanddepth_summary. Bids of 5 and 3 at 100.00, with the 5 filled, now leave 3 at 100.00, not 0. A cancel that asks to remove more than its order holds now removes only what the order holds. DatabentoWriteris now the inverse of that rule. Adeletedrow is aCfor everything the order had resting. It writes anFonly for a fill the order took while resting. An order that took liquidity when it arrived is written from when it rests, as anAfor the size it had left, or not at all if nothing was left. Pass"trades"with the events so the writer knows every fill an aggressor took; without them it knows only themarketorders' fills. A synthetic session written to DBN and read back now has the same trades and the same final book; before, every trade came back twice and filled orders stayed resting. A size that is not a whole number of units now raises aValueErrorinstead of being rounded.- The Bitstamp loader now puts each order's
createdrow first. It sorted an order's rows by size, so an instant order bought by quote amount, created with size 0, had itscreatedrow last and a phantom 1-lot fill. A rise in size is no longer read as a fill. price_level_volumekeepsint64sizes after a partial cancel. One LOBSTER type 2 or Databento partialCmade the wholedepth.volumecolumn, and thedepth_summarysizes,float64.price_level_volumeno longer hides a level the events overdraw. It clipped only the size it reported, so the level stayed short for the rest of the run: overdrawn by 5 and then given an order of 4, it read 0. It now holds the level's running total at zero, so the same level reads 4, and it warns with the level and the first event.auditcounts those rows asnegative_level(a warning). The bundled sample, the toy session and a synthetic session have none.- The book replay keeps its click script in a notebook (#121). IPython
displayed a
BookReplayFigurethrough Plotly's own renderer, which drops the script that makes trades clickable, and the tutorial build dropped the figure entirely. The figure now displays as HTML in a notebook, as documented. - Stale orders and crossing are measured correctly on display tables.
display_resultconverts sizes to base-asset floats.price_level_volumesummed those floats, and a level whose last order left could keep a remainder such as3e-17in place of0. The level then stayed in the faithful book. On the bundled sample, 22,915 depth rows kept a remainder.detect_stale_ordersreported atouch_secondsof0.0for the stale ask at 78,333, which holds the touch for 1,645.7 s, anddata_quality_summaryreported the book crossed 92.03% of the time against 91.61%.price_level_volumenow sums float sizes that sit on a decimal grid as whole multiples of that grid, the way it sums integer lots, so the display tables give the same results as the pipeline's own tables. Float sizes on no decimal grid, such as a size worked out by float subtraction, are still summed as floats, andprice_level_volumenow warns when it does that. - The price-level depth is replayed in event order.
price_level_volumeanddepth_metricssorted rows on the timestamp alone, so the rows of one instant were replayed bids first, then asks, by price, and adepth_summaryrow was not always the book after the event it names. On the bundled Bitstamp sample, for 44,043 of 156,719 new limit orders the last row before the order was replayed after it, so "the book before the order" already held the order. Both now use the order the per-order rebuild uses (schemas.time_order_keys: the timestamp, thensequence,event_idandingest_seqwhere present). Each level's running total is also taken in that order, so everydepthrow holds the level's volume after its own event, anddepthcarries thesequenceandingest_seqcolumns over from the events when they have them. The book replay (price_level_snapshots) uses the same order, so its touch still equals the depth summary's. On the sample, the book at the end of an instant changes at 2,634 of 130,244 instants (the best bid or ask at 2,453), because removing crossed levels depends on the order rows arrive in, andaggressiveness_bpschanges on 28,898 of 314,057 events. On a synthetic session, which is never crossed, every event's lastdepth_summaryrow now matches the per-order rebuild. aggressiveness_bpsis measured against the book at the order's own time.order_aggressivenessfound the book standing before each order by taking thedepth_summaryrow with the next-lowerevent_id. That is only correct when event ids are in time order. The Bitstamp loader numbers events after sorting them by order id, so on Bitstamp that row could come from any time in the session. On the bundled sample, 51,805 of 156,718 new orders were measured against a book from after the order, and 7,399 against a book more than a minute away, up to 30 minutes. The lookup now uses the documented event order (time_order_keys): the lastdepth_summaryrow with an earliertimestamp, or with the sametimestampand a lowerevent_id.aggressiveness_bpschanges on 45,087 of the sample's 314,057 event rows (14.4%). Databento, LOBSTER and the synthetic generator number events in time order, so their values do not change.compute_vpinrefuses a bucket size in the wrong units. Sizes are integer lots, sobucket_volume=5.0on the Bitstamp sample means 5e-8 BTC and asked for about 300 million buckets, enough to run the machine out of memory.compute_vpinandbulk_volume_classificationnow raiseValueErrorwhen a bucket would make more thanMAX_VOLUME_BUCKETS(one million) buckets, and say which unitsbucket_volumeis in. The how-to pages that passedbucket_volume=5.0now size the bucket from the trades.- Docs written before lots and UTC timestamps are corrected. The schema
page gives the current version,
4.0. The step-by-step and synthetic-data pages say timestamps are tz-aware UTC. Tutorial chapter 3's LOBSTER round trip now passeslot_size=1.0; without it every size was written as a fraction of a lot, and the round trip read back no executed volume. - The tutorial pages show no warnings (#120). Chapter 3 now reads its LOBSTER files back with the toy's tick size. With LOBSTER's one-cent default, $99 came back as 9900 ticks against the original 99, so the books before and after the round trip did not match. An empty book snapshot no longer draws an empty legend. The docs build now fails when a tutorial cell prints a warning or a figure fails to draw, and when a gallery recipe raises a warning.
- An Independent Reserve capture no longer keeps orders cancelled before
it started (#315). cryptofeed takes the opening book from the venue's REST
interface when the first stream message arrives. The venue serves that book
from a cache, and its orders are older than its
CreatedTimestampUtc, so the book could be a few seconds older than the stream. An order cancelled in between stayed in the book until the capture ended, and a trade at a price past it made the book crossed: 13 orders in a 12-minute capture, two of them at the best ask. The cryptofeed source now uses its own Independent Reserve feed, which fetches the book again, once a second, until it was created at least 3 s after the first message. The stream waits meanwhile and loses nothing. After 15 tries it uses the last book and logs a warning. - Coinbase captures through ccxt record the taker's side (#308). Coinbase
reports each trade with the side of the maker, and ccxt passes it on
unchanged, so every Coinbase capture had its trade signs reversed, and so did
order flow imbalance, VPIN and everything else built on them. The ccxt source
now reverses the side for the
coinbasevenue, on both its websocket and REST trades, and recordstrade_side_reversedinmeta.json. A Coinbase capture without that key was made before this change: reverse its signs.coinbaseexchangeneeds no change, because ccxt already reverses its side. - An Independent Reserve order no longer stays in the book after its cancel
(#313). Before 3.0, cryptofeed forgets an Independent Reserve order after its
first change, even when the order still has size, and skips every later
message for it. So the cancel after a partial fill never reached the
capture, the order stayed in the book until the capture ended, and
auditreported it as a stale resting order. The cryptofeed source now uses a subclass of cryptofeed's Independent Reserve feed that keeps the order while it rests. cryptofeed 3.0 fixes this too, but needs Python 3.13. auditno longer stops on UUID order ids (#311). A stale resting order from an Independent Reserve capture madeauditraiseValueError.StaleOrder.idnow holds the id as the feed writes it (int | str), and the text and JSON reports print it.- cryptofeed's Independent Reserve trades are linked to their orders
(#311). The trades now carry both order ids (
BidGuidandOfferGuid) inbuy_order_idandsell_order_id, and each fill is recorded from the trade, as on Bitstamp. On a per-change book, a fill that the trade and the book both report is recorded once, and a book message that repeats an order's size writes no row. - An Independent Reserve capture's
trades.csvno longer holds other markets' trades (#316). The venue sends a market's trade channel the trades of its other markets for the same coin, so a BTC-AUD capture also got BTC-NZD and BTC-SGD trades, priced in NZD and SGD.auditread them as trades through the book and reported resting orders as stale. The cryptofeed source now writes a trade totrades.csvonly when it is for the capture's pair, and counts the others asother_market_tradesinmeta.json. The venue keeps one book for all its markets, so a trade left out still reports the fill of any order it names in the capture, at the order's price. auditno longer reports lost messages on cryptofeed captures that lost none (#309). On Bitfinex and Blockchain.com cryptofeed's sequence number counts every message on the connection, trades and heartbeats too, and on Independent Reserve cryptofeed passes on no change to an order it does not hold. So the book rows skip numbers, andauditreported each skip as asequence_gapserror. The cryptofeed source now declaressequence_kind = SequenceKind.MONOTONICand records it inmeta.json, soauditchecks only that the number never goes back.meta.jsonreportssequence_out_of_orderin place ofsequence_gapsandsequence_missing, so a long capture's manifest no longer counts the skips as dropped messages. A capture whosemeta.jsonrecords nosequence_kind, such as one made before this change, is checked the way the source that made it declares now, not the way--sourcedoes.-
A quiet book no longer gives a blank depth heatmap (#303). The heatmap leaves out each price level that does not change in the window. When no level changed, as in a short capture of a quiet prediction market, that left out every level and drew blank axes, with only
Not enough data for any price levelin the log. Now the heatmap draws every level in that case, with a note under the title that no level changed. When the heatmap really is empty, the note says why: no depth data, no level between two named prices, no level in the chosen volume range, or no resting orders in the time window. All three backends put the note on its own line under the title and write it to the log. An empty heatmap still draws the midprice and trades. A spread or trades frame with no rows in the window no longer sets a NaN price range that left out every level. The gallery's depth-heatmap card namesplot_result(result, "depth_heatmap", show_all_depth=True), and the Kalshi and Polymarket how-tos describe the case. The matplotlib heatmap also no longer goes blank when one level has a single row in the window. -
The gallery prepares each card's data once (#303). The backend columns of a card now share one prepared payload, so the prepare step runs, and logs, once per card instead of once per backend.
-
The clock checks compare two real clocks, and run on L2 (#310). Where a venue sent no time, the cryptofeed and ccxt sources wrote the time they handled the message into
exchange_timestamp, which is later than the receive time. On cryptofeed's Bitfinex and Blockchain.com books, and on the Independent Reserve opening book,auditthen failed the capture onexchange_time_after_receive. Such rows now copy the receive time, as LOBSTER's one clock fills both columns. The newClocksdeclaration (BOTH,RECEIVE_ONLYorVENUE_ONLY) says which clocks a source's rows carry. LOBSTER declaresVENUE_ONLY. A live capture recordsclocksandbooks_without_venue_timeinmeta.json; read it withrecorded_clocks. With one clock,auditdoes not run the two clock checks and says why. The L2 depth frame now keepsexchange_timestampwhendepth.csvhas it, so the clock checks run on L2 captures, which before were never checked. The clock checks leave out the opening book's rows (originsnapshot), whose clocks the capture may not have measured; the L2 depth frame now keepsoriginfor this. - A cryptofeed REST opening book replays before the message that changed it (#310). On Binance and Independent Reserve, cryptofeed fetches the opening book while it handles the first live message, and hands the book over first with a later receipt time. On Binance (L2), replay applied the message and then the book's older size. On Independent Reserve (L3), with sequences tracked, the numbered message sorted before the book. The capture now holds a book with no delta until the next one arrives, and places it 1 ms before a message received earlier. The message keeps its own receipt time, and the book's rows are marked as the opening book.
- A Bitstamp capture no longer keeps trades from before its snapshot
(#301). It already skipped order messages from before the REST snapshot, but
kept the trades from the same time. The orders those trades filled are not in
the capture, so
auditcounted the trades as unmatched: up to 52% of a segment's trades with 30-second segments. The trades are now skipped and counted aspre_snapshot_trades_skippedinmeta.json. At a roll, the previous segment already has these trades. raw.jsonlno longer stops a cryptofeed capture of independent_reserve or blockchain. cryptofeed reads these venues' date and time strings asdatetime,dateandtimevalues, whichraw.jsonlcould not write, so every segment failed unless--no-rawwas passed. They are now written as ISO 8601 strings. Any other value or dict key that JSON cannot hold is written as text (str(value)), and a frame JSON cannot hold at all, such as one that refers to itself, is skipped. Neither stops the capture. Each segment'smeta.jsonnames the types written as text (raw_text_types) and counts the skipped frames (n_raw_frames_skipped); the manifest adds upraw_frames_skipped, and the capture logs each kind of warning once.- A custom plot keeps working after it is added to the gallery (#302).
The "A new plot" guide registered a plot at
Level.L2, then registered it again atNoneto put it in the gallery. After the second step,plot("cumvol")raised and told you to passLevel.L3, which was not registered. The guide now registers its example once, atNone, draws the gallery on the one backend it registered, and shows how a plot drawn at a level goes into the gallery as aPlotConcept. A test runs the guide's plot section as written. See Changed for the rule that replaces the second registration. - A gallery card added the wrong way says how to fix it (#312). A
level-less plot added to
GalleryModel.concepts, a plot drawn at a level added toGalleryModel.analytics, or aPlotConceptvariant at a level no renderer is registered at, showed a bare "Not available", the same as a renderer that raised. The gallery now checks each card against the levels its renderers are registered at. When they disagree, the card says how the plot is registered and how to change the model, and the log has the same text once. A backend that cannot be loaded says so on its cards, and is tried once instead of once for each card. A backend with no renderer for a plot that other backends draw still shows a bare "Not available". - On Python 3.11, a capture stops each segment when asked (#296). The
live sources waited for messages with
asyncio.wait_for, which on Python 3.11 can drop a cancel that arrives with a message. A roll then left the old segment streaming next to the new one to the end of the capture, with no further rolls, and SIGTERM or Ctrl-C did nothing. The sources now useasyncio.timeout, and ruff bansasyncio.wait_forin this repository. The runner cancels a stream again while it keeps yielding items, so a plug-in source with the same pattern cannot block a stop; a stream that is closing its connection is left to finish. Python 3.12 and later were not affected. - A segment that does not stop cannot hold up the capture (#296). A segment asked to stop has 20 seconds to close. After that it is cancelled and closed from its files, like a segment a crash left open. The manifest keeps why it was stopped and records the delay as its error, not as a gap. If closing its files fails, the error says so and the capture carries on. A segment covers the market only until it is asked to stop, and one asked to stop before its first live event covers nothing, so it no longer adds a second gap next to the real one. At the end of a capture all running segments are stopped together, so SIGTERM ends a capture in under a minute even when a source hangs.
-
auditno longer fails a complete Databento file (#298). Databento numbers every message on the venue's channel, so the numbers in one instrument's events skip the other instruments' messages and the trade and fill records, which become trades.auditread every skip as a lost message and failed a sound file with asequence_gapserror.DatabentoSourcenow declaressequence_kind = SequenceKind.MONOTONIC, soauditchecks only that the numbers never go back.auditreads a source's declaredsequence_kindwhen no capturemeta.jsonrecords one; read it with the newsequence_kind_of.recorded_sequence_kindreturnsNonewhen the capture records none, asrecorded_feed_typedoes. -
A Bitstamp L3 capture through cryptofeed passes
audit(#284). cryptofeed's Bitstamp L3 channel isdetail_order_book: a picture of the top 100 bids and top 100 asks about 10 times a second, not every order. Four defects followed from that: - An order that dropped past the 100th place was recorded as deleted, and as created again when it came back. It now stays tracked at its last size until the book shows its price again. This removes the duplicate created ids, and the clock errors the Bitstamp reader made from them.
- Book rows carried the venue's time in both clock columns.
timestampis now the time the capture received the message, like the trades. - Trades dropped the maker and taker order ids that Bitstamp sends. They are now read from the raw message.
- A fill showed only as a size change between two pictures, so a fully filled order read as cancelled. A trade that names a tracked order now reports its fill as it arrives, and a filled order is deleted at size 0, as the native Bitstamp feed reports it. A picture that shows an order gone before its trade arrives holds the delete for up to 2 seconds for it.
On a 90-second capture, makers now link on 40 of 42 trades, up from 16. For
analysis, the native bitstamp source still shows more: every order,
takers included.
- A capture that fails now exits non-zero and says why (#283).
ob-analytics captureused to exit 0 and write"errors": 0tometa.jsonwhen the stream raised, or when the source's optional extra was missing. A source is now checked before the capture starts: a missing extra, or an unknown ccxt or cryptofeed venue, stops the run with status 1 and creates no output directory. An error in the snapshot, the stream or the shutdown events keeps the rows already written, is recorded inmeta.jsonascapture_errorandcapture_error_phaseand counted inerrors, and makes the command exit 1. A source can take part in the early check by adding apreflight()method (SupportsPreflight). - A Binance capture no longer loses price levels near the top of the book
(#101). ccxt deletes the levels of a Binance book that fall past the depth
it is given, and Binance sends a level again only when it changes. After
the price moved away and back, the captured book had holes in its top 20
levels. The ccxt source now asks for the whole Binance book (see #275
below for what it does with that book) and never gives ccxt less than
1,000 levels a side to track, so a level rarely falls out of what ccxt
itself knows. ccxt's opening snapshot is now as deep as
--depth-limit(never less than 1,000 levels), so a Binance capture can record up to the 5,000 levels a side that Binance sends, about 1% from the price. A deeper--depth-limitis refused. auditno longer fails every ccxt capture with missing sequence numbers (#101). The ccxtnonceonly rises: a Binance diff covers a range of update IDs, and ccxt can apply several diffs before it returns a book. A capture now records"sequence_kind": "monotonic"inmeta.json, andauditthen checks only that the number never goes back. Captures made before this change record no kind and are still read as contiguous.- ccxt book rows are stamped with the time they arrived (#101). The
timestampof a ccxtdepth.csvrow was the venue's book time, while its trades used the receive time. ccxt stamps its first Binance book with its own snapshot's time and then applies older diffs, so sorting on that time swapped two updates and left a stale level:auditreported the book crossed for 90% of a session.timestampis now the receive time, and the venue's time is kept in a newexchange_timestampcolumn. - A ccxt book that loses sync is fetched again (#101). When ccxt finds a
missing Binance diff it drops its book and raises an error, which used to
end the book for the rest of the capture while trades went on. The capture
now asks for the book again (up to 10 times) and counts it as
book_resyncsinmeta.json. - A venue that refuses your location gives a one-line error. Binance
answers HTTP 451 from some countries.
capture ccxtnow says so and names--exchange binanceusand--market-data-mirror, instead of printing a traceback. - A level that only left
--depth-limit, not the book, is no longer recorded as cancelled (#275). Every ccxt capture used to cropdepth.csv/raw.jsonlto the top--depth-limitlevels a side, so a level that was still resting just outside that crop read as a0row when the price moved, the same as a real cancel — 28% of the removals in a five-minute Binance BTC/USDT capture. The capture now records whatever ccxt reports, uncropped: Coinbase, Bitstamp and OKX ignore--depth-limitand always hand ccxt their whole book (over 20,000 levels a side on Coinbase); Binance and its family are asked for their whole book too (see #101 above). Kraken is unaffected, because it subscribes at exactly--depth-limitlevels and drops a level from its own book once the price moves it out of that window — a0row there can still be either a real cancel or Kraken's own window exit, which is inherent to how Kraken reports its book.docs/howto/ccxt.mdnow says what a0row means, per venue. -
compute_vpinnow warns when its default bucket size is too big for the capture (#274). The defaultbucket_volume(average daily volume ÷ 50) scales a short capture up to a full day, so the bundled sample fills only one bucket and the trailingvpin_avgnever covers a full window. That was already recorded inattrs["diagnostics"], easy to miss on a frame that otherwise looks fine —compute_vpinnow also raises aUserWarningwhen there are fewer complete buckets thann_buckets, naming a smallerbucket_volumeorn_bucketsas the fix. The flow-toxicity how-to gains a short-captures section with a working example on the sample. -
The VPIN chart draws an empty panel when no bucket is complete. A capture with less volume than one bucket gives
compute_vpinzero rows, andplot("vpin", ...)then raised: aTypeErrorwith matplotlib, aKeyErrorwith both backends when the frame had no columns. Both backends now draw the axes with "(no complete buckets)" in the title.compute_vpinnow returns its usual columns and dtypes when it has no rows, where before it returned a frame with no columns (or, withsign_method="bvc", columns of object dtype). -
A price-level file no longer has its prices rounded to the tick size.
L2DepthLoaderandL2TradeReaderconverted each price to the nearest whole number of ticks, so a price finer thantick_sizemoved without a warning: a Kalshi price of 0.036 loaded as 0.04 at the default 0.01 tick, and the most traded Kalshi markets quote in tenths of a cent. Both now raiseConfigErrorwhen a price is not a whole number of ticks, and say which tick size to set. A ccxt capture records its market's tick size inmeta.json, andob-analytics processandob-analytics auditread it from there (recorded_tick_size), so a CLI replay needs no extra option. -
A streamed ccxt capture no longer writes a trade twice. ccxt's Polymarket websocket handed back a trade it had already delivered, together with the next new one, and only a polled capture skipped repeats. Every ccxt capture now skips a trade identical to one it has written: same id, time, price, size and side. Two fills that share a Polymarket id (the settling transaction) are both kept.
meta.jsoncounts the skipped repeats induplicate_trades. -
A polled ccxt capture no longer records trades from before it started. On a venue without websockets, the first poll of the trade tape returns the venue's recent history, which on Kalshi reached back nine hours. Those trades were written with the capture's receive time, as if they had just happened. The capture now drops trades older than its opening book.
-
A Bitstamp capture no longer starts from a snapshot older than its stream (#237). The capturer subscribes to the WebSocket, then fetches the REST book. It assumed the stream already covered the moment the book describes, but it often does not: in a live test the first order message came 0.7 s after the snapshot's
microtimestamp, and the bundled sample shows the same 0.74 s gap. An order deleted in that gap stayed in the capture until the syntheticdeletedat shutdown. In the bundled sample, one such ask was the best ask for 89% of the session.
The capturer now fetches the book again, a second apart and up to 10 times,
until some buffered order message is at or before the snapshot's
microtimestamp. meta.json gains snapshot_fetches and
snapshot_overlap. In the live test, the second fetch no longer listed any
of the 15 orders that were gone. Eight of those were orders that trades
printed through.
- A price level now empties when the order resting on it goes away.
price_level_volumeadded an order's volume at the price on itscreatedrow and subtracted it at the price on whichever later row removed it. Those two prices are not always the same: Bitstamp reports adeletedcarrying a price the order never rested at for 1.3% of orders, and the subtraction then landed on a level the volume was never added to, leaving the created level holding it for the rest of the session. Every later row now subtracts at the order's created price, so+vand-valways cancel on one level.
On the bundled Bitstamp sample this removed 104 price levels holding 29.95
BTC that no order was resting on. They were the reported touch on both sides
— best bid $78,495.00 against a real best bid of $78,350.00, and best ask
$78,324.00 against a real best ask of $78,333.00 — so best_bid_price moves
on 35.7% of depth_summary rows and best_ask_vol on 68.9%. The per-order
rebuild (engine.book_state) tracks orders by id and never had this problem;
the two rebuilds now agree on how long that book is crossed.
-
aggressiveness_bpsis NaN, not an infinity, against a zero touch. The depth engine reports a zero price for an empty side, and the Bitstamp sample also carries orders priced at zero (auditreports these asnonpositive_price). Dividing by that produced a signed infinity that travelled through every downstream mean. A distance from a price that is not tradeable has no value, so it is now NaN. -
Order lifecycles read every filled order as cancelled when sizes were floats (#226 regression).
order_lifecyclessummed each order's fills and cast the total toint64. On integer lots that is exact, but the function also accepts base-asset floats, and it is handed them on every gallery run:display_resultconverts a whole result to display units before any face builds. Base-asset sizes are mostly below 1, so a 0.121 BTC fill truncated to0, the order read as never executed, and the three lifecycle-derived L3 faces — Order Activity, Order Outcome and Queue Position — drew a book of nothing but cancellations. On the bundled Bitstamp sample the Order Activity face lost 224 of its 226 filled spans. The sum now keeps the units it was given, integer lots summing exactly and base-asset floats with the compensation that was dropped as part of #226.
LOBSTER was never affected: its lot size is 1, so a truncated size equals the size. Every LOBSTER face is pixel-identical across the change.
- LOBSTER's
fillcolumn wasfloat64, not integer lots (#226). A0.0literal in the expression that built it widened the whole column, so a schema-4.0 LOBSTER run wrote base-asset-looking floats that were really lot counts. Nothing raised; the values only differ from the correct ones once the lot size is not 1.
[0.1.0] - 2026-07-01¶
First public release (PyPI). The Python port of the R obAnalytics package, reworked into a pipeline API with pluggable formats, flow-toxicity metrics, L2/L3 visualization, and Matplotlib/Plotly backends — plus the packaging, documentation, and distribution that make it installable. The sections below also record how the API was deliberately de-bloated and unified during the port (the pipeline's numeric output is unchanged — the regression fingerprints pass; only the shape of the public API moved). See Extending ob-analytics.
Packaging & distribution¶
- The bundled Bitstamp sample ships gzip-compressed (
orders.csv.gz, ~23 MB → ~2.9 MB installed);sample_csv_path()returns the.gzpath, read transparently by pandas. No API change. - Published documentation site (GitHub Pages),
CITATION.cff, an explicit GPL-2.0-or-later license section, and a "Scale envelope" doc. - PyPI release workflow (
release.yml, trusted publishing), package classifiers and project URLs, andob_analytics.__version__. - Fixed quickstart and API-reference documentation drift.
Breaking¶
- Pydantic models removed.
ob_analytics.models(OrderEvent,Trade,DepthLevel,OrderBookSnapshot) deleted; the data contract is now column-list constants +validate_events_df/validate_trades_df/validate_depth_dfinob_analytics.schemas. metrics/package removed.ToxicityMetric,Vpin,Ofi,KyleLambda,register_metric, andlist_metricsare gone. Callcompute_vpin,compute_kyle_lambda, andorder_flow_imbalanceonresult.tradesdirectly.Pipeline(metrics=...)removed. Metrics are no longer a pipeline stage — compute them after the run.PipelineConfig.vpin_bucket_volumeremoved — passbucket_volume=tocompute_vpin.PipelineResultslimmed to exactlyevents,trades,depth,depth_summary, andconfig. Thevpin,ofi,metrics,metadata, andextrasattributes are gone.- The thirteen
plot_*wrappers removed → oneplot(name, *, backend="matplotlib", ax=None, **data)dispatcher keyed by(plot_name, backend); renderers self-register intoRENDERERS. - Global theme state removed.
set_plot_theme/get_plot_theme/_current_themedeleted; passtheme=PlotTheme(...)toplot(). - Exception hierarchy collapsed to
ObAnalyticsError+ConfigError.InvalidDataError,MatchingError,InsufficientDataError, andConfigurationErrorare removed. - Top-level
__all__trimmed to ~22 orchestration names. Low-level helpers now import from their submodules —ob_analytics.bitstamp,ob_analytics.lobster,ob_analytics.analytics,ob_analytics.depth,ob_analytics.data,ob_analytics.visualization,ob_analytics.flow_toxicity. Formatis now atyping.Protocol— there is no base class to inherit; any conforming object is recognised structurally.- Low-level helpers no longer re-exported from the package root (e.g.
depth_metricsis nowfrom ob_analytics.depth import depth_metrics). RunContext.extrasandFormat.collect_extrasremoved. LOBSTER trading halts are read fromLobsterLoader.trading_haltsand composed into the gallery viaextra_panels=.DepthMetricsEngine.update()removed → the public hot-path method isupdate_side(price, volume, side, out).
Added¶
ob_analytics.schemas— the single data contract: column-list constants (EVENT_COLUMNS,TRADE_COLUMNS,DEPTH_COLUMNS) plus thevalidate_*functions, run at the pipeline's Protocol boundaries. Replaces the Pydantic model layer.- One generic
Registry[K, V](ob_analytics._registry) backs the format, writer, capturer, and renderer registries. Register through the public helpersregister_format,register_writer,register_capturer, andRENDERERS.register/register_plot_backend. - Unified
plot()dispatcher +RENDERERSregistry keyed by(plot_name, backend), so new plots and backends plug in without a wrapper function. The HTML gallery composes custom panels viaextra_panels=. ob_analytics.live— optional sub-package for live order-book capture: theLiveCapturerprotocol (with an optionalSupportsDiagnosticscapability),CaptureConfig,CaptureResult,CaptureSink, and a generic asyncio runner. Capture output drops straight into the pipeline (orders.csvschema unchanged). Install withpip install "ob-analytics[live]".ob-analytics capture <venue>CLI verb with a built-inbitstampcapturer (ob_analytics/live/bitstamp.py);--listshows registered capturers.scripts/collect_bitstamp_btcusd.pyis now a thin wrapper around it.TradeSourceprotocol andBitstampTradeReader— read an authoritative companiontrades.csvand join it to events via thefillcolumn.RunContextdataclass (ob_analytics.protocols, re-exported at the top level) for per-run parameters such as LOBSTERtrading_datethat don't belong on long-livedFormatinstances.- Docs —
docs/extending.md(add a data source / writer / plot / metric / capturer). - Tests —
test_bitstamp.py,test_cli.py(subprocess smoke tests for all CLI subcommands),test_exceptions.py,test_data_registry.py, a regression snapshot suite pinning demo Parquet hashes + the Kyle-λ baseline, andob_analytics/__main__.py(python -m ob_analytics).
Changed¶
- Bundled sample —
ob_analytics/_sample_data/now shipsorders.csvandtrades.csvfrom a modern BTC/USD live capture (replaces the legacy 2015 orders-only slice). - Demos consolidated into
ob_analytics._demos;scripts/bitstamp_demo.py,scripts/lobster_demo.py, and thebitstamp-demo/lobster-demoCLI subcommands are now thin argparse wrappers. Behaviour unchanged. - Performance — the LOBSTER book is maintained as a
SortedDict(no per-event re-sort), Bitstamp trade→event resolution is indexed, LOBSTER depth uses a single strategy, the Plotly import is memoised, and depth metrics sum active levels into bps bins. Numeric output is unchanged (pinned by the regression snapshots). compute_kyle_lambdacomputes its OLS vianp.linalg.lstsq(was hand-rolled; agrees with the prior implementation tortol=1e-10).- Internal modules reorganized (renames from the 0.x line): e.g.
event_processing.py→bitstamp.py, validation/time helpers →_utils.py, and the visualization modules split into avisualization/subpackage. - Type checking is Astral's
ty(not mypy); lint and format are Ruff.
Removed¶
pacmanorder type. A legacy artifact of the 2015 Bitstamp HTTP API, where a singleorder_idcould appear at multiple prices over its lifetime. Modern Bitstamp WS v2 and LOBSTER do not produce this pattern (price-modifies become cancel + new id). ThetypeCategorical no longer includes"pacman", the set-subtraction classification path is gone, andLobsterLoaderno longer renumbers hidden-execution ids (raw type 5 now retains the native LOBSTERid=0).- Bitstamp trade inference. A companion
trades.csvnext toorders.csvis now required. Removed: Needleman–Wunsch matching,BitstampMatcher,BitstampTradeInferrer, theMatchingEngine/TradeInferrerprotocols,NeedlemanWunschMatcher, and thematch_cutoff_ms/price_jump_thresholdfields onPipelineConfig. - Zombie detection —
get_zombie_idsand thezombie_offset_seconds/skip_zombie_detectionconfig fields. - LOBSTER
LobsterMatcher— removed;LobsterTradeInferrerrenamed toLobsterTradeReaderwithload(events, source). - Legacy Bitstamp-only wrappers
load_event_data,event_match,match_trades,process_data, andplot_price_levels_faster. - 12 unused runtime dependencies (scikit-learn, scipy, jupyter, bokeh, …) and stale dev dependencies (black, flake8 + plugins, darglint).
Fixed¶
depth_metricsno longer overflows for prices > $9,999.99 — dynamicdict[int, int]state replaces the fixed array.best_bid/best_askare tracked correctly from the first event (were initialised with dataset-wide max/min).datetime_to_epochuses.astype("int64")instead of the deprecated.view("int64").- All
print()replaced withlogurulogging; all bareassertstatements replaced with raised exceptions;plt.show()removed from plot functions (callers control display).