Metadata-Version: 2.4
Name: pcapmbo
Version: 0.1.0
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Dist: pyarrow>=14 ; extra == 'arrow'
Requires-Dist: pytest>=7 ; extra == 'test'
Requires-Dist: zstandard ; extra == 'test'
Requires-Dist: tzdata ; extra == 'test'
Requires-Dist: pyarrow>=14 ; extra == 'test'
Requires-Dist: databento-dbn ; extra == 'test'
Provides-Extra: arrow
Provides-Extra: test
License-File: LICENSE
Summary: Decode raw exchange packet captures (pcap / pcap.zst) into standard market-by-order (MBO) events
Keywords: pcap,itch,market-data,order-book,mbo
License-Expression: Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/FIN-556-Market-Microstructures/pcapmbo

# pcapmbo

Decode raw exchange packet captures (pcap / pcap.zst) into standard
market-by-order (MBO) events, with both the exchange timestamp and the
capture timestamp. Rust core, Python API.

```bash
pip install "pcapmbo[arrow]"
```

```python
import pcapmbo

for batch in pcapmbo.read_pcap("capture.pcap.zst", symbols=["NVDA"]):
    print(batch.num_rows)            # a pyarrow.RecordBatch of MBO records

pcapmbo.to_dbn("capture.pcap.zst", "nvda.mbo.dbn.zst", symbols=["NVDA"])
```

**Supported feed:** Nasdaq TotalView-ITCH 5.0 over MoldUDP64, in classic pcap
files (nanosecond or microsecond, plain or zstd-compressed), with Ethernet,
up to two VLAN tags, IPv4 and UDP.

> **Status: alpha (0.1).** Checked against an independent parser on real
> Nasdaq captures (below). The API may still change before 1.0.

## Why

Fast ITCH parsers and order book tools already exist, but they read ITCH day
files, not network captures. The tools that do read captures are C++
programs with in-memory books or their own CSV output. pcapmbo gives you,
from a pip install:

- **raw captures in:** pcap / pcap.zst, with MoldUDP64 sequencing, gap
  reports, A/B duplicates dropped, and a session carried across rotated files
- **standard events out:** the MBO schema of the open
  [DBN](https://github.com/databento/dbn) format, following Databento's own
  normalization of Nasdaq ITCH, so the output works with Databento's tools as
  well as pandas, polars and Parquet
- **both clocks:** `ts_event` (exchange time) and `ts_recv` (when the capture
  saw the packet)

| | reads raw captures | standard event output | Python API | licence |
|---|---|---|---|---|
| **pcapmbo** | yes | DBN MBO, Arrow | yes | Apache-2.0 |
| [itch-book](https://github.com/groovg/itch-book) | no (ITCH day files) | its own | yes | MIT |
| [MeatPy](https://github.com/vgreg/MeatPy) | IEX DEEP only | its own | yes (pure Python) | BSD-3 |
| [pcap_feed_decoder](https://github.com/pankajj6/pcap_feed_decoder) | yes | in-memory books | no | AGPL-3.0 |
| [Databento DBN](https://github.com/databento/dbn) | no (Databento's own data) | DBN | yes | Apache-2.0 |

## Output

`read_pcap(paths, symbols=None, date=None, batch_size=1_000_000)` yields Arrow
record batches with `pcapmbo.schema()`:

| column | type | |
|---|---|---|
| `ts_recv` | timestamp[ns, UTC] | capture time |
| `ts_event` | timestamp[ns, UTC] | exchange time (ITCH timestamp on the Eastern trading date) |
| `publisher_id` | uint16 | 2, DBN's id for Nasdaq TotalView-ITCH |
| `instrument_id` | uint32 | the day's stock locate code |
| `action` | string | **A**dd, **C**ancel, **T**rade, **F**ill |
| `side` | string | **A**sk, **B**id, **N**one |
| `price` | int64 | units of 1e-9 (divide by `pcapmbo.PRICE_SCALE`); null if unknown |
| `size` | uint32 | shares |
| `channel_id` | uint8 | 0 |
| `order_id` | uint64 | Nasdaq order reference; 0 on Trades |
| `flags` | uint8 | `F_LAST`, `F_MAYBE_BAD_BOOK`, ... |
| `ts_in_delta` | int32 | `ts_recv - ts_event` |
| `sequence` | uint32 | MoldUDP64 sequence number (low 32 bits) |
| `symbol` | string | ticker |

`to_dbn(paths, out, symbols=None, date=None)` writes the same records as a DBN
file (zstd if `out` ends in `.zst`), with dataset `XNAS.ITCH`, schema `mbo`
and per-day symbol mappings. Databento's `databento-dbn` reads it back.

### How ITCH becomes MBO

| ITCH message | MBO records |
|---|---|
| Add (A), Add with MPID (F) | Add |
| Order Executed (E) | Trade, Fill, Cancel |
| Order Executed with Price (C) | Trade, Fill, Cancel (no Trade if non-printable) |
| Order Cancel (X) | Cancel (the shares removed) |
| Order Delete (D) | Cancel (the shares left) |
| Order Replace (U) | Cancel (old order), Add (new order, same side) |
| Trade, non-cross (P) | Trade, side None |
| Cross Trade (Q) | Trade, side None, if shares matched |
| everything else | nothing |

Trade and Fill records carry the aggressor's side and the execution price;
the Cancel after an execution carries the resting order's side and price and
is the only one that changes the book. Records from one ITCH message share
`sequence`; the last has `F_LAST`. A capture that starts mid-session can't
know orders added before it began: their executions and cancels get side
None, a null price and `F_MAYBE_BAD_BOOK`.

Not yet: filling gaps from a second line (A/B arbitration), IEX DEEP, CME
MDP 3.0, pcapng.

## Checked on real data

`scripts/compare_with_course_parser.py` decodes the same captures with
pcapmbo and with an independent Python ITCH parser (from the UIUC FIN 556
course project that pcapmbo grew out of) and compares every row.

One 10-minute Nasdaq file at the open (3 Feb 2025, 1.1 GB compressed,
45,088,399 messages), filtered to NVDA, AAPL and TSLA, on an Apple M4 Pro.
The course parsers keep an order book, as pcapmbo's MBO output does:

| | wall time | peak memory |
|---|---|---|
| Python reference parser | 53.4 s | 4.55 GB |
| C++ build of the same parser | 3.5 s | 77 MB |
| **pcapmbo**, ITCH decoding | **3.3 s** | **17 MB** |
| **pcapmbo**, MBO records | **3.4 s** | 365 MB |

The MBO run collects all 2.1 million records (about 115 MB) in one buffer and
copies it into Python; `read_pcap` streams them in batches instead.

All 1,618,385 rows for the three stocks matched the reference on every field,
including the side and price it takes from its order book on executions,
cancels and deletes. 0 gaps, 0 duplicates, 0 malformed messages.

## Market data

This repository contains **code only**. Never commit market data, licensed
or otherwise: tests use synthetic captures. The `.gitignore` blocks common
capture and data file types as a safety net.

## Development

Needs Rust 1.88 or newer and Python 3.9 or newer.

```bash
python -m venv .venv && source .venv/bin/activate
pip install maturin -e ".[test]"
cargo test                 # Rust tests
maturin develop --release  # build the extension into the venv
pytest                     # Python tests
```

### Test captures

Tests never use real market data. `tests/capgen.py` builds synthetic ITCH 5.0
captures byte by byte (pcap, Ethernet with optional VLAN tag, IPv4, UDP,
MoldUDP64), together with the list of messages a correct decoder should
produce. It covers every ITCH 5.0 message type and the cases decoders tend to
get wrong: heartbeats, non-market frames, A/B duplicates, sequence gaps,
session changes, microsecond pcaps, truncated frames and files split across a
session. The MBO output is checked byte for byte against a reference mapper
written separately in Python, and the DBN files against Databento's decoder.

```bash
python tests/capgen.py OUT_DIR    # write the standard fixture files
```

### Counting messages

```bash
cargo run --release --example count -- capture.pcap.zst
```

prints the messages per ITCH type, the gaps and duplicates found, and the
throughput.

## Licence

[Apache-2.0](LICENSE)

