Skip to content

About

Low-Latency In-Memory Matching Engine & Financial Risk Gateway (C++20, C#, React DOM Terminal)

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

NexusTrade — Low-Latency In-Memory Matching Engine & Financial Risk Gateway

C++20 CMake .NET React SignalR Docker License: MIT

NexusTrade is a multi-tier quantitative trading platform designed to demonstrate real systems programming, low-latency concurrent engineering, and financial market infrastructure. It couples a native C++20 in-memory Limit Order Book (LOB) with an ASP.NET Core 8 risk & regulatory gateway, and an institutional-grade React trading terminal streaming real-time market depth via WebSockets/SignalR.


Key Features

  • Microsecond In-Memory Matching Engine (C++20): Implements price-time priority (FIFO) matching algorithm across multi-symbol books (BTC-USD, ETH-USD, SOL-USD).
  • Zero-Allocation Hot Path: Custom MemoryPool<Order> eliminates heap fragmentation and dynamic malloc/free calls during order placement and execution.
  • Constant-Time $O(1)$ Order Cancellation: Intrusive doubly-linked queue nodes paired with direct memory indexing.
  • Pre-Trade Risk Management (C#): Enforces pre-trade margin solvency, fat-finger maximum order caps, and position limits prior to core engine dispatch.
  • Real-Time Level 2 Depth Ladder (DOM): React-based trader terminal with live bid/ask volume distribution bars, spread calculation, and click-to-trade order placement.
  • Live Tape Execution Stream: Instant trade settlement and WebSocket broadcast over ASP.NET Core SignalR.
  • High-Throughput IPC Socket Protocol: Cross-platform TCP daemon facilitating low-overhead binary/JSON interchange between .NET and C++.

Terminal UI Preview

+-------------------------------------------------------------------------------------------------------+
| [⚡ NexusTrade] L2 LOW-LATENCY  [BTC-USD] [ETH-USD] [SOL-USD]   BID: $64,490.00  ASK: $64,510.00  <12 μs|
+-------------------------------------------------------------------------------------------------------+
| ORDER BOOK DEPTH (L2)         | TRADER MARGIN & RISK LIMITS       | ORDER TICKET                      |
| PRICE ($)     SIZE    ORDERS  | Collateral: $150,000.00 USD       | [ BUY ]     [ SELL ]              |
| 64,530.00     5.00      2 [=] | BTC Vault:  3.5000 BTC            | Type: [Limit] [Market] [IOC]      |
| 64,520.00     2.80      1 [=] | ETH Vault: 25.0000 ETH            | Price:    [64,500.00]             |
| 64,510.00     1.20      1 [=] | Max Notional Cap: $50,000         | Quantity: [0.50]                  |
| ----------------------------- | --------------------------------- | Est. Notional: $32,250.00         |
| SPREAD: $20.00                | PIPELINE STATUS                   | [ SUBMIT BUY BTC-USD ]            |
| ----------------------------- | [C++ Core: 0.0.0.0:7777] (FIFO)   |                                   |
| 64,490.00     1.50      1 [=] | [C# Gateway: SignalR Active]      | PUBLIC TRADES TAPE                |
| 64,480.00     2.20      2 [=] | [Ring Buffer: Zero Heap Allocs]   | 64,510.00   0.50  14:02:41        |
| 64,470.00     4.50      3 [=] | Latency P50: 1.8 μs               | 64,510.00   0.70  14:02:39        |
+-------------------------------------------------------------------------------------------------------+

Tech Stack

Component Technology Rationale & Practical Role
Matching Core C++20 Predictable execution latency, cache-conscious memory layout, zero-allocation memory pools, and lock-free/low-contention primitives.
Build System CMake 3.20+ Cross-platform C++ compilation supporting GCC, Clang, and MSVC.
Risk Gateway C# / .NET 8 Enterprise API development, async socket I/O, EF Core database persistence, and SignalR hub multiplexing.
Database SQLite / PostgreSQL Cold storage for account margin balances, user profiles, and post-trade compliance audit records.
Web Terminal React 18 & TypeScript Componentized UI architecture, strict DTO typing, and low-overhead virtual DOM reconciliation.
Real-Time Wire SignalR WebSockets Sub-millisecond market depth broadcasting and live trade notifications to browser DOM.
Containerization Docker Compose Multi-container setup isolating the C++ core daemon, C# gateway, and Nginx terminal.

Project Structure

NexusTrade/
├── CMakeLists.txt                 # Root CMake build configuration
├── docker-compose.yml             # Engine, Gateway, and Frontend orchestrator
├── src/
│   ├── engine/                    # Native C++20 Core Matching Engine
│   │   ├── include/
│   │   │   ├── Types.hpp          # Side, OrderType, OrderStatus, Timestamp primitives
│   │   │   ├── Order.hpp          # Intrusive doubly-linked order node and execution structs
│   │   │   ├── PriceLevel.hpp     # FIFO queue at limit price level
│   │   │   ├── OrderBook.hpp      # Limit order book, bid/ask maps, matcher algorithms
│   │   │   ├── MatchingEngine.hpp # Multi-instrument book router
│   │   │   ├── MemoryPool.hpp     # Fast zero-allocation order pool
│   │   │   └── TcpServer.hpp      # High-performance socket server (Windows/Linux)
│   │   ├── src/
│   │   │   ├── OrderBook.cpp      # FIFO execution, matching logic, price improvement
│   │   │   ├── MatchingEngine.cpp # Symbol registration and book routing
│   │   │   ├── TcpServer.cpp      # Wire protocol parser and JSON serializer
│   │   │   └── main.cpp           # Engine daemon entrypoint and liquidity bootstrap
│   │   └── tests/
│   │       ├── OrderBookTests.cpp # FIFO matching, partial fills, cancellation tests
│   │       └── MatchingEngineTests.cpp
│   ├── gateway/                   # C# ASP.NET Core Risk & Trading Gateway
│   │   ├── NexusTrade.Gateway.sln
│   │   └── NexusTrade.Gateway.Api/
│   │       ├── Controllers/       # Orders, Accounts, MarketData endpoints
│   │       ├── Hubs/              # MarketDataHub (SignalR WebSocket)
│   │       ├── Services/          # EngineTcpClient, RiskService, MarketDataStreamer
│   │       └── Models/            # DTOs, TraderAccount, Audit records
│   └── frontend/                  # React 18 + TypeScript Trader Terminal
│       └── src/
│           ├── components/        # OrderBookLadder, OrderTicket, RecentTrades
│           ├── services/          # SignalR & REST API client
│           └── styles/            # Institutional dark terminal CSS
└── docs/
    ├── architecture.md            # In-depth architectural blueprint
    ├── protocol.md                # Wire protocol specification
    └── benchmarks.md              # Microsecond latency benchmark profiles

Quick Start (Docker Compose)

Launch all 3 tiers with Docker:

docker-compose up --build

Local Development & Manual Build

1. Build & Run C++ Engine

# Configure with CMake
cmake -B build -DCMAKE_BUILD_TYPE=Release

# Build binaries
cmake --build build --config Release

# Run unit tests
ctest --test-dir build --output-on-failure

# Start Engine Daemon
./build/src/engine/nexustrade_daemon 7777
# (On Windows: .\build\src\engine\Release\nexustrade_daemon.exe 7777)

2. Build & Run C# Gateway

cd src/gateway/NexusTrade.Gateway.Api
dotnet run

Gateway starts on http://localhost:5050.

3. Build & Run React Frontend

cd src/frontend
npm install
npm run dev

Open http://localhost:5173.


Wire Protocol Example

You can communicate directly with the C++ Matching Engine via telnet or nc:

nc localhost 7777
PING
# Response: {"status":"PONG","timestamp":1727877600000000000}

NEW_ORDER 9001 TEST_TRADER BTC-USD BUY LIMIT 6450000 100
# Response: {"status":"ACCEPTED","orderId":9001,"matches":[]}

GET_DEPTH BTC-USD 5
# Response: {"status":"OK","symbol":"BTC-USD","timestamp":...,"bids":[...],"asks":[...]}

Publishing to GitHub

cd NexusTrade
git init
git add .
git commit -m "feat: initial commit of NexusTrade low-latency matching engine and risk gateway"
git branch -M main
git remote add origin https://github.com/<your-username>/nexustrade.git
git push -u origin main

License

Distributed under the MIT License. See LICENSE for details.

About

Low-Latency In-Memory Matching Engine & Financial Risk Gateway (C++20, C#, React DOM Terminal)

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages