Skip to content

Bitstamp

Bitstamp-specific components: event loading, trade reading from companion trades.csv, CSV writing, and BitstampSource (the default pipeline source, which does both offline CSV replay and live WebSocket capture).

Modern workflows pair orders.csv with trades.csv (for example from ob-analytics capture bitstamp). The pipeline resolves trades.csv from the same directory as the orders.csv path passed to Pipeline.run.

BitstampLoader

BitstampLoader(
    config: PipelineConfig | None = None,
    *,
    venue: str | None = None,
    symbol: str | None = None,
)

Load raw limit-order events from a Bitstamp-format CSV.

Satisfies the :class:~ob_analytics.protocols.EventLoader protocol.

Parameters:

Name Type Description Default
config PipelineConfig

Pipeline configuration: the instrument's tick_size and lot_size. An order's price that is not a whole number of ticks raises ConfigError; a size between two lots is rounded with a warning. A trade's price can lie between two ticks, so it is rounded to the nearest tick, not checked.

None
venue str

Optional instrument identity. When either is supplied, the loaded frame gains per-row venue / symbol columns; venue falls back to "bitstamp" when only symbol is given. Each one not supplied is taken from the capture's meta.json when it records one, so a replayed capture names its instrument. With neither, the frame is left untagged.

None
symbol str

Optional instrument identity. When either is supplied, the loaded frame gains per-row venue / symbol columns; venue falls back to "bitstamp" when only symbol is given. Each one not supplied is taken from the capture's meta.json when it records one, so a replayed capture names its instrument. With neither, the frame is left untagged.

None

load

load(path: str | Path) -> pd.DataFrame

Read path CSV and return a cleaned events DataFrame.

Parameters:

Name Type Description Default
path str or Path

Path to a Bitstamp-format CSV with columns id, timestamp, exchange_timestamp, price, volume, action, direction.

required

Returns:

Type Description
DataFrame

Cleaned events with columns id, timestamp, exchange_timestamp, price, volume, action, direction, event_id, fill, original_number.

Notes

Each order's rows come in the order they happened: the created row first, then the rest by timestamp. Rows that share an instant follow the file's sequence column when it has one; a deleted row then goes last, and the rest keep their order in the file. A row with no sequence number keeps its place after the row before it in the file. event_id numbers the rows of all orders by the same keys: time, then sequence, then file order. The order ids take no part. fill is the drop in size from the order's previous row. A row whose size rises (an order changed to a larger amount) has fill 0.

load_windows

load_windows(
    path: str | Path,
    windows: list[
        tuple[Timestamp | None, Timestamp | None]
    ],
    *,
    working: Path | None = None,
) -> Iterator[LoadedWindow]

Yield the events of each time window of path in turn.

An order's rows are put in order, and its fills worked out, from all of its rows, and an order can last over many windows. So the rows go through files in working twice. The file is read :attr:read_size rows at a time, and each part's rows are split by order id into files. Then the rows of one group of orders at a time, about :attr:rows_per_group rows, are read back, put in order, and split into one file per window. Last, each window is read back on its own and its events are numbered. So no more than one part, one group or one window is in memory at once, and the file need not be in time order. The events are the rows :meth:load gives, cut at the windows.

The trades of the companion trades.csv are matched to their orders one group at a time too, by the rules :class:BitstampTradeReader applies. Once the last window is yielded, :attr:trade_matches holds the trades and the events they name, so the trade reader builds the whole run's trades without the events.

Parameters:

Name Type Description Default
path str or Path

The orders file, as for :meth:load.

required
windows list of tuple

(start, end) per window, tz-aware UTC, None for an open end, covering the whole file: what :func:~ob_analytics._windows.window_bounds returns.

required
working Path

An empty folder for the files, which the caller deletes. By default a temporary folder is made and deleted.

None

Yields:

Type Description
LoadedWindow

The window's events, and the event_id of each of them a trade names.

Raises:

Type Description
FileNotFoundError

If there is no trades.csv next to path.

BitstampTradeReader

BitstampTradeReader(
    config: PipelineConfig | None = None,
    *,
    loader: BitstampLoader | None = None,
)

Build trades from the companion trades.csv that ob-analytics capture bitstamp writes next to orders.csv.

Reads each row from <source_dir>/trades.csv and projects it into the canonical trades schema, joining against the events frame to resolve buy_order_id / sell_order_id into event_id and original_number references. It keeps the venue's time of each trade as exchange_timestamp, empty where the file has none.

A trade is matched to a row of the order it names whose fill is the trade's size, the earliest such row first. Bitstamp does not always report that size: an instant order bought by quote amount is created with size 0 and then shows a size of 0 or one lot, never what it bought. When no row shows the trade's size and the taker the trade names is such an order (one created with size 0), the trade is matched to that order's deleted row, else its latest row, and every such trade of that order names the same row. The order and its type are then right, but its rows show less fill than its trades. :func:~ob_analytics.quality.data_quality_summary counts these trades as trades_matched_by_order.

Every other trade is matched on size only. A trade stays unresolved (NaN) when no row of its order shows its size: the events have no row of that order, or a message was lost. The same rules apply to captures from other venues read through this reader.

Satisfies the :class:~ob_analytics.protocols.TradeReader protocol.

Parameters:

Name Type Description Default
config PipelineConfig

Pipeline configuration: the instrument's tick_size and lot_size.

None
loader BitstampLoader

The loader that read the events. When it read them one window at a time (:meth:BitstampLoader.load_windows), it has matched the trades already, and :meth:load, given an empty events frame, builds the trades from what it kept. :class:BitstampSource passes its loader.

None

BitstampWriter

BitstampWriter(config: PipelineConfig | None = None)

Write pipeline events back to Bitstamp-format CSV.

Writes a folder laid out as ob-analytics capture bitstamp lays one out: orders.csv, and trades.csv when the run has trades.

Satisfies the :class:~ob_analytics.protocols.DataWriter protocol.

write

write(
    data: dict[str, DataFrame],
    dest: str | Path,
    **kwargs: Any,
) -> Path

Write the events to <dest>/orders.csv in Bitstamp's format.

When data also carries a "trades" frame, a trades.csv is written next to it in capture format, so that a subsequent :class:BitstampTradeReader can reconstruct trades when the orders.csv is re-read. The events' sequence and origin columns are written too when the events carry them, so a capture read and written again keeps them.

The files are in the current capture format (times in nanoseconds), and the folder's meta.json records its version: one is written when there is none, and the other fields of one already there are kept.

Parameters:

Name Type Description Default
data dict of str to DataFrame

Must contain an "events" key. An optional "trades" key triggers a trades.csv in the same folder.

required
dest str or Path

Output folder, created when missing.

required

Returns:

Type Description
Path

The written orders.csv path.

Raises:

Type Description
ConfigError

If the events have no rows: an L2 run has no per-order events.

BitstampSource

BitstampSource(settings: SourceSettings | None = None)

The Bitstamp source: offline CSV replay and live WebSocket capture.

One descriptor for both ways to get Bitstamp data. It satisfies :class:~ob_analytics.protocols.OfflineSource (the CSV loader / trade reader / writer, inline and dependency-light) and :class:~ob_analytics.live._base.LiveSource (snapshot / stream / shutdown, delegated to a WebSocket engine imported lazily from :mod:ob_analytics.live.bitstamp). The lazy import is what keeps the offline path free of the [live] extra: importing this module never imports websockets; only starting a live capture does.

Conforms structurally to the source protocols — no inheritance required.

preflight

preflight() -> None

Raise the install hint now if the [live] extra is missing (SupportsPreflight).

diagnostics

diagnostics() -> dict[str, Any]

Per-run counters from the live engine (SupportsDiagnostics).