- About
- Why
- Formal Model & Mechanics
- Market Microstructure & Allocative Metrics
- Data Pipeline & Validation
- Zero-Intelligence Simulation
- Repository Structure
- Incremental Workflow
- Usage & Testing
- Limitations & Notes
cda engine is a deterministic, discrete event Continuous Double Auction (CDA) matching engine and Zero Intelligence (ZI) market simulator written in Python. Rather than relying on an opaque third party matching library, it builds a single instrument two sided Limit Order Book (LOB) from first principles and separates order stream sanitization, deterministic order matching, microstructure and surplus metrics, and ZI market simulation into distinct, independently testable modules.
| Dimension | Included in Current Architecture | Excluded |
|---|---|---|
| Instruments | Single instrument two sided book (BUY / SELL) |
Multi asset books, cross margining, synthetic spreads |
| Order Types | LIMIT (positive limit price) and MARKET (unpriced aggressive) |
IOC, FOK, stop loss, iceberg, post only |
| Priority Rule | Strict price time (FIFO) priority with deterministic tie breaking | Pro rata allocation, size priority, call auctions |
| Order Lifecycle | Arrival, matching/partial fill, resting on book, full depletion | Explicit CANCEL, AMEND / REPLACE, order expiration |
| Infrastructure | CSV ingestion, rejection logging, pytest tests, ZI runs |
FIX/ITCH network protocols, lock free queues, colocation |
Production matching engines optimize for sub microsecond latency, hardware affinity, and network framing, details that often obscure the exact mathematical transitions of an order book. Implementing a matching engine from first principles makes every rule explicit and helps catch subtle defects early, such as inverted tie breakers on equal prices, binary floating point drift in price comparisons, quantity leaks on partial fills, or division by zero errors on empty books and zero trade sessions.
At the same time, experimental market microstructure shows that continuous double auctions capture high allocative efficiency even when traders are unstrategic and budget constrained (Zero Intelligence agents, following Vernon Smith's double auction experiments). Keeping the deterministic matching core and the ZI simulation in one repository makes it possible to inspect every state transition, verify boundary conditions with pytest, and measure economic efficiency across horizons.
Each order LIMIT orders (empty/none for MARKET), $q_u \ge 0$ is remaining quantity (with valid initial quantity $Q{u,0} > 0$), and decimal.Decimal or integer tick multiples rather than binary float to avoid rounding drift.
Resting LIMIT orders on each side follow price time (FIFO) priority: better price first, then earlier arrival timestamp on ties (with a deterministic tie breaker such as input sequence index or order_id if price and timestamp match):
When a side is non empty, best bid and best ask are:
Once no crossable orders remain, the book satisfies
An incoming aggressive order crosses against the highest priority passive order on the opposite side while remaining quantity is positive and the crossing condition holds:
-
Aggressive
BUY(LIMITat$P_{\text{agg}}$ ): crosses top passiveSELLat$P_{\text{ask}}$ iff$P_{\text{agg}} \ge P_{\text{ask}}$ . -
Aggressive
SELL(LIMITat$P_{\text{agg}}$ ): crosses top passiveBUYat$P_{\text{bid}}$ iff$P_{\text{agg}} \le P_{\text{bid}}$ . -
Aggressive
MARKET(BUYorSELL): crosses against resting liquidity on the opposite side until its remaining quantity reaches$0$ or no crossable opposite liquidity remains. UnfilledMARKETremainders never rest on the book; any remainingLIMITquantity ($q_{\text{agg,rem}} > 0$ ) rests on its own side.
Each trade
For fill
Depleted passive orders (
At snapshot or step N/A for spread and mid price):
Book depth at price level
Volume Weighted Average Price over N/A when total volume is
For buyers with private valuations
Realized surplus over
Sorting buyer valuations non increasingly (
Smith's Allocative Efficiency (for N/A when
Raw order files (raw_orders.csv) use the header timestamp,order_id,side,order_type,price,quantity. Every record is checked against seven deterministic rules before matching:
timestamp: integer strictly greater than0.order_id: non empty string, strictly unique within the file.side: exact match in{"BUY", "SELL"}.order_type: exact match in{"LIMIT", "MARKET"}.price(LIMIT): valid number strictly greater than0.price(MARKET): empty/none (numeric price on a market order is rejected).quantity: integer strictly greater than0.
clean_orders.csv: valid orders sorted by ascendingtimestamp(with deterministic tie breaking).rejected_orders.log: rejected rows with row/order reference and failure reason (plus stdout summary stats on row counts, volumes, andLIMITmin/max/mean prices).trades.csv: sequential execution log (trade_id,buy_order_id,sell_order_id,execution_price,executed_quantity).book_final_state.txt: remaining resting orders in priority order and final bid ask spread (orN/A).zi_results.csv: trade series, price trajectory, and Smith efficiency across horizons.
- Assign private valuations
$V_i \in [P_{\min}, P_{\max}]$ to$N_b$ buyers and private costs$C_j \in [P_{\min}, P_{\max}]$ to$N_s$ sellers. - Over
$T$ turns, select an agent and generate a budget constrained order:BUYprice in$[P_{\min}, V_i]$ orSELLprice in$[C_j, P_{\max}]$ . - Submit each generated order to the deterministic CDA matching engine.
- Record trade/price trajectories and compute VWAP,
$\Pi_{\text{real}}$ ,$\Pi_{\max}$ , and$E_{\text{Smith}}$ across horizons (such as$T = 50, 200, 1000$ ).
cda-engine/
├── README.md
├── data/
│ ├── raw_orders.csv
│ └── incoming_orders.csv
├── src/
│ ├── __init__.py
│ ├── validator.py
│ ├── order.py
│ ├── book.py
│ ├── matching.py
│ ├── metrics.py
│ └── zi_simulation.py
└── tests/
├── test_validator.py
├── test_order_priority.py
└── test_matching.py
-
Stream Validation (
validator.py): Parseraw_orders.csv, enforce rules and unique IDs, sort valid rows intoclean_orders.csv, log rejections torejected_orders.log, and print summary statistics. -
Automated Testing (
pytest): Test validation boundaries, empty/malformed inputs, and price time priority using temporary files and unit tests. -
Book & Matching Engine (
order.py,book.py,matching.py): ModelOrderand two sided queues with FIFO priority, handle partial/multi level fills and volume conservation, and writetrades.csvandbook_final_state.txt. -
ZI Microstructure Study (
metrics.py,zi_simulation.py): Run constrained ZI simulations across horizons$T$ and evaluate VWAP, realized surplus, maximum surplus, and Smith efficiency.
pytest -v
python3 -m src.validator data/raw_orders.csv
python3 -m src.matching data/incoming_orders.csv
python3 -m src.zi_simulation --turns 50 200 1000 --seed 42- Single instrument scope; no explicit order cancellations or amendments; discrete step timestamps without network latency.
- Zero intelligence agents have no learning or strategic behavior; run multiple random seeds to evaluate statistical dispersion across horizons
$T$ . - Keep this
README.mdupdated incrementally as each module and test suite is completed.
- ZI Microstructure Study (metrics.py, zi_simulation.py): Run constrained ZI simulations across horizons T and evaluate VWAP, realized surplus, maximum surplus, and Smith efficiency.