A simple Limit Order Book implementation in C++. Maintains two side books (bids and asks) with support for:
- Limit order placement with automatic matching
- Partial and full fills
- Order cancellation in O(1) via hashmap of iterators
- Volume tracking per price level
- Text-based printing of book state
- Two sides: Bids (descending prices) and Asks (ascending prices) using
std::mapwith custom comparators. - Fast operations: O(log n) price-level lookup, O(1) insert/delete within price level via
std::list. - Order cancellation: Immediate removal by
OrderIdusingstd::unordered_map<OrderId, iterator>. - Recursive matching: New orders cross spread and match until exhausted.
- VolumeMap: Tracks total quantity at each price.
-
Order: Represents an individual order with price, quantity, ID, side, and timestamp.
-
OrderQueue:
std::list<Order>for each price level, enabling stable iterators. -
LimitOrderBook: Manages
BidsandAsksmaps:std::map<Price, OrderQueue, std::greater<Price>> Bidsstd::map<Price, OrderQueue, std::less<Price>> Asks
-
OrderMap:
std::unordered_map<OrderId, OrderQueue::iterator>for cancellation. -
VolumeMap:
std::unordered_map<Price, Quantity>for level volume.
- C++17 or later
- Clang++ or any C++17-compatible compiler
# Compile with clang++
clang++ -std=c++17 -O2 -Wall -Wextra -o orderbook main.cppYou can also use g++:
g++ -std=c++17 -O2 -Wall -Wextra -o orderbook main.cpp./orderbookThis runs the built-in test driver, demonstrating:
- Initial limit order placements
- Matching behavior for crossed orders
- Partial and full fills
- Order cancellation
- Final book state printing
LimitOrderBook book;
auto now = std::chrono::steady_clock::now();
// Place bids
book.PlaceOrder(100, 10, 1, OrderSide::BUY, now);
book.PlaceOrder(102, 5, 2, OrderSide::BUY, now);
// Place asks
book.PlaceOrder(105, 7, 3, OrderSide::SELL, now);
book.PlaceOrder(101, 3, 4, OrderSide::SELL, now);
// Print
book.PrintBook();
// Place an order that crosses the spread
book.PlaceOrder(103, 10, 5, OrderSide::BUY, now);
book.PrintBook();├── main.cpp # Implementation and test driver
└── README.md # This file
- Fork it
- Create your feature branch (
git checkout -b feature/fooBar) - Commit your changes (
git commit -am 'Add some fooBar') - Push to the branch (
git push origin feature/fooBar) - Create a new Pull Request
Please label issues and PRs appropriately. New contributors can look for issues tagged good first issue.