-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderBook.cpp
More file actions
84 lines (70 loc) · 2.42 KB
/
OrderBook.cpp
File metadata and controls
84 lines (70 loc) · 2.42 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
#include "OrderBook.h"
#include "Trade.h"
#include <algorithm>
void OrderBook::addOrder(const Order& order) {
if (order.getType() == OrderType::BUY) {
buyOrders.push_back(order);
} else {
sellOrders.push_back(order);
}
matchOrders(order.getSymbol());
}
std::vector<Order> OrderBook::getBuyOrders(const std::string& symbol) const {
std::vector<Order> result;
for (const auto& order : buyOrders) {
if (order.getSymbol() == symbol) {
result.push_back(order);
}
}
return result;
}
std::vector<Order> OrderBook::getSellOrders(const std::string& symbol) const {
std::vector<Order> result;
for (const auto& order : sellOrders) {
if (order.getSymbol() == symbol) {
result.push_back(order);
}
}
return result;
}
std::vector<Trade> OrderBook::getTradeHistory() const {
return tradeHistory;
}
void OrderBook::matchOrders(const std::string& symbol) {
auto buyIt = buyOrders.begin();
while (buyIt != buyOrders.end()) {
if (buyIt->getSymbol() != symbol) {
++buyIt;
continue;
}
auto sellIt = sellOrders.begin();
while (sellIt != sellOrders.end()) {
if (sellIt->getSymbol() != symbol) {
++sellIt;
continue;
}
if (buyIt->getPrice() >= sellIt->getPrice()) {
int matchedQuantity = std::min(buyIt->getQuantity(), sellIt->getQuantity());
double matchedPrice = sellIt->getPrice();
Trade executedTrade("T123", symbol, matchedPrice, matchedQuantity);
tradeHistory.push_back(executedTrade);
if (buyIt->getQuantity() > matchedQuantity) {
*buyIt = Order(buyIt->getId(), symbol, buyIt->getPrice(), buyIt->getQuantity() - matchedQuantity, buyIt->getType());
} else {
buyIt = buyOrders.erase(buyIt);
}
if (sellIt->getQuantity() > matchedQuantity) {
*sellIt = Order(sellIt->getId(), symbol, sellIt->getPrice(), sellIt->getQuantity() - matchedQuantity, sellIt->getType());
} else {
sellIt = sellOrders.erase(sellIt);
}
break;
} else {
++sellIt;
}
}
if (sellIt == sellOrders.end()) {
++buyIt;
}
}
}