Orderbook Simulation
OrderbookSim is a C++ application simulating a financial market order book. It efficiently manages and matches buy and sell orders while calculating the Volume-Weighted Average Price (VWAP).
Orderbook.hpp
Go to the documentation of this file.
1 
11 #pragma once
12 
13 #include "Order.hpp"
14 #include "Trade.hpp"
15 #include "Usings.hpp"
16 #include "OrderModify.hpp"
17 #include "OrderbookLevelInfos.hpp"
18 #include "OrderDetailHistory.hpp"
19 
20 #include <map>
21 #include <unordered_map>
22 #include <optional>
23 #include <mutex>
24 #include <condition_variable>
25 #include <cmath>
26 
36 class Orderbook {
37 private:
42  struct OrderEntry {
43  OrderPtr _order{ nullptr };
44  OrderPtrs::iterator _location;
45  };
46 
51  enum class ExecutionTypes {
52  BuyersPrice,
53  SellersPrice,
54  MidPrice
55  };
56 
61  struct LevelData {
62  Quantity _quantity{};
63  Quantity _count{};
64 
69  enum class Action {
70  Add,
71  Remove,
72  Match
73  };
74  };
75 
76  std::map<Price, OrderPtrs, std::greater<Price>> _asks;
77  std::map<Price, OrderPtrs, std::less<Price>> _bids;
78  std::unordered_map<OrderId, OrderEntry> _orders;
79  std::unordered_map<Price, LevelData> _data;
80 
81  mutable std::mutex _ordersMutex;
82  std::thread _ordersPruneThread;
83  std::condition_variable _shutdownConditionVariable;
84  std::atomic<bool> _shutdown{ false };
85 
86  ExecutionTypes _executionType = ExecutionTypes::BuyersPrice;
87  OrderDetailHistory _orderDetailHistory;
88 
89  // Private member functions
90  bool canMatch(Side side, Price price) const;
91  Trades MatchOrders();
92  void CancelOrders(OrderIds orderIds);
93  void CancelOrderInternal(OrderId orderId);
94  bool canFullyFill(Side side, Price price, Quantity quantity) const;
95 
96  void onOrderCanceleld(OrderPtr order);
97  void onOrderAdded(OrderPtr order);
98  void onOrderMatchedWithHistoryUpdate(Price price, Quantity quantity, bool isFullyFilled, Price purchasePrice);
99  void onOrderMatched(Price price, Quantity quantity, bool isFullyFilled);
100  void UpdateLevelData(Price price, Quantity quantity, LevelData::Action action);
101  Trades MatchOrder(OrderModify order);
102 
103  // Private methods for managing Good For Day orders
104  void PruneGoodForDayOrders();
105 
106 public:
110  Orderbook() : _ordersPruneThread{ [this] { PruneGoodForDayOrders(); } } {}
111 
112  // Deleted copy and move constructors and operators to prevent copying
113  Orderbook(const Orderbook&) = delete;
114  void operator=(const Orderbook&) = delete;
115  Orderbook(Orderbook&&) = delete;
116  void operator=(Orderbook&&) = delete;
117 
122  _shutdown.store(true, std::memory_order_release);
123  _shutdownConditionVariable.notify_one();
124  _ordersPruneThread.join();
125  }
126 
132  void changeExecutionType(int type);
133 
140  Trades addOrder(OrderPtr order);
141 
151  Trades addOrder(OrderType type, Side side, Price price, Quantity qty);
152 
163  Trades addOrder(OrderType type, OrderId orderId, Side side, Price price, Quantity qty);
164 
174  void addOrderViaPython(int type, int id, int side, int price, int qty);
175 
181  void CancelOrder(OrderId orderId);
182 
189  Trades ModifyOrder(OrderModify order);
190 
196  void setPriceScale(Price _price);
197 
203  Price getPriceScale();
204 
208  void printAllOrders();
209 
221  void saveToJson(const std::string& buyfilename = "BuyHistory.json", const std::string& sellfilename = "SellHistory.json", const std::string& purchasefilename = "PurchaseHistory.json", const std::string& buyLivefilename = "BuyLiveHistory.json", const std::string& sellLivefilename = "SellLiveHistory.json");
222 
228  std::size_t Size() const;
229 
238  OrderbookLevelInfos getOrderInfos() const;
239 
245  void EndOfDay();
246 };
Declares the OrderDetailHistory class for managing order histories and live orders.
Defines the OrderModify class, which encapsulates modifications to an order's details.
OrderType
Specifies the different types of orders that can be used in a trading system.
Definition: OrderType.hpp:18
Defines the Order class and related types for managing orders in a trading system.
std::shared_ptr< Order > OrderPtr
A shared pointer to an Order object.
Definition: Order.hpp:163
Defines the OrderbookLevelInfos class for managing bid and ask levels in an orderbook.
Side
Represents the side of an order in a trading system (either buy or sell).
Definition: Side.hpp:16
Defines the Trade class, representing a completed trade with bid and ask details.
std::vector< Trade > Trades
A type alias for a collection of Trade objects.
Definition: Trade.hpp:64
Defines type aliases commonly used in the trading system.
std::int32_t Price
Represents the price of an order or trade.
Definition: Usings.hpp:21
std::uint32_t Quantity
Represents the quantity or volume of assets in an order or trade.
Definition: Usings.hpp:29
std::vector< OrderId > OrderIds
A collection of unique order identifiers.
Definition: Usings.hpp:45
std::uint64_t OrderId
Represents a unique identifier for an order.
Definition: Usings.hpp:37
Manages the history of orders and tracks live orders in the orderbook.
Definition: OrderDetailHistory.hpp:27
Represents a modification to an existing order.
Definition: OrderModify.hpp:23
Holds the bid and ask levels for an orderbook.
Definition: OrderbookLevelInfos.hpp:21
Manages and matches orders in a trading environment.
Definition: Orderbook.hpp:36
Orderbook()
Default constructor, initializes the Good For Day order pruning thread.
Definition: Orderbook.hpp:110
void operator=(const Orderbook &)=delete
Orderbook(Orderbook &&)=delete
void operator=(Orderbook &&)=delete
~Orderbook()
Destructor, joins the pruning thread and signals shutdown.
Definition: Orderbook.hpp:121
Orderbook(const Orderbook &)=delete
Definition: addOrder.py:1
@ Add
Add a new order.