A high-performance cryptocurrency matching engine implementing REG NMS-inspired principles with real-time market data streaming and comprehensive order matching capabilities.
This project implements a production-ready cryptocurrency matching engine that processes orders based on price-time priority and internal order protection principles. The engine supports multiple order types, real-time market data dissemination, and comprehensive trade execution reporting.
- REG NMS Compliance: Implements price-time priority and trade-through protection
- Multiple Order Types: Limit, Market, IOC, FOK order support
- Real-time Data Streaming: WebSocket-based market data and trade feeds
- High Performance: Optimized for low-latency order processing
- REST API: Full order management and market data access
- Comprehensive Testing: Unit tests, integration tests, and performance benchmarks
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β REST API β β Matching Engine β β WebSocket API β
β (Flask) βββββΊβ (Order Book) βββββΊβ (Real-time) β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Order β β Trade β β Market Data β
β Management β β Execution β β Dissemination β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
- Price-Time Priority: Orders at same price level executed in FIFO order
- Internal Order Protection: Prevents trade-throughs by always matching at best available prices
- Real-time Performance: Optimized data structures for low-latency processing
- Extensibility: Modular design for easy addition of new order types and features
Why Python?
- Rapid development and prototyping
- Excellent for financial applications with decimal precision
- Rich ecosystem for networking and data processing
- Suitable for educational and demonstration purposes
Alternative Considered: C++ - Would provide better performance but longer development time.
Why Flask?
- Lightweight and fast
- Easy to extend and customize
- Excellent for microservices architecture
- Simple JSON request/response handling
Why WebSockets?
- Real-time bidirectional communication
- Low latency for market data streaming
- Efficient for high-frequency updates
- Standard in financial applications
Why Decimal instead of float?
- Exact decimal representation (critical for financial calculations)
- Avoids floating-point precision errors
- Standard in financial applications
Why Asyncio?
- Efficient I/O-bound operation handling
- Non-blocking WebSocket communication
- Better resource utilization than threading
| Metric | Value | Context |
|---|---|---|
| Throughput | 1,200-1,800 orders/sec | Mixed order types |
| Average Latency | 0.5-2.0 ms | Order processing |
| P95 Latency | < 5 ms | 95th percentile |
| P99 Latency | < 10 ms | 99th percentile |
| Memory Usage | ~50 MB | 10,000 order capacity |
| Order Type | Throughput | Avg Latency |
|---|---|---|
| LIMIT | 1,500 ops/sec | 0.6 ms |
| MARKET | 1,400 ops/sec | 0.7 ms |
| IOC | 1,350 ops/sec | 0.7 ms |
| FOK | 1,300 ops/sec | 0.8 ms |
python -m pytest tests/ -v- Tests core matching logic
- Order type validation
- Error handling scenarios
python run_complete_test.py- End-to-end system testing
- REST API + WebSocket integration
- Order book state consistency
python performance/benchmark_comprehensive.py
python performance/custom_benchmark.py --throughput-orders 5000# Terminal 1: Start server
python src/main.py
# Terminal 2: WebSocket client
python test_websocket_client.py
# Terminal 3: Submit orders
python run_complete_test.pyorder_start = time.time()
trades = await engine.process_order(order)
order_end = time.time()
latency = (order_end - order_start) * 1000 # Convert to millisecondstotal_orders = 1000
total_time = end_time - start_time
throughput = total_orders / total_time # orders per second- Average: Mean of all latency measurements
- P95: 95th percentile (95% of requests faster than this)
- P99: 99th percentile (99% of requests faster than this)
- Success Rate: (Processed Orders / Total Orders) Γ 100
- Python 3.11+
- pip (Python package manager)
git clone <repository-url>
cd matching-engine
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtpython src/main.py# Run unit tests
python -m pytest tests/ -v
# Run integration test
python run_complete_test.py
# Run performance benchmark
python performance/quick_benchmark.pySubmit Order
curl -X POST http://localhost:5000/order \
-H "Content-Type: application/json" \
-d '{
"symbol": "BTC-USDT",
"order_type": "limit",
"side": "buy",
"quantity": "1.5",
"price": "50000.0"
}'Get Order Book
curl http://localhost:5000/orderbook/BTC-USDTGet Statistics
curl http://localhost:5000/statsConnect
const ws = new WebSocket('ws://localhost:8765');Subscribe to Order Book
{
"action": "subscribe_orderbook",
"symbols": ["BTC-USDT"]
}Subscribe to Trades
{
"action": "subscribe_trades",
"symbols": ["BTC-USDT"]
}class OrderBook:
def __init__(self, symbol: str):
self.bids: Dict[Decimal, PriceLevel] = {} # Max-heap for prices
self.asks: Dict[Decimal, PriceLevel] = {} # Min-heap for prices
self.bid_prices = [] # Negative prices for max-heap
self.ask_prices = [] # Regular prices for min-heap- Price Priority: Better prices execute first
- Time Priority: Same price β first-in, first-out
- Trade-Through Protection: Always match at best available price
- Order Type Handling: Specific rules for MARKET, IOC, FOK
- Main Thread: WebSocket server and event loop
- Thread Pool: Order processing (4 workers)
- Async I/O: Non-blocking WebSocket communication
- REG NMS-inspired price-time priority
- Internal order protection (no trade-throughs)
- Multiple order types (Limit, Market, IOC, FOK)
- Real-time BBO calculation and dissemination
- REST API for order management
- WebSocket for market data streaming
- Trade execution reporting
- Comprehensive error handling
- Unit tests and documentation
- Target: >1,000 orders/second
- Achieved: 1,200-1,800 orders/second
- Latency: Sub-5ms for 95% of orders
- Stability: Handles 10,000+ orders without degradation
- Clean, maintainable architecture
- Comprehensive test coverage
- Detailed documentation
- Performance benchmarking suite
-
Advanced Order Types
- Stop-Loss orders
- Stop-Limit orders
- Take-Profit orders
- Trailing stops
-
Enhanced Persistence
# Order book snapshotting def save_snapshot(self): with open(f"orderbook_{self.symbol}.json", 'w') as f: json.dump(self.to_dict(), f) def load_snapshot(self): # Recovery from disk pass
-
Fee Model Implementation
class FeeModel: def calculate_fee(self, trade: Trade, side: str) -> Decimal: # Maker-taker fee structure if side == 'maker': return trade.quantity * trade.price * self.maker_fee else: return trade.quantity * trade.price * self.taker_fee
-
Multi-asset Support
- Cross-pair trading
- Portfolio management
- Risk controls per symbol
-
Risk Management
class RiskManager: def validate_order(self, order: Order) -> bool: # Position limits # Credit checks # Volatility controls pass
-
Market Data Protocols
- FIX protocol support
- Binary protocols for lower latency
- Compression for bandwidth efficiency
-
Distributed Architecture
- Sharded order books
- Load balancing across multiple engines
- High availability with failover
-
Regulatory Compliance
- Audit trails
- Reporting systems
- Compliance monitoring
-
Advanced Analytics
- Real-time risk analytics
- Market making algorithms
- Predictive order routing
- GIL Limitations: Python's Global Interpreter Limit
- Decimal Operations: Slower than integer math
- Heap Operations: O(log n) for price level management
- C++ Extension: Critical path in C++ for 10x performance
- Integer Arithmetic: Use integers instead of decimals (fixed-point)
- Lock-free Data Structures: Reduce contention in concurrent access
- Memory Pool: Object reuse to reduce GC pressure
- Financial exchange architecture
- Order matching algorithms
- Real-time systems design
- Performance optimization
- WebSocket programming
- REST API design
- Concurrent programming patterns
- Decimal arithmetic for finance
- REG NMS regulations and principles
- Market microstructure
- Order book dynamics
- Trade execution logic
- Financial data streaming
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is for educational purposes. Please ensure proper licensing for production use.
- REG NMS regulations for guiding principles
- Modern exchange architecture patterns
- Python ecosystem for robust development tools
Built with β€οΈ for high-performance financial systems
For questions or contributions, please open an issue or reach out to the development team.