Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Matching Engine Project Documentation

Overview

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).

Project Structure

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

System Architecture and Design Choices

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.

Layered Architecture

  1. 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.
  2. 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.
  3. Persistence Layer:

    • JSON-based state persistence for order books on startup/shutdown.
    • Designed for simplicity; can be extended to databases for production use.
  4. Web UI Layer (UI/index.html):

    • Client-side interface for demonstration and manual testing.
    • Connects to WebSocket streams for live updates.

Design Choices

  • 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.

Core Components

1. MatchingEngine Class (matching_engine_core.py)

The central orchestrator that manages multiple order books:

  • Order Books: Dictionary mapping symbols to OrderBook instances.
  • 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.

2. OrderBook Class

Encapsulates the order book for a single trading symbol:

  • Bids/Asks: SortedDict for price-sorted access to price levels.
  • Price Levels: Dictionary of PriceLevel objects keyed by price.
  • Order Map: Hash map for O(1) order lookups by ID.
  • BBO Calculation: Efficient best bid/ask queries.

3. PriceLevel Class

Groups orders at the same price level:

  • Orders: Deque for FIFO order processing.
  • Total Quantity: Cached aggregate for fast liquidity checks.

4. Order and Trade Dataclasses

  • Order: Immutable dataclass holding order metadata (ID, symbol, side, type, price, quantity, timestamp).
  • Trade: Dataclass representing executed trades, including fees and aggressor side.

Key Design Decisions

  1. Data Structures (detailed in dedicated section below).
  2. Concurrency Model: Per-symbol locking avoids global locks, enabling concurrent processing of different symbols while ensuring consistency within each.
  3. Matching Algorithm: Price-time priority ensures fair execution; supports complex order types like IOC/FOK.
  4. Persistence Strategy: Simple JSON files for development; trade-off of simplicity vs. performance for production databases.
  5. Real-Time Updates: WebSocket broadcasting for low-latency client notifications.

Data Structures Used for the Order Book and Their Rationale

The order book's data structures are carefully chosen to balance performance, memory efficiency, and correctness for high-frequency trading scenarios.

Core Data Structures

1. SortedDict for Price Levels

  • 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

2. Deque for FIFO Order Queues

  • 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

3. Hash Map for Order Lookup

  • 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

4. Decimal for Financial Precision

  • Implementation: Python's decimal.Decimal with 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

Design Rationale

  • 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

Alternative Considerations

  • 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

Order Types

1. Limit Orders

  • Rest on the order book at specified price
  • Match when opposite side crosses the price
  • Remain on book until filled or cancelled

2. Market Orders

  • Execute immediately at best available prices
  • Consume liquidity across multiple price levels
  • No price limit - will take whatever is available

3. IOC (Immediate-Or-Cancel)

  • Execute immediately for available quantity
  • Cancel any unfilled portion
  • Useful for "fill what you can" scenarios

4. FOK (Fill-Or-Kill)

  • Execute only if entire quantity can be filled immediately
  • Cancel completely if insufficient liquidity
  • All-or-nothing execution

API Specifications

The matching engine provides a comprehensive REST API and WebSocket streaming interface for order management and market data access.

REST Endpoints

POST /orders

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 decimals
  • 422 Unprocessable Entity: Pydantic validation errors
  • 500 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

POST /cancel

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/cancelled
  • 500 Internal Server Error: Unexpected errors

GET /orderbook/{symbol}

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

GET /metrics

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)"
}

WebSocket Endpoints

/ws/marketdata

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

/ws/trades

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

Error Handling

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

Rate Limiting

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

Installation and Setup

Prerequisites

  • Python 3.8+
  • pip package manager

Installation Steps

  1. Clone or navigate to project directory:

    cd e:/MatchingEngine
  2. Create virtual environment:

    python -m venv venv
    venv\Scripts\activate  # Windows
    # source venv/bin/activate  # Linux/Mac
  3. Install dependencies:

    pip install -r requirements.txt

Running the Application

Start the API Server

# Using run.py
python run.py

# Or directly with uvicorn
uvicorn api.app:app --reload --host 0.0.0.0 --port 8000

The server will start at http://localhost:8000

API Documentation

Once running, visit:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • Web UI: http://localhost:8000/UI/index.html

Testing

Unit Tests

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 -v

Test Coverage

The 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

API Testing

Use the simple test script:

python test_api.py

Demo Scenarios

Interactive Web UI

Open 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

Demo Client Script

Run the Python demo client:

python demo_client.py

This demonstrates:

  1. Basic Matching: Limit orders building the book, market order execution
  2. FIFO Priority: Multiple orders at same price, time-based execution
  3. IOC/FOK Orders: Special order type behaviors
  4. Cancellation: Order removal from the book

Demo Scenarios Details

Scenario 1: Basic Limit Order Matching

  • Places buy orders at different prices
  • Places sell orders at different prices
  • Executes market buy that sweeps multiple levels

Scenario 2: FIFO Priority

  • Places 3 buy orders at same price (different times)
  • Places matching sell order
  • Demonstrates first-in-first-out execution

Scenario 3: IOC and FOK Orders

  • Tests IOC partial execution
  • Tests FOK failure (insufficient liquidity)
  • Tests FOK success (exact match)

Scenario 4: Order Cancellation

  • Places multiple orders
  • Demonstrates cancellation functionality
  • Shows order book updates

Code Walkthrough

Core Matching Logic (matching_engine_core.py)

Order Submission Flow

  1. Validation: Check order parameters and types
  2. Creation: Generate UUID and create Order dataclass
  3. Locking: Acquire symbol-specific lock
  4. Processing: Call _process_order for matching logic
  5. Notification: Broadcast trade and book updates
  6. Metrics: Record processing time

Matching Algorithm Implementation Details

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:

  1. 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)
  2. 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
  3. Price Acceptance Logic:

    • Market Orders: Accept any price (always True)
    • Buy Limit Orders: Accept prices ≤ limit price
    • Sell Limit Orders: Accept prices ≥ limit price
  4. 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
  5. 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
  6. 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
  7. 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

Data Persistence

  • save_state(): Serializes order books to JSON
  • load_state(): Restores order books from JSON
  • Automatic save on shutdown, load on startup

API Layer (api/app.py)

FastAPI Setup

  • CORS: Enabled for web UI access
  • Global Engine: Single MatchingEngine instance
  • Broadcasters: WebSocket managers for market data and trades

Request Handling

  • Validation: Pydantic models for type safety
  • Error Handling: Comprehensive exception catching
  • Async Processing: Non-blocking order submission

WebSocket Management

  • Connection Handling: Accept/reject client connections
  • Broadcasting: Async queue-based message distribution
  • Heartbeat: Keep-alive pings for connection stability

Web UI (UI/index.html)

Architecture

  • 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

Features

  • 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

Performance Characteristics

Target Metrics

  • Throughput: >1,000 orders/second
  • Latency: <10ms average processing time
  • Scalability: Linear scaling with CPU cores

Optimizations

  • 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

Monitoring

  • Metrics Endpoint: /metrics for performance statistics
  • Processing Times: Rolling average and percentiles
  • Order/Trade Counts: Total and rate calculations

Configuration and Customization

Fee Structure

# 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

Precision Settings

# Global decimal precision
getcontext().prec = 18  # 18 decimal places

WebSocket Settings

# In api/app.py
market_data_broadcaster = Broadcaster()
trade_broadcaster = Broadcaster()

Troubleshooting

Common Issues

  1. Import Errors

    • Ensure PYTHONPATH includes project root
    • Check virtual environment activation
  2. WebSocket Connection Issues

    • Verify server is running on correct port
    • Check firewall settings
    • Ensure browser supports WebSockets
  3. Order Book Persistence

    • Check write permissions for data/ directory
    • Verify JSON file format if manually edited
  4. Performance Issues

    • Monitor metrics endpoint for bottlenecks
    • Consider uvloop for better async performance
    • Check system resources (CPU, memory)

Debug Mode

Run server with debug logging:

uvicorn api.app:app --reload --log-level debug

Future Enhancements

Planned Features

  • 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

Performance Improvements

  • Rust/C++ Extensions: Critical path optimization
  • Redis Integration: Distributed caching
  • Message Queues: Async order processing
  • Profiling Tools: Performance monitoring suite

Contributing

Development Setup

  1. Fork the repository
  2. Create feature branch
  3. Make changes with tests
  4. Run full test suite
  5. Submit pull request

Code Standards

  • Type Hints: Full type annotation coverage
  • Docstrings: Comprehensive documentation
  • Testing: 100% test coverage target
  • Linting: Follow PEP 8 standards

License

MIT License - Free for educational and commercial use.

References


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.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages