|
exchange
Low-latency exchange in C++
|
A stock exchange written in C++20, built as a set of separate processes that communicate through shared memory. Clients connect over gRPC. The core is a matching engine that keeps an order book for every security and matches buy and sell orders by price, then by arrival time. It supports limit and market orders, the GTC, IOC and FOK time in force options, and cancelling and amending orders. Separate services turn the output of the matching engine into market data, such as order book snapshots (L1 and L2) and candlestick (OHLCV) data.
Besides unit tests, the matching logic is verified with mutation testing, differential testing and fuzzing, and every push is built and tested in 12 compiler and sanitizer configurations.
The project is a work in progress. The matching engine, the order book publisher and the candlestick publisher are implemented and tested. The gateway currently answers the securities lookups, and the execution publisher, order manager and archiver are placeholders. SPEC.md describes the full target design.
The following concerns are out of scope, otherwise I would have a running business :) High availability, fault tolerance, FIX support, network security, multicast, cloud deployment, trading schedule, risk checks, wallet management, GUI for traders, regulatory compliance.
All source classes, functions, and APIs were named, designed, and implemented by hand. AI was used for research, code review, writing tests, writing the Markdown files from notes, writing the CI YAML files, and code completion for repeated patterns.
Each component runs as its own process, as shown in the diagram above. The gateway receives requests from clients over gRPC, and order requests are written as events to a shared memory queue. The matching engine is the only reader of that queue. It runs on a single thread pinned to one CPU core, applies each event to the order book of its security, and broadcasts the resulting actions (trades, added, resized and removed orders) on a second shared memory queue. The publishers, the order manager and the gateway read from that broadcast queue to build their own view of the market. The queues are Aeron ring buffers placed in shared memory created with Boost.Interprocess. See SPEC.md for the full design.
The libraries are installed by Conan from conanfile.txt: gRPC, Protobuf, spdlog, Aeron, Boost, GoogleTest, oneTBB, concurrentqueue, libcurl, nlohmann_json and uWebSockets.
On Windows, I recommend MSVC, to avoid issues with Conan. Install it via the Visual Studio Installer with the "Desktop development with C++" package.
When selecting individual components, install the MSVC v143 (VS 2022) build tools specifically, rather than the newer v144 toolset. Most prebuilt binary packages on ConanCenter are currently built against v143, so using it avoids Conan falling back to --build=missing and rebuilding dependencies from source.
Only needed if you want to run formatting, linting, or docs generation, or use the just aliases below:
Every module follows the same layout, with public headers under include/, the implementation under src/ and the tests under test/. The executables in apps/ only call into these modules.
Mutation testing checks the quality of the tests themselves. Small bugs (mutants) are added to the source code on purpose, and a good test suite should fail for each of them. 15 handwritten mutants, stored as git patches, are applied one at a time and the tests are run against each. The first run caught 12 of the 15, and the surviving mutants led to new tests. See MUTATION_TESTING.md for the approach and the full results.
The matching engine is compared against a simple reference implementation with the same logic. Every handwritten test, and 20,000 randomly generated sequences of orders on every run, are sent to both, and the test fails if their outputs differ. One million random sequences were also run locally without a single difference. See DIFFERENTIAL_TESTING.md.
The matching engine is fuzzed with libFuzzer, which generates millions of order sequences and moves towards inputs that reach new code (coverage-guided fuzzing). The order book checks its own invariants with assertions, such as the best buy price always being below the best sell price, and the fuzzer reports any input that breaks one of them or triggers a memory error. A 10-minute run in CI executed almost 6 million sequences without finding an issue. See FUZZING.md.
Tests are built alongside the project and registered with CTest:
Or just test. Other variants:
The matching engine can process around 7.5 million order events per second on one core, with a p99 latency of ~0.5 μs. Benchmarked in Docker on Windows (WSL), with an Ubuntu 24.04 container. There is a warmup period of 1M events, followed by a recorded run of 4M events. Throughput and latency are measured in separate passes. See BENCHMARKING.md.
Every push runs the build GitHub Actions workflow:
Dependencies are installed with Conan in every job, and the downloaded packages are cached between runs. The formatting and linting checks can also be run locally:
Requires the project to have been built first (see Building), since clang-tidy reads the compile commands from the build output.
The API documentation is generated from the source comments with Doxygen and published to GitHub Pages by the docs workflow on every push to main. To generate it locally:
Output is written to docs/html.
Documentation about the public gRPC API of the exchange can be found in the dedicated README.
Detect your Conan profile (first time only):
Install dependencies and generate the CMake toolchain/presets:
Configure the project:
Build:
On Windows, run these from a Visual Studio developer shell. The equivalent just commands are just install and just build.
The executables are placed under cmake-build-release/build/Release/apps/. The matching engine creates the shared memory, so it has to start first, followed by the publishers and then the gateway, each in its own terminal:
The gateway listens on port 8989. The example client connects to it and requests the list of securities once per second:
There is a Justfile with short aliases for the commands above (and a few extras like dependency auditing and simulated CI dry-runs via act). Once just is installed, run commands from the repo root:
Run just --list to see all available aliases.