This project provides a simple yet effective implementation of an immutable financial order book using modern C++. It demonstrates how to manage state changes without mutation, using a copy-on-write strategy with shared pointers for efficiency.
This approach is common in functional programming and offers several advantages in concurrent or state-sensitive systems, such as providing a clear and safe history of the order book's state over time.
-
Immutability: The
OrderBookclass is immutable. Methods likeaddandmatchdo not modify the object they are called on. Instead, they return a newOrderBookinstance representing the state after the operation. This makes the system's state history explicit and thread-safe by design. -
Copy-on-Write with
std::shared_ptr: To avoid the performance cost of deep-copying the entire order book for every small change, the implementation usesstd::shared_ptrto manage the underlying bid and ask maps. When a new order is added, only the relevant map (bids or asks) is deep-copied, while the other is shared with the previous version of the book. This is an efficient "copy-on-write" strategy. -
State Versions: The
main()function demonstrates how each operation creates a new, distinct version of the book (book_v0,book_v1,book_v2, etc.), allowing you to inspect or reuse any previous state of the order book at any time without fear of it being changed.
This project is a single-file C++ application with no external dependencies. You can compile and run it using any modern C++ compiler (C++11 or newer).
# Compile the source code
g++ -std=c++11 -o orderbook project.cpp
# Run the executable
./orderbook# Compile the source code
cl.exe /std:c++17 /EHsc project.cpp
# Run the executable
.\project.exeThe main() function in project.cpp provides a clear demonstration of the immutable workflow:
- Initial State (v0): An empty order book is created.
- Adding Orders (v1-v4): Four orders are added sequentially. Each
addcall returns a newOrderBookinstance, creating versionsv1throughv4. The originalv0book remains empty, proving immutability. - Triggering a Match (v5): A new buy order is added at a price that can be matched with an existing sell order. This creates
book_v5. - Matching Engine (v6): The
match()method is called onbook_v5. This function finds and executes trades, returning a pair containing the final state of the book (book_v6) and a list of trades that occurred. - Post-Match State: The program prints the trades and the new state of the book (
book_v6). It also shows thatbook_v5(the state right before the match) remains unchanged, highlighting that thematchoperation is also immutable.