-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderBook.cpp
More file actions
250 lines (198 loc) · 5.87 KB
/
OrderBook.cpp
File metadata and controls
250 lines (198 loc) · 5.87 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
243
244
245
246
247
248
249
250
#include <iostream>
#include <format>
#include <algorithm>
#include <chrono>
#include <vector>
#include <iterator>
#include "OrderBook.h"
#include "Order.h"
#include "Types.h"
#include "Side.h"
void OrderBook::addToBook(OrderPointer order)
{
Price orderPrice = order->getPrice();
Side orderSide = order->getSide();
PriceLevel* level = nullptr;
if (orderSide == Side::Buy) {
auto [it, inserted] = bids_.try_emplace(
orderPrice,
PriceLevel{ .totalQuantity = Quantity{0}, .orders = {} }
);
level = &it->second;
}
else {
auto [it, inserted] = asks_.try_emplace(
orderPrice,
PriceLevel{ .totalQuantity = Quantity{0}, .orders = {} }
);
level = &it->second;
}
level->orders.push_back(order);
level->totalQuantity += order->getRemainingQuantity(); // remaining, since order may have partially filled before resting
auto orderIterator = std::prev(level->orders.end());
orders_[order->getOrderId()] = OrderEntry{
.side = orderSide,
.price = orderPrice,
.iterator = orderIterator
};
}
bool OrderBook::canMatch(OrderPointer order) const
{
Price orderPrice = order->getPrice();
if (order->getSide() == Side::Buy) {
if (asks_.empty()) {
return false;
}
return orderPrice >= asks_.begin()->first; // get price from iterator
}
else {
if (bids_.empty()) {
return false;
}
return orderPrice <= bids_.begin()->first;
}
}
OrderBook::PriceLevel* OrderBook::getBestOppositeLevel(OrderPointer order)
{
if (order->getSide() == Side::Buy) {
if (asks_.empty()) {
return nullptr;
}
return &asks_.begin()->second;
}
if (bids_.empty()) {
return nullptr;
}
return &bids_.begin()->second;
}
Trade OrderBook::createTrade(
OrderPointer incomingOrder,
OrderPointer restingOrder,
Quantity quantity,
Timestamp timestamp
)
{
OrderId incomingOrderId = incomingOrder->getOrderId();
OrderId restingOrderId = restingOrder->getOrderId();
Trade trade;
trade.id = nextTradeId_;
++nextTradeId_;
if (incomingOrder->getSide() == Side::Buy) {
trade.buyOrderId = incomingOrderId;
trade.sellOrderId = restingOrderId;
}
else {
trade.buyOrderId = restingOrderId;
trade.sellOrderId = incomingOrderId;
}
trade.price = restingOrder->getPrice();
trade.quantity = quantity;
trade.timestamp = timestamp;
return trade;
}
void OrderBook::cleanupAfterTrade(
OrderPointer incomingOrder,
OrderPointer restingOrder,
PriceLevel* bestPriceLevel,
Quantity tradeQuantity
)
{
bestPriceLevel->totalQuantity -= tradeQuantity;
if (restingOrder->isFilled()) {
orders_.erase(restingOrder->getOrderId());
bestPriceLevel->orders.pop_front();
}
if (bestPriceLevel->orders.empty()) {
Price price = restingOrder->getPrice();
if (incomingOrder->getSide() == Side::Buy) {
asks_.erase(price);
}
else {
bids_.erase(price);
}
}
}
std::vector<Trade> OrderBook::matchOrder(OrderPointer incomingOrder)
{
std::vector<Trade> trades;
auto now = std::chrono::time_point_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now()
);
Timestamp arrivalTime{ now.time_since_epoch() };
while (!incomingOrder->isFilled() && canMatch(incomingOrder)) {
PriceLevel* bestPriceLevel = getBestOppositeLevel(incomingOrder);
OrderPointer restingOrder = bestPriceLevel->orders.front();
Quantity tradeQuantity = std::min(
restingOrder->getRemainingQuantity(),
incomingOrder->getRemainingQuantity()
);
Trade trade = createTrade(incomingOrder, restingOrder, tradeQuantity, arrivalTime);
incomingOrder->fill(tradeQuantity);
restingOrder->fill(tradeQuantity);
trades.push_back(trade);
trades_.push_back(trade);
cleanupAfterTrade(
incomingOrder,
restingOrder,
bestPriceLevel,
tradeQuantity
);
}
return trades;
}
std::vector<Trade> OrderBook::addOrder(Order order)
{
auto orderPointer = std::make_shared<Order>(std::move(order));
std::vector<Trade> trades;
if (canMatch(orderPointer)) {
trades = matchOrder(orderPointer);
}
if (!orderPointer->isFilled()) {
addToBook(orderPointer);
}
return trades;
}
bool OrderBook::removeOrder(OrderId orderId)
{
auto it = orders_.find(orderId);
if (it == orders_.end()) {
return false;
}
OrderEntry orderEntry = it->second;
OrderPointer order = *(orderEntry.iterator);
PriceLevel* priceLevel = nullptr;
if (orderEntry.side == Side::Buy) {
priceLevel = &bids_.at(orderEntry.price);
}
else {
priceLevel = &asks_.at(orderEntry.price);
}
priceLevel->totalQuantity -= order->getRemainingQuantity();
priceLevel->orders.erase(orderEntry.iterator);
if (priceLevel->orders.empty()) {
if (orderEntry.side == Side::Buy) {
bids_.erase(orderEntry.price);
}
else {
asks_.erase(orderEntry.price);
}
}
orders_.erase(orderId);
return true;
}
bool OrderBook::cancelOrder(OrderId orderId)
{
return removeOrder(orderId);
}
void OrderBook::printBook()
{
std::cout << "=== ASKS ===" << std::endl;
for (auto const& [key, value] : asks_) {
std::cout << std::format("{} | {} ({})\n", key.get(), value.totalQuantity.get(), value.orders.size());
}
std::cout << "-------------" << std::endl;
for (auto const& [key, value] : bids_) {
std::cout << std::format("{} | {} ({})\n", key.get(), value.totalQuantity.get(), value.orders.size());
}
std::cout << "=== BIDS ===" << std::endl;
}