11#include <unordered_map>
13#include <slick/object_pool.hpp>
14#include <slick/queue.hpp>
18#include <slick/orderbook/orderbook_l3.hpp>
20#include <slick/orderbook/observer.hpp>
21#include <boost/uuid/uuid.hpp>
22#include <boost/uuid/uuid_io.hpp>
23#include <boost/uuid/random_generator.hpp>
24#include <boost/lexical_cast.hpp>
38 return static_cast<orderbook::Side
>(side);
43class OrderBook :
public OrderBookL3,
public orderbook::IOrderBookObserver,
public std::enable_shared_from_this<OrderBook> {
85 using OrderBookL3::addOrder;
86 using OrderBookL3::modifyOrder;
87 using OrderBookL3::deleteOrder;
89 void addOrder(
Order* order, uint64_t timestamp, uint64_t seq_num = 0,
bool is_last_in_batch =
true) {
99 seq_num, is_last_in_batch);
106 virtual void addBookOrder(uint64_t order_id, slick::orderbook::Side book_side,
price_t price,
qty_t qty, uint64_t timestamp, uint64_t seq_num,
bool is_last_in_batch =
true) = 0;
108 void deleteOrder(
Order* order, uint64_t timestamp, uint64_t seq_num = 0,
bool is_last_in_batch =
true) {
109 deleteOrder(order->
id, timestamp, seq_num, is_last_in_batch);
137 uint64_t seq_num = 0,
bool is_last_in_batch =
true) {
139 if (it ==
orders_.end()) [[unlikely]] {
140 order->
price = new_price;
143 it =
orders_.emplace(order->
id, order).first;
152 else if (new_price != order->
price) {
153 order->
price = new_price;
174 std::vector<std::tuple<uint64_t, orderbook::Side, price_t, qty_t, time_t, uint64_t>> sim_orders;
175 sim_orders.reserve(
orders_.size());
176 for (
auto& [
id, order] :
orders_) {
177 if (order->leaves_quantity > 0) {
178 sim_orders.emplace_back(
id,
to_book_side(order->side), order->price,
179 order->leaves_quantity, order->last_update_time, order->priority);
182 OrderBookL3::clear();
184 for (
auto& [
id, side, price, qty, ts, prio] : sim_orders) {
185 OrderBookL3::addOrder(
id, side, price, qty, ts, prio, 0,
false);
189 bool executeOrder(slick::orderbook::OrderId order_id, slick::orderbook::Quantity executed_quantity, uint64_t timestamp, uint64_t seq_num = 0,
bool is_last_in_batch =
true)
override {
199 if (seq_num > 0 && seq_num < getLastSeqNum()) {
206 auto rt = OrderBookL3::executeOrder(order_id, executed_quantity, timestamp, seq_num, is_last_in_batch);
207 if (order && order->leaves_quantity == 0) {
208 if (!order->client_order_id.empty()) {
211 if (!order->order_id.empty()) {
243 return next_priority_.fetch_add(1, std::memory_order_relaxed) + 1;
275template<OrderBookType BookType>
284 void addBookOrder(uint64_t order_id, slick::orderbook::Side book_side,
price_t price,
qty_t qty, uint64_t timestamp, uint64_t seq_num,
bool is_last_in_batch =
true)
override;
306 static thread_local boost::uuids::random_generator uuid_gen;
307 const boost::uuids::uuid u = uuid_gen();
312 "order_id must hold a rendered UUID exactly");
313 boost::uuids::to_chars(u, order->order_id.data());
314 order->order_id.data()[36] =
'\0';
317 order->request_tag = 0;
319 order->last_update_time = order->created_time;
320 order->resetFillAccounting();
334 if (update.quantity == 0) {
341 auto *our_order =
findOrder(update.order_id);
344 if (update.price != update.old_price) {
347 it->second -= update.old_qty;
352 it->second += update.quantity;
353 }
else if (update.quantity) {
360 it->second += update.quantity - update.old_qty;
362 else if (update.quantity) {
367 else if (update.quantity == 0 && our_order->quantity != update.quantity) {
368 our_order->leaves_quantity = 0;
383 auto it =
orders_.find(order_id);
384 return it !=
orders_.end() ? it->second :
nullptr;
388template<OrderBookType BookType>
391 slick::orderbook::Side book_side,
396 bool is_last_in_batch) {
400template<OrderBookType BookType>
402 std::stringstream ss;
403 ss <<
"OrderBook: " <<
symbol_ <<
"\n";
404 auto &sell_levels = getLevelsL3(orderbook::Side::Sell);
406 auto it_sell = std::make_reverse_iterator(std::ranges::next(sell_levels.begin(), 20, sell_levels.end()));
407 for (; it_sell != sell_levels.rend(); ++it_sell) {
408 ss << std::right << std::setw(50) << std::format(
"{:.2f}",
to_price_double(it_sell->first));
409 ss << std::right << std::setw(20) << std::format(
"{:.8f}",
to_qty_double(it_sell->second.total_quantity));
410 ss << std::right << std::setw(10) << it_sell->second.orderCount() <<
"\n";
413 auto &buy_levels = getLevelsL3(orderbook::Side::Buy);
415 for (
auto it_buy = buy_levels.begin(); it_buy != buy_levels.end() && i < 20; ++it_buy, ++i) {
416 ss << std::right << std::setw(10) << it_buy->second.orderCount();
417 ss << std::right << std::setw(20) << std::format(
"{:.8f}",
to_qty_double(it_buy->second.total_quantity));
418 ss << std::right << std::setw(20) << std::format(
"{:.2f}",
to_price_double(it_buy->first)) <<
"\n";
426 auto &ask_levels = getLevelsL3(orderbook::Side::Sell);
428 for (
auto it = ask_levels.begin(); it != ask_levels.end() && i < 10; ++it, ++i) {
429 auto &levels = book_update.
sell;
430 levels[i].
price = it->first;
431 levels[i].qty = it->second.getTotalQuantity();
432 levels[i].num_orders =
static_cast<uint32_t
>(it->second.orderCount());
435 auto &bid_levels = getLevelsL3(orderbook::Side::Buy);
436 for (
auto it = bid_levels.begin(); it != bid_levels.end() && i < 10; ++it, ++i) {
437 auto &levels = book_update.
buy;
438 levels[i].
price = it->first;
439 levels[i].qty = it->second.getTotalQuantity();
440 levels[i].num_orders =
static_cast<uint32_t
>(it->second.orderCount());
446 auto &ask_levels = getLevelsL3(orderbook::Side::Sell);
447 auto &bid_levels = getLevelsL3(orderbook::Side::Buy);
449 auto index = md_update_queue.reserve(
static_cast<uint32_t
>(sz));
451 memcpy(update->symbol,
symbol_.data(),
sizeof(update->symbol));
461 auto *snapshot =
reinterpret_cast<BookSnapshot*
>(response->data);
462 snapshot->
num_bid =
static_cast<uint32_t
>(bid_levels.size());
463 snapshot->num_ask =
static_cast<uint32_t
>(ask_levels.size());
465 auto *levels =
reinterpret_cast<MDLevel*
>(snapshot->levels);
467 for (
auto it = bid_levels.begin(); it != bid_levels.end(); ++it, ++levels) {
468 levels->price = it->first;
469 levels->qty = it->second.total_quantity;
470 levels->num_orders =
static_cast<uint32_t
>(it->second.orderCount());
472 for (
auto it = ask_levels.begin(); it != ask_levels.end(); ++it, ++levels) {
473 levels->price = it->first;
474 levels->qty = it->second.total_quantity;
475 levels->num_orders =
static_cast<uint32_t
>(it->second.orderCount());
477 md_update_queue.publish(index,
static_cast<uint32_t
>(sz));
482 auto &ask_levels = getLevelsL3(orderbook::Side::Sell);
483 auto &bid_levels = getLevelsL3(orderbook::Side::Buy);
485 auto index = md_update_queue.reserve(
static_cast<uint32_t
>(sz));
487 memcpy(update->symbol,
symbol_.data(),
sizeof(update->symbol));
491 auto *snapshot =
reinterpret_cast<BookSnapshot*
>(update->data);
492 snapshot->
num_bid =
static_cast<uint32_t
>(bid_levels.size());
493 snapshot->num_ask =
static_cast<uint32_t
>(ask_levels.size());
495 auto *levels =
reinterpret_cast<MDLevel*
>(snapshot->levels);
497 for (
auto it = bid_levels.begin(); it != bid_levels.end(); ++it, ++levels) {
498 levels->price = it->first;
499 levels->qty = it->second.total_quantity;
500 levels->num_orders =
static_cast<uint32_t
>(it->second.orderCount());
502 for (
auto it = ask_levels.begin(); it != ask_levels.end(); ++it, ++levels) {
503 levels->price = it->first;
504 levels->qty = it->second.total_quantity;
505 levels->num_orders =
static_cast<uint32_t
>(it->second.orderCount());
507 md_update_queue.publish(index,
static_cast<uint32_t
>(sz));
void populateL2Snapshot(slick::queue< uint8_t > &md_update_queue) override
void populateMDBookUpdate(MDBookUpdate &book_update) override
std::string to_string() const override
void populateL2SubscriptionResponse(slick::queue< uint8_t > &md_update_queue, uint8_t channel) override
~OrderBookImpl() override=default
OrderBookImpl(symid_t sid, std::string_view symbol, Venue venue, uint_fast32_t buffer_size=65536)
void addBookOrder(uint64_t order_id, slick::orderbook::Side book_side, price_t price, qty_t qty, uint64_t timestamp, uint64_t seq_num, bool is_last_in_batch=true) override
Rest phantom (market-data) liquidity.
Order * findOrderByClientOrderId(std::string_view client_order_id)
utils::StringViewEq StringViewEq
static uint64_t nextOrderPriority() noexcept
One sequence shared by every book, so it is drawn from atomically: each exchange runs on its own thre...
Order * findOrder(uint64_t id)
void onPriceLevelUpdate(const PriceLevelUpdate &update) override
qty_t getMDLevelQty(price_t price) const
std::unordered_map< utils::fixed_string< 37 >, Order *, StringViewHash, StringViewEq > orders_by_order_id_
~OrderBook() override=default
virtual std::string to_string() const =0
uint64_t lastSeqNum() const noexcept
virtual void populateL2SubscriptionResponse(slick::queue< uint8_t > &md_update_queue, uint8_t channel)=0
OrderUpdate last_order_update_
slick::ObjectPool< Order > order_buffer_
Order * findOrderByOrderId(std::string_view order_id)
std::unordered_map< utils::fixed_string< 37 >, Order *, StringViewHash, StringViewEq > orders_by_client_order_id_
utils::StringViewHash StringViewHash
void onOrderUpdate(const OrderUpdate &update) override
time_t lastUpdateTime() const noexcept
OrderBook(symid_t sid, std::string_view symbol, Venue venue, uint_fast32_t buffer_size=65536)
const symbol_name_t & symbolName() const noexcept
Wire-ready, so publishers copy it as a fixed block instead of reading sizeof(field) bytes out of a sh...
void modifyOrder(Order *order, price_t new_price, qty_t new_qty, uint64_t timestamp, uint64_t seq_num=0, bool is_last_in_batch=true)
virtual void populateMDBookUpdate(MDBookUpdate &book_update)=0
virtual void addBookOrder(uint64_t order_id, slick::orderbook::Side book_side, price_t price, qty_t qty, uint64_t timestamp, uint64_t seq_num, bool is_last_in_batch=true)=0
Rest phantom (market-data) liquidity.
bool executeOrder(slick::orderbook::OrderId order_id, slick::orderbook::Quantity executed_quantity, uint64_t timestamp, uint64_t seq_num=0, bool is_last_in_batch=true) override
void deleteOrder(Order *order, uint64_t timestamp, uint64_t seq_num=0, bool is_last_in_batch=true)
static std::atomic< uint64_t > next_priority_
void freeOrder(Order *order)
symid_t sid() const noexcept
std::unordered_map< price_t, qty_t > feed_md_level_quantity_
void deleteOrder(Order *order)
void setLastUpdate(time_t timestamp, uint64_t seq_num) noexcept
virtual void populateL2Snapshot(slick::queue< uint8_t > &md_update_queue)=0
void addOrder(Order *order, uint64_t timestamp, uint64_t seq_num=0, bool is_last_in_batch=true)
std::unordered_map< uint64_t, Order * > orders_
bool empty() const noexcept
uint64_t nextOrderId() noexcept
void executeOrder(Order *order, price_t price, qty_t executed_quantity, time_t timestamp)
uint64_t get_current_time_ns()
slick::orderbook::Timestamp Timestamp
slick::orderbook::SymbolId SymbolId
slick::orderbook::PriceLevelUpdate PriceLevelUpdate
slick::orderbook::TopOfBook TopOfBook
constexpr double to_price_double(price_t price)
slick::orderbook::OrderUpdate OrderUpdate
slick::orderbook::OrderBookL3 OrderBookL3
slick::orderbook::IOrderBookObserver IOrderBookObserver
utils::fixed_string< sizeof(MarketDataUpdate::symbol)> symbol_name_t
An instrument name at its wire width.
orderbook::Side to_book_side(Side side)
constexpr double to_qty_double(qty_t qty)
utils::fixed_string< 37 > client_order_id
utils::fixed_string< 37 > order_id
Transparent hash/equality for maps keyed by fixed_string.