Skip to main content

Order Book Matching Engine

pytest !pypi !python-versions pre-commit Ruff

Overview

This repository provides a high-performance order book matching engine implemented in Python, complete with a RESTful API layer and a real-time interactive simulation dashboard. Its main features are:

  • Core Engine: Price-time priority matching supporting limit/market orders, order cancellation, and expiration.
  • Market Simulation: A discrete-time state-passing simulation framework featuring registered trading agents (such as Poisson-arrival NoiseTrader entities), an event-driven NewsFeed, and a read-only MarketView proxy wrapper.
  • REST API: FastAPI server for remote order placement, manual or automated matching/simulation runs, and engine controls.
  • Web UI: Modern glassmorphic SPA dashboard featuring an integrated live-updating market simulation, manual order entry/cancellation, trades list, interactive SVG depth chart, and real-time OHLC candlestick chart visualization.
  • Data Export: Direct conversion of order books, trades, and summary states into Polars LazyFrames (optional dependency).

Install

# Core matching engine only
pip install order-matching

# With polars export support (recommended for data science workflows)
pip install order-matching[polars]

# With REST API and Web UI simulation support
pip install order-matching[web]

# Install all optional dependencies (polars + web)
pip install order-matching[all]

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.enums 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 & Frontend

For demo, education, and backtesting workflows, a RESTful API layer and simple UI frontend are provided.

Running frontend and API server

Start the API server and frontend using the fastapi CLI:

uv run fastapi dev

Or run with uvicorn:

uv run uvicorn order_matching.api.app:app --reload

Interactive Dashboard UI

The API server mounts a modern, glassmorphic dark-theme Single Page Application (SPA) dashboard available at the root URL: http://127.0.0.1:8000 (redirects to /ui).

Features include:

  • Live Market Simulation: The dashboard runs an active market simulation with a pool of preconfigured automated traders placing orders organically at random intervals. Manual orders placed via the UI match and execute directly against these automated traders.
  • Engine Control & Pause/Resume: The automated matching runs and the simulation steps run every second by default. They can be paused or resumed dynamically using the clickable Engine Status button in the header, freezing the simulated market state.
  • Order Placement & Cancellation: Easily place new limit or market orders manually and cancel outstanding orders in real-time.
  • Depth Chart Visualization: An interactive, responsive SVG cumulative depth chart with vertical cursor tracking and detailed hover tooltips.
  • Candlestick Chart Visualization: Real-time OHLC (Open, High, Low, Close) candlestick chart powered by Lightweight Charts with configurable time intervals (5s, 15s, 30s, 1m), zoom, pan, and crosshair interactions for visualizing price evolution during simulation runs.
  • Real-Time Feeds: Auto-refreshing logs of outstanding orders, recent trade ticks, current bid-ask spread, and top bid/ask levels.
  • Market Reset: Modal controls to clear the entire market state and restart the simulation from scratch, with support for random seed specification.

API Endpoints

Explore interactive API docs at http://127.0.0.1:8000/docs.

  • 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 optional from_timestamp query filter).
  • DELETE /orders/{order_id}: Cancel an active order by ID.
  • POST /reset: Reset the engine state (with optional random seed).
  • GET /summary: Retrieve aggregated order book price levels (matching OrderBook.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.

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

Metadata

Release files for order-matching 0.11.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for order-matching 0.11.0
File Size Uploaded
order_matching-0.11.0.tar.gz 37.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for order-matching 0.11.0
File Interpreter ABI Platform
order_matching-0.11.0-py3-none-any.whl Python 3 none any Details

Total release size: 92.2 kB

Release files / order_matching-0.11.0.tar.gz

Download URL order_matching-0.11.0.tar.gz
Size 37.9 kB
Tags Source
SHA-256 checksum
How to use checksums
4a86b279d2daceb3a147f11145915aaf146b12213f9e694ee9b10a2403e919f4
BLAKE2b-256 checksum
How to use checksums
3b1ef2f62123398b44945fb992e707172a0e8241d2895c915bbe9f4c5fc728a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.32 {"installer":{"name":"uv","version":"0.11.32","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}

Release files / order_matching-0.11.0-py3-none-any.whl

Download URL order_matching-0.11.0-py3-none-any.whl
Size 54.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
81aa2b75fe617788fdf309efb0c2d7b5b62eac6a9da7dd6bcf143bd4da84225c
BLAKE2b-256 checksum
How to use checksums
61efaa9b815814e1dc8042e824196db5e347e495249f667d579dbb67dd60e46e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.32 {"installer":{"name":"uv","version":"0.11.32","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}

Release history Release notifications | RSS feed

0.12.0

2 release files

This release

0.11.0 This release

2 release files

0.10.0

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.12

2 release files

0.3.9

2 release files

0.3.8

2 release files

0.3.7

2 release files

0.3.6

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page