-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.cpp
More file actions
242 lines (204 loc) · 7.65 KB
/
project.cpp
File metadata and controls
242 lines (204 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#include <iostream>
#include <map>
#include <list>
#include <memory>
#include <vector>
#include <functional>
#include <algorithm>
#include <iomanip>
// Represents the side of an order.
enum class Side
{
BUY,
SELL
};
// Represents a single order in the book.
struct Order
{
uint64_t id;
Side side;
double price;
uint32_t quantity;
};
// Represents an executed trade.
struct Trade
{
uint64_t buyOrderId;
uint64_t sellOrderId;
double price;
uint32_t quantity;
};
class OrderBook
{
public:
using BidsMap = std::map<double, std::list<Order>, std::greater<double>>;
using AsksMap = std::map<double, std::list<Order>>;
using MatchResult = std::pair<OrderBook, std::vector<Trade>>;
// Default constructor for an empty order book.
OrderBook()
: bids_(std::make_shared<BidsMap>()),
asks_(std::make_shared<AsksMap>()) {}
OrderBook add(const Order &order) const
{
// 1. Create a shallow copy. This just copies the shared_ptrs, which is fast.
OrderBook newBook = *this;
if (order.side == Side::BUY)
{
// 2. Make a deep copy of the specific map we need to change.
newBook.bids_ = std::make_shared<BidsMap>(*bids_);
// 3. Modify the deep copy. The original remains untouched.
(*newBook.bids_)[order.price].push_back(order);
}
else
{
newBook.asks_ = std::make_shared<AsksMap>(*asks_);
(*newBook.asks_)[order.price].push_back(order);
}
return newBook;
}
MatchResult match() const
{
// If there's nothing to match, return the current state with no trades.
if (bids_->empty() || asks_->empty())
{
return {*this, {}};
}
auto bestBidPrice = bids_->begin()->first;
auto bestAskPrice = asks_->begin()->first;
// If the highest bid is less than the lowest ask, there's no trade.
if (bestBidPrice < bestAskPrice)
{
return {*this, {}};
}
// A trade is possible. We start with the current book's state.
OrderBook currentBook = *this;
std::vector<Trade> trades;
// Loop as long as a match is possible.
while (!currentBook.bids_->empty() && !currentBook.asks_->empty() &&
currentBook.bids_->begin()->first >= currentBook.asks_->begin()->first)
{
// Create the next version of the book by deep-copying both maps.
OrderBook nextBook = currentBook;
nextBook.bids_ = std::make_shared<BidsMap>(*currentBook.bids_);
nextBook.asks_ = std::make_shared<AsksMap>(*currentBook.asks_);
auto &bidLevel = nextBook.bids_->begin()->second;
auto &askLevel = nextBook.asks_->begin()->second;
Order &bidOrder = bidLevel.front();
Order &askOrder = askLevel.front();
// Determine trade quantity.
uint32_t tradeQuantity = std::min(bidOrder.quantity, askOrder.quantity);
// Create a trade record. The trade price is the price of the resting order (the ask).
trades.emplace_back(Trade{
bidOrder.id,
askOrder.id,
askOrder.price,
tradeQuantity});
// Reduce quantities of the traded orders.
bidOrder.quantity -= tradeQuantity;
askOrder.quantity -= tradeQuantity;
// If an order is fully filled, remove it.
if (bidOrder.quantity == 0)
{
bidLevel.pop_front();
}
if (askOrder.quantity == 0)
{
askLevel.pop_front();
}
// If a price level is now empty, remove it from the map.
if (bidLevel.empty())
{
nextBook.bids_->erase(nextBook.bids_->begin());
}
if (askLevel.empty())
{
nextBook.asks_->erase(nextBook.asks_->begin());
}
// The new state becomes the current state for the next loop iteration.
currentBook = nextBook;
}
return {currentBook, trades};
}
/**
* @brief Prints a visual representation of the order book.
*/
void print() const
{
std::cout << "--- ORDER BOOK ---" << std::endl;
std::cout << std::fixed << std::setprecision(2);
// Print Asks (in reverse order to show lowest ask at the bottom)
std::cout << "ASKS (Price | Quantity)" << std::endl;
std::cout << "----------------------" << std::endl;
for (auto it = asks_->rbegin(); it != asks_->rend(); ++it)
{
uint32_t totalQuantity = 0;
for (const auto &order : it->second)
{
totalQuantity += order.quantity;
}
std::cout << it->first << " | " << totalQuantity << std::endl;
}
std::cout << "----------------------" << std::endl;
// Print Bids
std::cout << "BIDS (Price | Quantity)" << std::endl;
std::cout << "----------------------" << std::endl;
for (const auto &pair : *bids_)
{
uint32_t totalQuantity = 0;
for (const auto &order : pair.second)
{
totalQuantity += order.quantity;
}
std::cout << pair.first << " | " << totalQuantity << std::endl;
}
}
private:
// Use shared pointers for efficient, immutable copying.
std::shared_ptr<BidsMap> bids_;
std::shared_ptr<AsksMap> asks_;
};
int main() {
uint64_t orderIdCounter = 1;
// Start with a clean slate. This is Version 0.
OrderBook book_v0;
std::cout << "--- Initial State (v0) ---" << std::endl;
book_v0.print();
// Each 'add' call creates a new, independent version of the book.
auto book_v1 = book_v0.add({orderIdCounter++, Side::BUY, 99.50, 100});
auto book_v2 = book_v1.add({orderIdCounter++, Side::BUY, 99.75, 50});
auto book_v3 = book_v2.add({orderIdCounter++, Side::SELL, 100.50, 200});
auto book_v4 = book_v3.add({orderIdCounter++, Side::SELL, 100.25, 75});
std::cout << "--- State after adding 4 orders (v4) ---" << std::endl;
book_v4.print();
// Let's prove immutability: the original book (v0) is still empty.
std::cout << "--- Checking original state (v0) ---" << std::endl;
book_v0.print();
// --- Step 2: Add an order that will cause a match ---
std::cout << "--- Adding a new BUY order at 100.25 ---" << std::endl;
auto book_v5 = book_v4.add({orderIdCounter++, Side::BUY, 100.25, 150});
std::cout << "--- State before matching (v5) ---" << std::endl;
book_v5.print();
// --- Step 3: Run the matching engine ---
std::cout << "--- Running the matching engine... ---" << std::endl;
auto matchResult = book_v5.match();
OrderBook book_v6 = matchResult.first;
std::vector<Trade> trades = matchResult.second;
if (!trades.empty()) {
std::cout << "Trades Executed!" << std::endl;
for (const auto& trade : trades) {
std::cout << " - Matched Buy Order " << trade.buyOrderId
<< " with Sell Order " << trade.sellOrderId
<< ". Quantity: " << trade.quantity
<< " @ Price: " << trade.price << std::endl;
}
std::cout << std::endl;
} else {
std::cout << "No trades were executed." << std::endl;
}
std::cout << "--- State after matching (v6) ---" << std::endl;
book_v6.print();
// Note that book_v5 is still unchanged because match() is also immutable.
std::cout << "--- Checking pre-match state (v5) ---" << std::endl;
book_v5.print();
return 0;
}