Spaces:
Sleeping
Sleeping
File size: 7,687 Bytes
ba6114e | 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 | #include "core/order_book.hpp"
#include <stdexcept>
#include <cassert>
namespace hft {
OrderBook::OrderBook(std::string symbol) : symbol_(std::move(symbol)) {}
void OrderBook::notify_order(const Order& o) {
if (order_cb_) order_cb_(o);
}
Trade OrderBook::make_trade(Order& buy, Order& sell, Price px, Quantity qty) {
Trade t;
t.trade_id = next_trade_id_++;
t.buy_order_id = buy.id;
t.sell_order_id = sell.id;
t.symbol = symbol_;
t.price = px;
t.qty = qty;
t.timestamp = now_ns();
buy.filled_qty += qty;
sell.filled_qty += qty;
buy.status = (buy.remaining() == 0) ? OrderStatus::FILLED : OrderStatus::PARTIALLY_FILLED;
sell.status = (sell.remaining() == 0) ? OrderStatus::FILLED : OrderStatus::PARTIALLY_FILLED;
return t;
}
void OrderBook::add_to_book(Order& order) {
auto& book = (order.side == Side::BUY) ? bids_ : asks_;
auto& level = book[order.price];
level.price = order.price;
level.orders.push_back(&order);
level.total_qty += order.remaining();
orders_[order.id] = ℴ
}
void OrderBook::remove_from_book(Order& order) {
auto& book = (order.side == Side::BUY) ? bids_ : asks_;
auto it = book.find(order.price);
if (it == book.end()) return;
auto& level = it->second;
Quantity removed = 0;
level.orders.remove_if([&](Order* o) {
if (o->id == order.id) {
removed = o->remaining();
return true;
}
return false;
});
level.total_qty -= removed;
if (level.empty()) book.erase(it);
orders_.erase(order.id);
}
std::vector<Trade> OrderBook::try_match(Order& incoming, bool fok_check) {
std::vector<Trade> trades;
if (fok_check) {
Quantity available = 0;
if (incoming.side == Side::BUY) {
for (auto& [px, lvl] : asks_) {
if (incoming.type != OrderType::MARKET && px > incoming.price) break;
available += lvl.total_qty;
if (available >= incoming.qty) break;
}
} else {
for (auto rit = bids_.rbegin(); rit != bids_.rend(); ++rit) {
if (incoming.type != OrderType::MARKET && rit->first < incoming.price) break;
available += rit->second.total_qty;
if (available >= incoming.qty) break;
}
}
if (available < incoming.qty) {
incoming.status = OrderStatus::EXPIRED;
notify_order(incoming);
return trades;
}
}
if (incoming.side == Side::BUY) {
for (auto it = asks_.begin(); it != asks_.end() && incoming.remaining() > 0; ) {
auto& [px, level] = *it;
if (incoming.type == OrderType::LIMIT || incoming.type == OrderType::IOC) {
if (px > incoming.price) break;
}
while (!level.orders.empty() && incoming.remaining() > 0) {
Order* resting = level.orders.front();
Quantity fill_qty = std::min(incoming.remaining(), resting->remaining());
Price fill_px = resting->price;
auto trade = make_trade(incoming, *resting, fill_px, fill_qty);
trades.push_back(trade);
if (trade_cb_) trade_cb_(trade);
level.total_qty -= fill_qty;
notify_order(*resting);
notify_order(incoming);
if (resting->is_done()) {
level.orders.pop_front();
orders_.erase(resting->id);
}
}
if (level.empty()) {
it = asks_.erase(it);
} else {
++it;
}
}
} else {
// Sell-side: match against bids (highest first = rbegin)
// We iterate from the back using a reverse approach but erase safely.
while (!bids_.empty() && incoming.remaining() > 0) {
auto it = std::prev(bids_.end()); // best bid = last element
auto& [px, level] = *it;
if (incoming.type == OrderType::LIMIT || incoming.type == OrderType::IOC) {
if (px < incoming.price) break;
}
while (!level.orders.empty() && incoming.remaining() > 0) {
Order* resting = level.orders.front();
Quantity fill_qty = std::min(incoming.remaining(), resting->remaining());
Price fill_px = resting->price;
auto trade = make_trade(*resting, incoming, fill_px, fill_qty);
trades.push_back(trade);
if (trade_cb_) trade_cb_(trade);
level.total_qty -= fill_qty;
notify_order(*resting);
notify_order(incoming);
if (resting->is_done()) {
level.orders.pop_front();
orders_.erase(resting->id);
}
}
if (level.empty()) {
bids_.erase(it);
} else {
break; // Remaining qty at this level, stop matching
}
}
}
return trades;
}
std::vector<Trade> OrderBook::add_order(Order& order) {
std::vector<Trade> trades;
order.status = OrderStatus::NEW;
notify_order(order);
switch (order.type) {
case OrderType::LIMIT: {
trades = try_match(order);
if (!order.is_done()) add_to_book(order);
break;
}
case OrderType::MARKET: {
trades = try_match(order);
if (order.remaining() > 0) {
order.status = OrderStatus::CANCELLED;
notify_order(order);
}
break;
}
case OrderType::IOC: {
trades = try_match(order);
if (order.remaining() > 0 && !order.is_done()) {
order.status = OrderStatus::EXPIRED;
notify_order(order);
}
break;
}
case OrderType::FOK: {
trades = try_match(order, true);
break;
}
}
return trades;
}
bool OrderBook::cancel_order(OrderId id) {
auto it = orders_.find(id);
if (it == orders_.end()) return false;
Order* o = it->second;
remove_from_book(*o);
o->status = OrderStatus::CANCELLED;
notify_order(*o);
return true;
}
bool OrderBook::modify_order(OrderId id, Price new_price, Quantity new_qty) {
auto it = orders_.find(id);
if (it == orders_.end()) return false;
Order* o = it->second;
if (new_qty <= o->filled_qty) return false;
remove_from_book(*o);
o->price = new_price;
o->qty = new_qty;
add_to_book(*o);
return true;
}
std::optional<Order*> OrderBook::find_order(OrderId id) {
auto it = orders_.find(id);
if (it == orders_.end()) return std::nullopt;
return it->second;
}
OrderBookSnapshot OrderBook::snapshot(int depth) const {
OrderBookSnapshot snap;
snap.symbol = symbol_;
snap.timestamp = now_ns();
int cnt = 0;
for (auto it = bids_.rbegin(); it != bids_.rend() && cnt < depth; ++it, ++cnt) {
L2Level l;
l.price = it->first;
l.qty = it->second.total_qty;
l.order_count = (int)it->second.orders.size();
snap.bids.push_back(l);
}
cnt = 0;
for (auto it = asks_.begin(); it != asks_.end() && cnt < depth; ++it, ++cnt) {
L2Level l;
l.price = it->first;
l.qty = it->second.total_qty;
l.order_count = (int)it->second.orders.size();
snap.asks.push_back(l);
}
return snap;
}
} // namespace hft
|