Skip to content

About

A high-performance, research-grade C++17 implementation of a parallel order book engine featuring adaptive data structure selection and lock-free concurrency primitives.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Adaptive Lock-Free Parallel Order Book Engine (TradeVIT Stack)

This repository now contains a complete high-performance trading stack:

  • C++17 adaptive lock-free order book and matching engine
  • FastAPI backend that runs the C++ engine in API mode
  • React + Vite frontend dashboard (TradeVIT)
  • Read-only Auto Insight Mode for predictive market signals

The implementation is designed for low-latency experimentation and research workloads where throughput, stability, and observability matter.

Current Project Scope

1. Core Matching Engine (C++)

  • Adaptive dual data structure:
    • Sorted vector for low-load paths
    • Lock-free skip list for high-load paths
  • Price-time priority matching
  • Parallel insertion and lock-free contention handling (CAS with retry/backoff)
  • Hysteresis-based switching to avoid oscillation
  • Runtime strategy controls for rule-based vs ML-based mode decisions

2. Backend Service (FastAPI)

  • Starts and manages the C++ engine process (--api mode)
  • Exposes REST APIs for order submission, order book, trades, and simulation control
  • Validates order side/price/qty before forwarding to engine
  • Exposes aggregated system metrics from engine CSV logs

3. Frontend Dashboard (React)

  • TradeVIT branded trading UI
  • Live order book and trade history panels
  • Manual order entry
  • Auto-trading simulator toggle
  • Auto Insight ON/OFF toggle
  • Hover-based contextual insight tooltips in order book and trade history

4. Auto Insight Mode (Read-Only Analytics)

  • Floating alert panel with bullish/bearish/warning signals
  • Detects support/resistance walls, imbalance shifts, volatility bursts, spread widening
  • Includes anti-spoofing heuristics and confidence/ETA windows
  • Optionally improves/reduces confidence using backend system metrics
  • Never mutates or writes to the order book (read-only inference layer)

Architecture Overview

Frontend (React/Vite)
    |
    | HTTP polling (order book, trades, metrics, controls)
    v
Backend (FastAPI)
    |
    | stdio JSON commands (ADD / GET_BOOK / GET_TRADES)
    v
C++ Engine (order_book_engine --api)
    |
    +-- AdaptiveOrderBook (buy)
    +-- AdaptiveOrderBook (sell)
    +-- MatchingEngine thread

Adaptive Switching and ML Integration

Rule-based baseline

The engine monitors:

  • arrival rate
  • queue depth / book size
  • skip-list contention
  • recent latency

Default thresholds used by rule mode:

  • low load threshold: 1000 orders/sec
  • high load threshold: 5000 orders/sec
  • mode switch hysteresis: 100 ms

ML-based switching (optional)

  • Runtime toggle: --ml-mode ON|OFF
  • Model file: --ml-model <path>
  • Uses lightweight prediction for target mode selection
  • Automatic fallback to rule mode when:
    • model is unavailable
    • prediction fails
    • inference budget is exceeded
    • prediction pattern is unstable

Important runtime behavior

Mode checks are now performed in all active flows:

  • benchmark flows
  • interactive flow
  • API flow (periodic checks after insert batches)

This keeps adaptive switching active during dashboard/API usage, not only benchmarks.

Metrics Logging and System Metrics API

Engine CSV logging

Enable/disable and configure via:

  • --metrics-log ON|OFF
  • --metrics-log-prefix <prefix>

Generated files:

  • <prefix>_buy.csv
  • <prefix>_sell.csv

Logged columns include:

  • arrival_rate, book_size, queue_depth, contention, recent_latency_us
  • rule-selected mode, final selected mode
  • strategy name (RULE / ML)
  • ML confidence and inference time
  • fallback-used flag

Backend aggregation endpoint

GET /api/system-metrics

  • Reads latest rows from buy/sell CSV files
  • Returns averaged runtime indicators and strategy status
  • Returns {"status":"unavailable"} when metrics files are not yet available

Environment variable:

  • ENGINE_METRICS_PREFIX (default: ml_switch_metrics)

REST API Surface

Base URL: http://127.0.0.1:8000

  • GET /health
    • Engine process status
  • POST /api/orders
    • Body: { "side": "buy|sell", "price": number, "qty": int }
    • Strict validation for side/price/qty
  • GET /api/orderbook?depth=20
    • Returns top bid/ask levels
  • GET /api/trades?limit=50
    • Returns recent executed trades
  • POST /api/simulation/start
  • POST /api/simulation/stop
  • GET /api/simulation/status
  • GET /api/system-metrics

Benchmark Suite (Updated)

The benchmark flow now includes:

  1. Single-threaded baseline
  2. Multi-threaded scalability
  3. Low load scenario
  4. High load scenario
  5. Burst traffic scenario
  6. Heavy skew scenario
  7. High contention scenario
  8. Rule vs ML comparison

Collected outputs include throughput, latency percentiles (P50/P95/P99), mode switches, and ML fallback/failure counters.

Quick Start

Prerequisites

  • C++17 compiler (g++/clang)
  • make
  • Python 3.10+
  • Node.js 18+

One-time setup

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r backend/requirements.txt

cd frontend
npm install
cd ..

make

Run full stack

Option A (script):

./run_app.sh

Option B (manual, two terminals):

Terminal 1:

source .venv/bin/activate
python backend/main.py

Terminal 2:

cd frontend
npm run dev

Frontend default URL:

  • http://localhost:5173

Backend default URL:

  • http://127.0.0.1:8000

Engine-only usage

./order_book_engine --help
./order_book_engine --demo
./order_book_engine --interactive
./order_book_engine --quick 10000
./order_book_engine --benchmark 50000

With ML mode enabled:

./order_book_engine --benchmark 50000 --ml-mode ON --ml-model ml_model_weights.csv
./order_book_engine --quick 10000 --ml-mode ON --metrics-log ON --metrics-log-prefix ml_run

API mode:

./order_book_engine --api --ml-mode ON --ml-model ml_model_weights.csv

Frontend Experience Notes

  • System Operational badge reflects backend connectivity
  • Auto-trading switch controls backend market-maker simulation
  • Auto Insight panel shows active predictive alerts and confidence
  • Hovering order book levels reveals support/resistance interpretation
  • Hovering trade rows reveals momentum/impact interpretation

Project Layout

.
├── main.cpp
├── order_book_engine.hpp
├── matching_engine.hpp
├── order_generator.hpp
├── benchmark.hpp
├── Makefile
├── CMakeLists.txt
├── run_app.sh
├── build_and_test.sh
├── test_api.py
├── backend/
│   ├── main.py
│   ├── bot.py
│   └── requirements.txt
└── frontend/
    ├── package.json
    ├── src/
    │   ├── App.tsx
    │   ├── index.css
    │   ├── components/
    │   │   ├── OrderBook.tsx
    │   │   ├── OrderForm.tsx
    │   │   ├── TradeHistory.tsx
    │   │   └── InsightPanel.tsx
    │   └── insights/
    │       └── autoInsightEngine.ts
    └── ...

Verification Commands

Build and smoke test:

./build_and_test.sh

Backend health:

curl -sS http://127.0.0.1:8000/health

API sanity test:

python test_api.py

Frontend production build:

cd frontend
npm run build

Known Extensions and Next Steps

Planned enhancements that are still open:

  • dedicated unit test suite for core engine internals
  • persistent order book snapshots/replay tooling
  • multi-symbol support and symbol-partitioned books
  • async metrics sink for stricter non-blocking telemetry writes

License

MIT License

About

A high-performance, research-grade C++17 implementation of a parallel order book engine featuring adaptive data structure selection and lock-free concurrency primitives.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages