Skip to content

Capture live order-book data

ob-analytics ships a small framework for capturing live order-book data straight into the format the pipeline reads. Install the optional [live] extra (pulls in websockets) and use the capture CLI verb. Live capture is supported on Linux and macOS only.

pip install "ob-analytics[live]"

ob-analytics capture bitstamp --pair btcusd --minutes 10 -o /tmp/cap
ob-analytics process /tmp/cap --gallery --output /tmp/cap_out

What the bitstamp source shows

Property Value
Level L3
Depth shown whole book
Orders shown every order, takers included
Update form every change
What can be missed a lost message
After a lost message drifts: the order stays until the capture ends
Sequence none
Clocks venue + receive
Crossing diff feed
Trade sides named both
Taker side venue
Fills per fill
Trade tape gaps none
Price grid fixed (0.01 on BTC/USD)
What the book means normal
Access public

Use it for Bitstamp order analysis: order lifetimes, order types, queue position and maker–taker links. Don't use it without reading audit's stale-order check: a lost message leaves an order in the book until the capture ends. What each feed shows explains each property and compares every source.

A capture is a directory of segments. A short run has one; a long run can have many (see Running for days). Each segment is a complete capture on its own, so it replays alone:

/tmp/cap/
  manifest.json
  seg-0001/
    orders.csv  trades.csv  raw.jsonl  meta.json
  seg-0002/
    ...
File Contents
manifest.json The whole capture: its segments, why each one ended, and the gaps between them
seg-NNNN/orders.csv BitstampLoader-compatible event log (created / changed / deleted)
seg-NNNN/depth.csv L2 captures only, in place of orders.csv: one row per price-level change
seg-NNNN/trades.csv Venue-reported trades (informational; pipeline infers fills itself)
seg-NNNN/raw.jsonl The raw WebSocket frames, one per line (omit with --no-raw). A value or dict key that JSON cannot hold is written as text (str(value)). A frame that JSON cannot hold at all, such as one that refers to itself, is skipped. Neither stops the capture
seg-NNNN/meta.json Segment metadata, the capture record: start/end, counts, per-capturer diagnostics, the source and what it declares about its feed, and the instrument's tick_size and lot_size, the file format version (capture_format), and the instrument's venue and symbol. When the venue gives a step, the capture uses it and records it as stated (tick_size_stated or lot_size_stated is true). When the venue does not give a step, the capture starts from 0.01 and 1e-8 and makes each step finer until every price and size written fits, and records it as fitted (false). A stated step that a price or size does not fit is made finer too, and is then recorded as fitted. A fitted tick can be finer than the venue's real tick, which makes every count in ticks too large; audit says which the capture has. A capture made before captures recorded this reads as fitted. With raw.jsonl on, raw_text_types names the types written as text and n_raw_frames_skipped counts the skipped frames. n_raw_frames counts every frame, skipped ones included, so raw.jsonl has n_raw_frames - n_raw_frames_skipped lines. The capture logs a warning the first time each happens

The file format

The CSV files are in format version 2, which meta.json records as "capture_format": 2:

  • Times are whole nanoseconds since the epoch (UTC), so each time keeps the precision the venue sent. Bitstamp sends microseconds.
  • Every file names the book side or the taker's side direction, and the size volume.
  • meta.json records the venue and symbol. A replay puts them on every row of the events (L3) or the depth (L2), so you do not need a RunContext. A RunContext or --venue / --symbol replaces them.
File Columns
orders.csv id, timestamp, exchange_timestamp, price, volume, action, direction, sequence, origin
depth.csv timestamp, exchange_timestamp, direction, price, volume, sequence, origin
trades.csv trade_id, timestamp, exchange_timestamp, price, volume, buy_order_id, sell_order_id, direction

A capture made before captures recorded a format version has no capture_format, and is read as version 1: times in milliseconds, and side and amount in place of direction and volume in trades.csv and depth.csv. It has no venue or symbol on its rows unless you give them. A capture made by a later version of ob-analytics than yours is refused with a message to upgrade.

Reading a capture

process and audit given the capture directory work through each segment. They need no --source: the capture records the source that reads it back (replay_source, in meta.json and manifest.json), such as depth_csv for a ccxt capture. A capture made by an older version records none and is read by the source for its level, or by bitstamp when it records no level either. A --source of another level is refused. A --source of the same level that is not the recorded one is used, with a warning that names the recorded one. process writes each segment's results to the folder of the same name under --output and copies manifest.json there. To read one segment in Python, pass its book file: Pipeline().run("/tmp/cap/seg-0001/orders.csv").

The pipeline reads the segment's meta.json and uses the recorded tick size and lot size when your config does not set them, the same as process does. So the Python API and the CLI give the same result for one folder. To read the record yourself, use read_record:

from ob_analytics.capture_record import read_record

record = read_record("/tmp/cap/seg-0001")
record.tick_size, record.tick_size_stated, record.lot_size, record.feed_type

The Bitstamp capturer also pulls a REST order-book snapshot at startup (emitting synthetic created events for every resting order) and emits synthetic deleted events at shutdown so every order id in orders.csv has a complete created -> ... -> deleted lifecycle.

Which rows came from the snapshot

Every row of orders.csv and depth.csv has an origin column that says which part of the capture wrote it:

origin Written by
snapshot The opening book, before the stream starts
stream A live message from the venue
shutdown A synthetic close-out at the end of the run

The runner fills this in, so it means the same thing for every venue. A source that delivers its opening book as its first live message, as the cryptofeed source does, has no snapshot rows. Captures made before this column existed do not have it.

The pipeline keeps the column, so result.events["origin"] tells you whether an order was first seen in the opening book or placed during the run.

When the snapshot and the stream line up

The Bitstamp capturer subscribes to the stream first, then fetches the REST book while it holds the live messages in a buffer. That only works if the stream already covers the moment the REST book describes. Then every change after the snapshot arrives on the stream, and buffered messages the snapshot already includes are skipped (pre_snapshot_skipped in meta.json). Trades from before the snapshot are skipped too (pre_snapshot_trades_skipped). The orders they filled are not in the capture, so audit would count them as unmatched. At a roll, the previous segment already has these trades.

Bitstamp's REST book can be older than that. In a live test the first order message on the stream came 0.7 seconds after the snapshot's microtimestamp. An order deleted in that gap is in the snapshot, but the stream never reports its delete. The bundled sample has the same gap, and two of its asks are stale for this reason. A second fetch 2 seconds later no longer listed any of them.

So the capturer checks for overlap: at least one buffered order message must be at or before the snapshot's microtimestamp. If none is, it waits a second and fetches the book again, up to 10 times. meta.json records how many fetches it took (snapshot_fetches) and whether the snapshot it used overlaps the stream (snapshot_overlap). If snapshot_overlap is false, orders removed just before the stream started may stay on the book until shutdown.

Opening orders the stream never confirmed

The opening book is not checked against the stream after the capture starts. An order that the snapshot lists but that had already gone rests in the capture until the synthetic deleted at shutdown. It then looks like a normal order with a complete lifecycle.

meta.json reports n_snapshot_unconfirmed: how many orders in the opening book were never named again by an order event or a trade. Most of these are far from the touch and did not trade during the run, so a large number is normal. Compare it with the size of the opening book, then look at the unconfirmed orders near the touch. An unconfirmed order that trades print through was not really on the book; ob-analytics audit reports these as stale_orders. L2 captures report null, because a price level has no id that the stream could confirm.

Running for days

A capture can run unattended. Every break in it is handled the same way: the current segment is closed, with its closing rows, and a new segment starts from a fresh snapshot. manifest.json records each break.

Rolling to a new segment. --roll-minutes 60 starts a new segment every hour, and --roll-mb 500 starts one when a segment has written 500 MB since its first live event (the opening snapshot does not count). Both must be above 0. The new segment starts before the old one stops, and the old one stops only when the new one is streaming. The two segments overlap, so a roll loses nothing.

A lost connection. The segment ends with the error in its meta.json. The capture waits 1 second, then starts a new segment. The wait doubles after each failure in a row, up to 60 seconds, and goes back to 1 second after a segment that ran for a minute. The time between the two segments is recorded as a gap. Book changes made during a gap cannot be recovered: no venue replays them. The new snapshot means the book is correct again from the start of the next segment.

A restart. Run the same command again with the same --output and the capture continues in the next segment. If the old process died without closing its last segment, the restart closes it: it cuts off a half-written last line, writes a deleted row for each order still open at the last recorded time, and completes meta.json with "unfinished": true. The time the capture was down is recorded as a gap. The capture refuses an --output that holds a different venue or pair, files but no manifest.json, or a manifest.json this version cannot read. While it runs, the capture holds a lock on --output (the .capture.lock file), so a second capture into the same directory stops with an error instead of rewriting the first one's files.

A segment that does not stop. A segment asked to stop, at a roll, at the end or on a signal, has 20 seconds to close its connection and write its closing rows. If it takes longer, it is cancelled and closed from its files, the same way a restart closes a segment a crash left open. The manifest keeps why it was stopped (rolled_time, finished, ...) and records the delay as its error. The delay is not a gap: the segment had already stopped streaming. If closing its files fails, the error says so and the capture carries on. So a connection that hangs cannot stop the rolls, and SIGTERM ends a capture in under a minute: at most two of these limits, if it arrives while a roll is waiting for a segment that hangs.

A second Ctrl-C or SIGTERM. The first signal asks the running segment to stop and write its closing rows. A second signal stops the capture at once: a segment still closing is cancelled and closed from its files, as above, and its error says a second signal stopped it. Every file is closed, and meta.json and the manifest are still written.

This lets a service manager restart the capture. For example, a systemd unit with Restart=always and ExecStart=ob-analytics capture bitstamp --pair btcusd --minutes 10080 --roll-minutes 60 -o /data/btcusd captures for a week (counted from each start) and continues after a crash or reboot.

manifest.json records:

Field Meaning
source, pair, level What was captured. A restart must match them
feed_type, trade_attribution, sequence_kind What the source declares about its feed
replay_source The offline source that reads the capture back. process and audit use it when --source is not given
version The layout version (currently 1)
started, ended When the capture started, and when it last stopped
restarts How many times the capture was started again in this directory
segments Each segment: when it streamed from and to (until it was asked to stop; none for a segment asked to stop before its first live event), why it ended (rolled_time, rolled_size, failed, ended_early, unfinished, stopped, finished), its error, row counts, the messages its source dropped, its diagnostics_error when the source's counters were lost, its book_resyncs, and the frames raw.jsonl skipped
gaps Each stretch with no segment streaming: start, end, length, and cause (disconnect, restart, roll, stopped, finished)
dropped, book_resyncs, raw_frames_skipped, gap_seconds Totals over the whole capture

The manifest is rewritten after every change and every 10 seconds while the capture runs, so it is never more than 10 seconds out of date.

ob-analytics audit /tmp/cap audits each segment, then prints the capture's own checks: gaps, segments a dead process left open, dropped messages, errors (a segment that ended on one, or was slow to stop), and resyncs. These are warnings, so audit --strict fails a capture that has any. A segment whose source's counters were lost (diagnostics_error) fails the dropped-message check too, since its count is not known. You can audit or process a capture while it runs. The segment still being captured is left out, and the log names it: it has no closing rows yet, so every order still resting would read as a fault. Only closed segments are read.

A capture that fails

ob-analytics capture checks the source before it starts. If a source needs an optional extra that is not installed, or the venue name is unknown, it prints the reason, exits with status 1, and creates no output directory.

If the first segment of a new capture fails before its first event, the settings are probably wrong (a pair the venue does not list, a location it refuses), so the capture stops and exits with status 1 instead of retrying. It also exits with status 1 if no segment streamed at all. A failure after that ends the segment and the capture carries on, as described above.

A segment keeps the rows it wrote before an error. Its meta.json records the error as capture_error, and the step that failed as capture_error_phase (snapshot, stream, shutdown, or close when a file could not be written out). After a failed snapshot the stream does not run. Messages a source received but could not use are counted in dropped. At L3, an order message a source cannot use (Bitstamp's, or cryptofeed's) ends the segment instead, with UnmappedMessageError as its error: the book would be wrong from then on, and the next segment starts from a fresh snapshot. The kalshi source does the same at L2, for a book change it cannot apply or a missing sequence number. A trade Bitstamp cannot parse is still left out and counted, since its order events carry the fills. If the source cannot report its counters, the capture logs a warning and meta.json records diagnostics_error instead. ob-analytics audit on a single capture reports the dropped messages and the error as the dropped_messages and capture_errors warnings.

Adding a new venue

A venue the built-in sources do not reach needs a source of its own with the live capability: three async methods that parse the venue's feed into event rows. run_capture does the rest: it writes the files and meta.json, rolls segments, and starts a new segment when the connection drops. See The live capability in "Extending ob-analytics" for the methods, an example, and the rules a stream must keep.