Order Book Matching Engine
Project description
Order Book Matching Engine
Overview
This package is a simple order book matching engine implementation in Python. Its main features are:
- price-time priority
- limit and market orders
- order cancellation and expiration
- conversion into polars LazyFrame of orders, executed trades, order book summary (optional polars dependency)
Install
# Core matching engine only
pip install order-matching
# With polars export support (recommended for data science workflows)
pip install order-matching[polars]
Documentation
khrapovs.github.io/OrderBookMatchingEngine
Usage
>>> from datetime import datetime, timedelta
>>> from pprint import pp
>>> import polars as pl
>>> from order_matching.matching_engine import MatchingEngine
>>> from order_matching.order import LimitOrder
>>> from order_matching.side import Side
>>> from order_matching.orders import Orders
>>> matching_engine = MatchingEngine(seed=123)
>>> timestamp = datetime(2023, 1, 1)
>>> transaction_timestamp = timestamp + timedelta(days=1)
>>> buy_order = LimitOrder(side=Side.BUY, price=1.2, size=2.3, timestamp=timestamp, order_id="a", trader_id="x")
>>> sell_order = LimitOrder(side=Side.SELL, price=0.8, size=1.6, timestamp=timestamp, order_id="b", trader_id="y")
>>> # Place orders without matching:
>>> matching_engine.place(orders=Orders([buy_order, sell_order]))
>>> # Trigger matching at a specific timestamp:
>>> executed_trades = matching_engine.match(timestamp=transaction_timestamp)
>>> pp(executed_trades.trades)
[Trade(side=SELL,
price=1.2,
size=1.6,
incoming_order_id='b',
book_order_id='a',
execution=LIMIT,
trade_id='c4da537c-1651-4dae-8486-7db30d67b366',
timestamp=datetime.datetime(2023, 1, 2, 0, 0))]
Data Export (Polars)
If you installed with [polars] extra, you can export data to polars LazyFrame:
>>> from order_matching.orders import Orders
>>> from order_matching.executed_trades import ExecutedTrades
>>> from order_matching.exporters.polars import PolarsExporter
>>> exporter = PolarsExporter()
>>> orders_df = exporter.export_orders(Orders())
>>> trades_df = exporter.export_trades(ExecutedTrades())
>>> trades_df = ExecutedTrades().to_frame()
REST API
For demo, education, and backtesting workflows, a RESTful API layer is provided.
Running the API Server
Start the API server in development mode using the fastapi CLI:
uv run fastapi dev
Or run with uvicorn:
uv run uvicorn order_matching.api.app:app --reload
Explore interactive API docs at http://127.0.0.1:8000/docs.
Endpoints
POST /place: Place a batch of one or more orders without triggering matching.POST /match: Trigger matching at a specific timestamp for all queued/placed orders.GET /orders: Retrieve the current unmatched order book state (grouped by price).GET /trades: Retrieve trade execution history (with optionalfrom_timestampquery filter).DELETE /orders/{order_id}: Cancel an active order by ID.POST /reset: Reset the engine state (with optional randomseed).GET /summary: Retrieve aggregated order book price levels (matchingOrderBook.summary()).
API Limitations
- Single-User / Educational Use: The server uses in-memory state and is not thread-safe.
- No Persistence: Restarting the server clears all order book and trade history state.
Related Projects
Contribute
Install project in editable mode and sync all dependencies:
uv sync --all-groups --all-extras
and use pre-commit to make sure that your code is formatted and linted automatically:
uv run prek install
Run tests:
uv run pytest
Run benchmark and see the result either in the terminal or as a plot in benchmark_history.svg:
./benchmark.sh
Build and serve documentation website:
uv run mkdocs serve
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file order_matching-0.6.0.tar.gz.
File metadata
- Download URL: order_matching-0.6.0.tar.gz
- Upload date:
- Size: 14.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
301f3427d1733e6702df75a18ca75b3a75cc4a22f04b1496c3ab89c78c3bfdb6
|
|
| MD5 |
c6eadecb4a14481c43b79869f1c2ca7d
|
|
| BLAKE2b-256 |
453058ad422180ecbfd439aa373fb6f3c21f54fd70c9714d288613382c1679d4
|
File details
Details for the file order_matching-0.6.0-py3-none-any.whl.
File metadata
- Download URL: order_matching-0.6.0-py3-none-any.whl
- Upload date:
- Size: 24.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
70e18af0bde2e0469c8a0ba79b969a322eb9520c201c324129e5d0485bfd1ff1
|
|
| MD5 |
95951ed9390218f7c799f9c89ece1055
|
|
| BLAKE2b-256 |
aa9692110a3a33d8237c644d39b37ef1664067d2487c5ef9d1b323936f02ec43
|