This project implements a high-performance order matching engine for financial trading systems. Built with Python, FastAPI, and WebSockets, it provides real-time order matching with price-time priority (FIFO) and supports multiple order types including Market, Limit, IOC (Immediate-Or-Cancel), and FOK (Fill-Or-Kill).
e:/MatchingEngine/
├── matching_engine_core.py # Core matching engine implementation
├── matching_engine.py # Compatibility shim for imports
├── api.py # API package redirect
├── api/
│ ├── __init__.py # API package initialization
│ └── app.py # FastAPI server with REST and WebSocket endpoints
├── UI/
│ └── index.html # Web-based control panel and order book viewer
├── Tests/
│ └── test_matching_engine.py # Comprehensive unit tests
├── data/
│ └── engine_state.json # Persistent order book state
├── demo_client.py # Interactive demo script
├── test_api.py # Simple API test script
├── run.py # Server startup script
├── requirements.txt # Python dependencies
└── project_files.txt # Legacy project description
The matching engine is designed as a high-performance, real-time order matching system for financial trading, built with a layered architecture to ensure scalability, reliability, and low latency. The system follows a microservices-inspired approach within a single process, separating concerns into core matching logic, API layer, and persistence.
-
Core Engine Layer (
matching_engine_core.py):- Pure business logic for order matching, order book management, and trade execution.
- Stateless except for in-memory order books, allowing horizontal scaling if needed.
- Uses async primitives for concurrency without external dependencies.
-
API Layer (
api/app.py):- RESTful HTTP endpoints for order submission, cancellation, and queries.
- WebSocket endpoints for real-time streaming of market data and trades.
- Input validation, error handling, and serialization/deserialization.
-
Persistence Layer:
- JSON-based state persistence for order books on startup/shutdown.
- Designed for simplicity; can be extended to databases for production use.
-
Web UI Layer (
UI/index.html):- Client-side interface for demonstration and manual testing.
- Connects to WebSocket streams for live updates.
- In-Memory Processing: All order books reside in memory for sub-millisecond access times. This choice prioritizes speed over durability, with persistence as a backup mechanism.
- Per-Symbol Isolation: Each symbol has its own order book and lock, minimizing contention and allowing parallel processing across symbols.
- Event-Driven Notifications: Listener callbacks for trades and book updates enable real-time broadcasting without polling.
- Async-First: Built on asyncio for non-blocking I/O, supporting high throughput without thread overhead.
- Type Safety: Extensive use of type hints and Pydantic models to catch errors at development time.
- Extensibility: Modular design allows adding new order types, fee models, or risk checks without core rewrites.
The central orchestrator that manages multiple order books:
- Order Books: Dictionary mapping symbols to
OrderBookinstances. - Locks: Per-symbol asyncio.Lock for thread-safe concurrent access.
- Listeners: Callback functions for trade executions and order book changes.
- Metrics: Rolling statistics on order processing times and counts.
- Persistence: JSON serialization for state recovery across restarts.
Encapsulates the order book for a single trading symbol:
- Bids/Asks: SortedDict for price-sorted access to price levels.
- Price Levels: Dictionary of
PriceLevelobjects keyed by price. - Order Map: Hash map for O(1) order lookups by ID.
- BBO Calculation: Efficient best bid/ask queries.
Groups orders at the same price level:
- Orders: Deque for FIFO order processing.
- Total Quantity: Cached aggregate for fast liquidity checks.
- Order: Immutable dataclass holding order metadata (ID, symbol, side, type, price, quantity, timestamp).
- Trade: Dataclass representing executed trades, including fees and aggressor side.
- Data Structures (detailed in dedicated section below).
- Concurrency Model: Per-symbol locking avoids global locks, enabling concurrent processing of different symbols while ensuring consistency within each.
- Matching Algorithm: Price-time priority ensures fair execution; supports complex order types like IOC/FOK.
- Persistence Strategy: Simple JSON files for development; trade-off of simplicity vs. performance for production databases.
- Real-Time Updates: WebSocket broadcasting for low-latency client notifications.
The order book's data structures are carefully chosen to balance performance, memory efficiency, and correctness for high-frequency trading scenarios.
- Implementation:
SortedDict[Decimal, PriceLevel]for bids and asks - Rationale:
- Provides O(log n) insertion, deletion, and ordered iteration
- Maintains price-sorted order automatically (ascending for asks, descending for bids via reverse iteration)
- More memory-efficient than balanced binary trees for typical order book depths (10-100 levels)
- Faster than heap-based approaches for frequent insertions/deletions
- Trade-offs: Slower than hash maps for random access, but necessary for price-based ordering
- Implementation:
deque[Order]within each PriceLevel - Rationale:
- O(1) append and popleft operations for FIFO processing
- Memory-efficient linked structure prevents array resizing overhead
- Supports time-based priority at same price level
- Trade-offs: No random access (not needed for FIFO), slightly higher memory per element than list
- Implementation:
Dict[str, Tuple[Decimal, PriceLevel, Order]](order_map) - Rationale:
- O(1) average-case lookup by order_id for cancellations
- Enables fast order removal without scanning price levels
- Stores reference tuple for efficient updates
- Trade-offs: Additional memory overhead, but critical for O(1) cancellations
- Implementation: Python's
decimal.Decimalwith 18-digit precision - Rationale:
- Avoids floating-point precision errors in financial calculations
- Supports exact decimal arithmetic required for trading
- Configurable precision prevents rounding surprises
- Trade-offs: Slower than float operations, but essential for financial accuracy
- Price-Time Priority: SortedDict ensures best prices are matched first; deque ensures FIFO at same price
- Memory Efficiency: Lazy allocation of PriceLevel objects; cached total quantities avoid summation
- Concurrency Safety: Per-symbol isolation allows lock-free reads for different symbols
- Scalability: Data structures scale well to thousands of orders per symbol
- SortedDict vs. Heap: SortedDict chosen over heap for better average-case performance and easier iteration
- Deque vs. List: Deque prevents O(n) shifts during FIFO operations
- In-Memory vs. Database: In-memory chosen for latency; persistence via JSON for simplicity
- Rest on the order book at specified price
- Match when opposite side crosses the price
- Remain on book until filled or cancelled
- Execute immediately at best available prices
- Consume liquidity across multiple price levels
- No price limit - will take whatever is available
- Execute immediately for available quantity
- Cancel any unfilled portion
- Useful for "fill what you can" scenarios
- Execute only if entire quantity can be filled immediately
- Cancel completely if insufficient liquidity
- All-or-nothing execution
The matching engine provides a comprehensive REST API and WebSocket streaming interface for order management and market data access.
Submit a new order to the matching engine.
Request Body Schema:
{
"symbol": "string (required, e.g., 'BTC-USDT')",
"order_type": "string (required, enum: 'market', 'limit', 'ioc', 'fok')",
"side": "string (required, enum: 'buy', 'sell')",
"quantity": "string (required, decimal string, e.g., '0.5')",
"price": "string (optional for limit/ioc/fok, decimal string, e.g., '50000.0')"
}Success Response (200):
{
"order_id": "string (UUID)",
"status": "string ('accepted')",
"symbol": "string",
"side": "string",
"order_type": "string",
"quantity": "string (remaining quantity)",
"price": "string|null",
"timestamp": "string (ISO 8601)"
}Error Responses:
400 Bad Request: Invalid parameters, missing required fields, invalid decimals422 Unprocessable Entity: Pydantic validation errors500 Internal Server Error: Unexpected errors
Validation Rules:
- Quantity must be positive decimal
- Price required for limit/ioc/fok orders, must be positive
- Symbol, side, order_type must match allowed values
Cancel an existing order by ID.
Request Body Schema:
{
"symbol": "string (required)",
"order_id": "string (required, UUID format)"
}Success Response (200):
{
"status": "string ('cancelled')",
"order_id": "string"
}Error Responses:
404 Not Found: Order not found or already filled/cancelled500 Internal Server Error: Unexpected errors
Retrieve current order book snapshot for a symbol.
Path Parameters:
symbol: Trading symbol (e.g., 'BTC-USDT')
Query Parameters:
depth(optional): Number of price levels to return (default: 10, max: 50)
Success Response (200):
{
"symbol": "string",
"bbo": {
"bid": ["string (price)", "string (quantity)"] | null,
"ask": ["string (price)", "string (quantity)"] | null
},
"asks": [["string (price)", "string (total qty)"], ...],
"bids": [["string (price)", "string (total qty)"], ...]
}Notes:
- Prices and quantities returned as decimal strings
- Asks sorted ascending by price, bids sorted descending
- BBO shows best bid/ask prices and total quantities at those levels
- Empty order book returns null BBO and empty arrays
Retrieve performance and operational metrics.
Success Response (200):
{
"total_orders": "integer (cumulative orders processed)",
"total_trades": "integer (cumulative trades executed)",
"avg_processing_ms": "float (rolling average processing time)",
"p50_ms": "float (median processing time)",
"p95_ms": "float (95th percentile processing time)",
"samples": "integer (number of timing samples)"
}Real-time order book update stream.
Connection: WebSocket at ws://localhost:8000/ws/marketdata
Incoming Messages: None (streaming only)
Outgoing Message Format:
{
"type": "orderbook",
"timestamp": "string (ISO 8601 or event loop time)",
"symbol": "string",
"bbo": {
"bid": ["string (price)", "string (quantity)"] | null,
"ask": ["string (price)", "string (quantity)"] | null
},
"asks": [["string (price)", "string (total qty)"], ...],
"bids": [["string (price)", "string (total qty)"], ...]
}Connection Management:
- Server sends periodic ping messages for keep-alive
- Client should respond with any message to maintain connection
- Connection times out after 60 seconds of inactivity
Real-time trade execution stream.
Connection: WebSocket at ws://localhost:8000/ws/trades
Incoming Messages: None (streaming only)
Outgoing Message Format:
{
"type": "trade",
"trade_id": "string (UUID)",
"timestamp": "string (ISO 8601)",
"symbol": "string",
"price": "string (execution price)",
"quantity": "string (filled quantity)",
"aggressor_side": "string ('buy' or 'sell')",
"maker_order_id": "string (UUID)",
"taker_order_id": "string (UUID)",
"maker_fees": "string (optional, fee amount)",
"taker_fees": "string (optional, fee amount)"
}Notes:
- Each trade message represents one execution between maker and taker orders
- Fees are included when fee rates are configured (> 0)
- Messages are broadcast immediately upon trade execution
All endpoints follow consistent error response patterns:
- HTTP status codes indicate error categories
- Response bodies contain descriptive error messages
- Validation errors provide specific field-level feedback
- Internal errors are logged with correlation IDs for debugging
Currently no rate limiting implemented. For production use, consider:
- Per-client rate limits on order submission
- Burst allowances for high-frequency trading
- IP-based throttling for API protection
- Python 3.8+
- pip package manager
-
Clone or navigate to project directory:
cd e:/MatchingEngine -
Create virtual environment:
python -m venv venv venv\Scripts\activate # Windows # source venv/bin/activate # Linux/Mac
-
Install dependencies:
pip install -r requirements.txt
# Using run.py
python run.py
# Or directly with uvicorn
uvicorn api.app:app --reload --host 0.0.0.0 --port 8000The server will start at http://localhost:8000
Once running, visit:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - Web UI:
http://localhost:8000/UI/index.html
Run the comprehensive test suite:
# Run all tests
pytest Tests/ -v
# Run with coverage
pytest Tests/ -v --cov=matching_engine_core
# Run specific test class
pytest Tests/test_matching_engine.py::TestBasicOrderMatching -vThe test suite covers:
- Basic limit order matching
- Market order execution across multiple levels
- FIFO priority at same price
- IOC partial fills and cancellations
- FOK all-or-nothing behavior
- Order cancellation
- BBO (Best Bid/Offer) updates
- Edge cases and error conditions
- Concurrent processing across symbols
Use the simple test script:
python test_api.pyOpen UI/index.html in a browser for:
- Demo Mode: Pre-built scenarios showing different order types
- Manual Mode: Interactive order placement and cancellation
- Real-time Order Book: Live updates via WebSocket
- Console Output: Step-by-step execution logs
Run the Python demo client:
python demo_client.pyThis demonstrates:
- Basic Matching: Limit orders building the book, market order execution
- FIFO Priority: Multiple orders at same price, time-based execution
- IOC/FOK Orders: Special order type behaviors
- Cancellation: Order removal from the book
- Places buy orders at different prices
- Places sell orders at different prices
- Executes market buy that sweeps multiple levels
- Places 3 buy orders at same price (different times)
- Places matching sell order
- Demonstrates first-in-first-out execution
- Tests IOC partial execution
- Tests FOK failure (insufficient liquidity)
- Tests FOK success (exact match)
- Places multiple orders
- Demonstrates cancellation functionality
- Shows order book updates
- Validation: Check order parameters and types
- Creation: Generate UUID and create Order dataclass
- Locking: Acquire symbol-specific lock
- Processing: Call
_process_orderfor matching logic - Notification: Broadcast trade and book updates
- Metrics: Record processing time
The _process_order method implements the core price-time priority matching logic with support for all order types. Here's the detailed step-by-step implementation:
-
FOK Pre-Validation:
- For Fill-Or-Kill orders, scan opposite side price levels to calculate total available liquidity
- Sum quantities across all acceptable price levels (considering order side and limit price)
- If total available < required quantity, return empty trades list (order rejected)
-
Price Level Iteration:
- Determine iteration direction: ascending for asks (sell side), descending for bids (buy side)
- Use SortedDict.irange() for efficient ordered traversal
- For each price level, check if it satisfies price acceptance criteria
-
Price Acceptance Logic:
- Market Orders: Accept any price (always True)
- Buy Limit Orders: Accept prices ≤ limit price
- Sell Limit Orders: Accept prices ≥ limit price
-
FIFO Quantity Matching:
- Within each acceptable price level, process orders in FIFO order (deque.popleft())
- Calculate fill quantity: min(remaining incoming quantity, available maker quantity)
- Update both incoming and maker order quantities
- Generate trade record with execution details
-
Trade Generation:
- Create Trade dataclass with UUID, timestamp, symbol, execution price/quantity
- Identify aggressor side (incoming order side)
- Link maker and taker order IDs
- Calculate and attach maker/taker fees using configured rates
-
Order Book Updates:
- Remove completely filled maker orders from deque and order_map
- Update PriceLevel total_qty cache
- Remove empty price levels from SortedDict
- For IOC orders: stop after first partial fill, cancel remainder
- For FOK: guaranteed full fill or complete rejection
-
Resting Order Placement:
- If incoming order has remaining quantity and is limit type
- Add to appropriate price level (create if needed)
- Update order_map for fast cancellation lookup
Key Implementation Notes:
- All operations are atomic within the symbol-specific async lock
- Decimal arithmetic ensures precision in financial calculations
- Event listeners are called for each trade and book update
- Processing time is measured for performance metrics
- save_state(): Serializes order books to JSON
- load_state(): Restores order books from JSON
- Automatic save on shutdown, load on startup
- CORS: Enabled for web UI access
- Global Engine: Single MatchingEngine instance
- Broadcasters: WebSocket managers for market data and trades
- Validation: Pydantic models for type safety
- Error Handling: Comprehensive exception catching
- Async Processing: Non-blocking order submission
- Connection Handling: Accept/reject client connections
- Broadcasting: Async queue-based message distribution
- Heartbeat: Keep-alive pings for connection stability
- Vanilla JavaScript: No frameworks for simplicity
- Real-time Updates: WebSocket connections for live data
- Responsive Design: Mobile-friendly interface
- Demo Scenarios: Guided tutorials for each concept
- Mode Switching: Demo vs Manual operation
- Order Placement: Form-based order submission
- Order Book Display: Real-time visualization
- Console Logging: Step-by-step execution feedback
- Throughput: >1,000 orders/second
- Latency: <10ms average processing time
- Scalability: Linear scaling with CPU cores
- Async Processing: Non-blocking I/O operations
- Efficient Data Structures: O(1) queue operations, O(log n) price access
- Lock Granularity: Per-symbol locking minimizes contention
- Memory Management: Deque-based queues prevent memory leaks
- Metrics Endpoint:
/metricsfor performance statistics - Processing Times: Rolling average and percentiles
- Order/Trade Counts: Total and rate calculations
# In MatchingEngine.__init__
self.maker_fee_rate = Decimal('0.001') # 0.1% maker fee
self.taker_fee_rate = Decimal('0.002') # 0.2% taker fee# Global decimal precision
getcontext().prec = 18 # 18 decimal places# In api/app.py
market_data_broadcaster = Broadcaster()
trade_broadcaster = Broadcaster()-
Import Errors
- Ensure
PYTHONPATHincludes project root - Check virtual environment activation
- Ensure
-
WebSocket Connection Issues
- Verify server is running on correct port
- Check firewall settings
- Ensure browser supports WebSockets
-
Order Book Persistence
- Check write permissions for
data/directory - Verify JSON file format if manually edited
- Check write permissions for
-
Performance Issues
- Monitor metrics endpoint for bottlenecks
- Consider uvloop for better async performance
- Check system resources (CPU, memory)
Run server with debug logging:
uvicorn api.app:app --reload --log-level debug- Database Persistence: PostgreSQL/SQLite backend
- Authentication: User sessions and API keys
- Advanced Order Types: Stop-loss, trailing stops
- Risk Management: Position limits, margin requirements
- Market Data: Historical data and analytics
- Load Balancing: Horizontal scaling support
- Rust/C++ Extensions: Critical path optimization
- Redis Integration: Distributed caching
- Message Queues: Async order processing
- Profiling Tools: Performance monitoring suite
- Fork the repository
- Create feature branch
- Make changes with tests
- Run full test suite
- Submit pull request
- Type Hints: Full type annotation coverage
- Docstrings: Comprehensive documentation
- Testing: 100% test coverage target
- Linting: Follow PEP 8 standards
MIT License - Free for educational and commercial use.
This documentation provides a comprehensive guide to understanding, running, and extending the matching engine project. For questions or contributions, please refer to the code comments and test cases for detailed implementation insights.