A real-time order book visualization and matching engine simulator built with Python. This project implements the core data structures and algorithms that power modern electronic trading systems—the kind of infrastructure that processes millions of orders per second at exchanges worldwide.
OrderBook simulates a limit order book, the fundamental mechanism used by financial exchanges to match buyers and sellers. The system:
- Accepts orders (buy/sell limit orders and market orders)
- Matches trades using price-time priority (best price wins, then first-in-first-out)
- Visualizes the market in real-time through a terminal UI showing bid/ask depth, spreads, and trade history
- Simulates market activity with configurable random order flow and market-making behavior
This is useful for:
- Understanding how financial exchanges work under the hood
- Experimenting with order matching algorithms
- Visualizing market microstructure dynamics
- Learning about data structures optimized for trading systems
| Technology | Purpose |
|---|---|
| Python 3.11+ | Modern Python with type hints for clarity and correctness |
| Textual | Rich terminal UI framework for real-time visualization without a browser |
| sortedcontainers | O(log n) sorted data structures for efficient price-level management |
| pytest | Comprehensive test suite (180 tests) ensuring correctness |
Why these choices?
- Textual provides a modern TUI that runs anywhere Python runs—no web server, no browser, just a terminal
- sortedcontainers uses B-trees internally, giving O(log n) insertions with O(1) access to best prices—critical for matching engine performance
- Decimal arithmetic throughout prevents the floating-point errors that can cause real financial bugs
# Clone the repository
git clone https://github.com/yourusername/orderbook.git
cd orderbook
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Or install as a package
pip install -e .Launch the terminal UI for manual order entry:
python -m orderbook.mainUse the order entry form to submit buy/sell orders and watch the order book update in real-time.
Generate random order flow to see the market in action:
python -m orderbook.main --simulateCustomize simulation parameters:
# Higher order rate (20 orders/second) and different base price
python -m orderbook.main --simulate --rate 20 --price 50.00| Key | Action |
|---|---|
q |
Quit |
r |
Refresh display |
from decimal import Decimal
from orderbook import MatchingEngine, Side
# Create engine
engine = MatchingEngine()
# Submit limit orders
engine.submit_limit_order(Side.BUY, Decimal("99.50"), Decimal("100"))
engine.submit_limit_order(Side.SELL, Decimal("100.50"), Decimal("50"))
# Submit a market order that crosses the spread
result = engine.submit_market_order(Side.BUY, Decimal("30"))
# Check the trade
for trade in result.trades:
print(f"Traded {trade.quantity} @ {trade.price}")
# View order book state
snapshot = engine.order_book.get_depth(levels=5)
print(f"Spread: {snapshot.spread}, Mid: {snapshot.mid_price}")orderbook/
├── __init__.py # Package exports
├── models.py # Data models: Order, Trade, Side, OrderStatus
├── engine.py # OrderBook + MatchingEngine + MetricsTracker
├── simulation.py # OrderFlowSimulator + MarketMaker
├── main.py # CLI entry point
└── ui/
├── __init__.py
└── app.py # Textual TUI application
tests/
├── unit/ # Unit tests for each component
│ ├── test_task_1_setup.py
│ ├── test_task_2_models.py
│ ├── test_task_3_orderbook.py
│ ├── test_task_4_matching.py
│ ├── test_task_5_simulation.py
│ ├── test_task_6_ui_layout.py
│ ├── test_task_7_ui_forms.py
│ ├── test_task_8_metrics.py
│ └── test_task_9_main.py
└── integration/ # End-to-end workflow tests
└── test_integration.py
The matching engine implements price-time priority:
- Price Priority: Better prices match first (higher bids, lower asks)
- Time Priority: At the same price, earlier orders match first (FIFO)
Incoming Buy @ $100 for 50 shares matches against:
- Sell @ $99 (10 shares) → fills 10 @ $99
- Sell @ $100 (30 shares) → fills 30 @ $100
- Remaining 10 shares rest in book @ $100
- SortedDict for bid/ask price levels: O(log n) insert/delete, O(1) best price access
- Lists at each price level: O(1) FIFO append, O(n) remove (acceptable for time priority)
- Dict for order ID lookup: O(1) cancel operations
| Type | Behavior |
|---|---|
| Limit | Matches at specified price or better; unfilled quantity rests in book |
| Market | Fills immediately at best available prices; unfilled portion is cancelled |
# Run all tests
pytest
# Run with verbose output
pytest -v
# Run specific test file
pytest tests/unit/test_task_4_matching.py
# Run with coverage
pytest --cov=orderbook- Decimal over float: Prevents accumulating rounding errors in financial calculations
- Immutable-ish design: Orders track their own state; modifications create clear audit trail
- Separation of concerns: OrderBook manages data structure, MatchingEngine handles business logic
- Async-ready simulation: Simulator uses asyncio for non-blocking order generation
MIT