1#include <slick/logger.hpp>
23 const nlohmann::json &config)
24 :
venue_(venue),
instance_(config.contains(
"name") && config[
"name"].is_string() ? config[
"name"].get<std::string>() : std::string()),
request_queue_(config.value(
"request_queue_size", 1048576), config.contains(
"request_queue_shm_name") ? config[
"request_queue_shm_name"].get_ref<const std::string &>().c_str() : nullptr),
response_queue_(config.value(
"response_queue_size", 1048576), config.contains(
"response_queue_shm_name") ? config[
"response_queue_shm_name"].get_ref<const std::string &>().c_str() : nullptr),
md_queue_(config.value(
"md_queue_size", 16777216), config.contains(
"md_queue_shm_name") ? config[
"md_queue_shm_name"].get_ref<const std::string &>().c_str() : nullptr),
enabled_(config.value(
"enabled", true))
26 if (!config.contains(
"order_gateway"))
28 throw std::runtime_error(std::format(
"Exchange {} Missing order_gateway config", to_string(venue)));
30 if (!config.contains(
"md_publisher"))
32 throw std::runtime_error(std::format(
"Exchange {} Missing md_publisher config", to_string(venue)));
35 if (config.contains(
"self_match_prevention"))
37 const auto &mode = config[
"self_match_prevention"].get_ref<const std::string &>();
38 smp_mode_ = to_smp_mode(mode);
39 if (smp_mode_ == SelfMatchPreventionMode::NONE && mode !=
"none")
41 LOG_WARN(
"Exchange {} unknown self_match_prevention '{}', self-match prevention disabled. "
42 "Expected one of: none, cancel_resting, cancel_newest",
43 to_string(venue), mode);
47 LOG_INFO(
"Exchange {} self-match prevention: {}", to_string(venue), to_string(smp_mode_));
50 matching_keys_unread_ = config.contains(
"matching_algorithm") || config.contains(
"pro_rata");
64 LOG_WARN(
"Exchange {} matches FIFO only; matching_algorithm and pro_rata are ignored",
to_string(
venue_));
68 run_.store(
true, std::memory_order_release);
99 while (
run_.load(std::memory_order_relaxed)) {
107 std::vector<cli::CliEndpoint *> out;
111 out.push_back(endpoint);
118 std::vector<FeedInfo> out;
139 if (!
run_.exchange(
false, std::memory_order_acq_rel))
180 constexpr int max_batch = 1024;
181 for (
int processed = 0; processed < max_batch; ++processed)
188 switch (request->msg_type)
232 std::string_view key(user_id, len);
245 if (std::ranges::any_of(
matching_engines_, [](
const auto &slot) {
return slot !=
nullptr; }))
247 throw std::logic_error(std::format(
"Exchange {}: configureMatching after a symbol was assigned an engine",
258 assert(symbol->
matching_engine_ ==
nullptr &&
"symbol is already bound to an exchange's engine");
275 auto *symbol = symbol_mgr.getSymbol(request.
symbol,
venue_);
283 if (msg.client_order_id[0] !=
'\0')
285 auto *order = symbol->order_book_->findOrderByClientOrderId(msg.client_order_id);
286 if (order) [[unlikely]]
288 LOG_WARN(std::format(
"ClientOrderId {} already exist", msg.client_order_id));
293 Order *order = symbol->order_book_->allocateOrder();
294 order->
symbol = symbol->symbol_;
300 order->
side = msg.side;
301 order->
type = msg.type;
303 order->
price = msg.price;
305 order->
type = msg.type;
311 auto [reject_reason, trade_summaries] = symbol->addOrder(order, request.
time_stamp);
313 if (!trade_summaries.empty())
315 for (
const auto &summary : trade_summaries)
337 auto *symbol = symbol_mgr.getSymbol(request.
symbol,
venue_);
356 LOG_WARN(std::format(
"{} OrderId {} not found for modification", symbol->symbol_.view(), request.
modify_order.
order_id));
373 if (!trade_summaries.empty())
375 for (
const auto &summary : trade_summaries)
393 auto *symbol = symbol_mgr.getSymbol(request.
symbol,
venue_);
412 LOG_WARN(std::format(
"{} OrderId {} not found for cancellation", symbol->symbol_.view(), request.
cancel_order.
order_id));
419 symbol->cancelOrder(order, request.
time_stamp);
436 memcpy(update->symbol, request.
symbol,
sizeof(update->symbol));
442 rsp->reject_reason = reason;
453 std::memcpy(update->symbol, symbol.
data(),
sizeof(update->symbol));
464 std::memcpy(response.symbol, request.
symbol,
sizeof(response.symbol));
465 std::memcpy(response.user_id, request.
add_order.
user_id,
sizeof(response.user_id));
467 std::memset(response.order_id, 0,
sizeof(response.order_id));
470 response.error_message[0] =
'\0';
471 response.order_num = 0;
473 response.aggressor =
false;
480 response.cum_qty = 0;
481 response.leaves_qty = 0;
482 response.reject_reason = reason;
495 std::memcpy(response.symbol, request.
symbol,
sizeof(response.symbol));
496 std::memcpy(response.user_id, msg.user_id,
sizeof(response.user_id));
497 std::memcpy(response.client_order_id, msg.client_order_id,
sizeof(response.client_order_id));
498 std::memcpy(response.order_id, msg.order_id,
sizeof(response.order_id));
499 response.error_message[0] =
'\0';
500 response.order_num = 0;
502 response.aggressor =
false;
506 response.price = msg.new_price;
507 response.qty = msg.new_qty;
508 response.cum_qty = 0;
509 response.leaves_qty = 0;
510 response.reject_reason = reason;
520 std::memcpy(response.symbol, request.
symbol,
sizeof(response.symbol));
524 std::memcpy(response.user_id, msg.user_id,
sizeof(response.user_id));
525 std::memcpy(response.client_order_id, msg.client_order_id,
sizeof(response.client_order_id));
526 std::memcpy(response.order_id, msg.order_id,
sizeof(response.order_id));
527 response.error_message[0] =
'\0';
528 response.order_num = 0;
530 response.aggressor =
false;
536 response.cum_qty = 0;
537 response.leaves_qty = 0;
538 response.reject_reason = reason;
586 std::memcpy(update->symbol, symbol.
data(),
sizeof(update->symbol));
587 auto *level_update =
reinterpret_cast<MDLevelUpdate *
>(update->data);
588 level_update->
num_level_update =
static_cast<uint32_t
>(level_updates.size());
589 std::memcpy(level_update->levels, level_updates.data(), level_updates.size() *
sizeof(
MDLevel));
600 std::memcpy(update->symbol, symbol.
data(),
sizeof(update->symbol));
601 auto *order_update =
reinterpret_cast<MDOrderUpdate *
>(update->data);
602 order_update->
num_orders =
static_cast<uint32_t
>(order_updates.size());
603 std::memcpy(order_update->orders, order_updates.data(), order_updates.size() *
sizeof(
MDOrder));
620 std::memcpy(update->symbol, symbol->
symbol_.
data(),
sizeof(update->symbol));
621 auto summary =
reinterpret_cast<TradeSummary *
>(update->data);
623 summary->trade_id = trade_id;
624 summary->security_id = symbol->
id_;
626 summary->price = trade_summary.
price;
627 summary->qty = trade_summary.
qty;
628 summary->num_orders = trade_summary.
num_orders;
629 for (
size_t i = 0; i < trade_summary.
Trades.size(); ++i)
631 summary->trades[i].order_id = trade_summary.
Trades[i].order_id;
632 summary->trades[i].qty = trade_summary.
Trades[i].qty;
637 .trade_id = trade_id,
638 .event_time =
static_cast<uint64_t
>(trade_summary.
timestamp),
640 .price = trade_summary.
price,
641 .qty = trade_summary.
qty,
649 auto num_trades =
static_cast<uint32_t
>(history.size());
654 std::memcpy(update->symbol, symbol->
symbol_.
data(),
sizeof(update->symbol));
669 auto reflected_in_book = [book_time](
const MDTrade &trade) {
674 auto *trades = snapshot->
trades;
675 uint32_t num_snapshot = 0;
676 uint32_t num_update = 0;
684 for (uint32_t i = 0; i < num_trades; ++i)
686 const auto *trade = history[i];
687 if (trade ==
nullptr) [[unlikely]]
691 if (reflected_in_book(*trade))
697 for (uint32_t i = 0; i < num_trades; ++i)
699 const auto *trade = history[i];
700 if (trade ==
nullptr) [[unlikely]]
704 if (!reflected_in_book(*trade))
710 snapshot->num_snapshot = num_snapshot;
711 snapshot->num_update = num_update;
716 time_t event_time, uint64_t seq_num,
bool end_event)
719 auto [level, index] = book.getLevel(
to_book_side(side), price);
734 auto unreflected = symbol->
takeTradedQty(side, price, event_time);
737 target_qty = target_qty > unreflected ? target_qty - unreflected : 0;
740 auto md_level_qty = book.getMDLevelQty(price);
741 if (target_qty > md_level_qty)
744 auto size = target_qty - md_level_qty;
751 else if (target_qty < md_level_qty)
763 auto diff = md_level_qty - target_qty;
765 for (
auto it = level->orders.rbegin(); it != level->orders.rend() && diff > 0; ++it)
774 auto to_reduce = std::min<qty_t>(diff, order.quantity);
776 .order_id = order.order_id,
777 .new_qty = order.quantity - to_reduce,
778 .priority = order.priority});
785 book.modifyOrder(reduction.order_id, price, reduction.new_qty, event_time,
786 reduction.priority, seq_num,
795 const auto timestamp =
event.transact_time;
809 const auto *resting = book.OrderBookL3::findOrder(event.
book_order_id);
843 qty_t qty =
event.qty;
855 [[maybe_unused]]
const bool added = book.OrderBookL3::addOrder(
866 qty_t qty =
event.qty;
904 response.order_type = order->
type;
905 response.price = order->
price;
908 response.cum_qty = 0;
910 assert(response.leaves_qty == response.qty);
912 response.request_time = request_time;
913 response.side = order->
side;
926 response.order_type = order->
type;
927 response.request_time = request_time;
928 response.price = order->
price;
931 response.cum_qty = 0;
934 response.side = order->
side;
947 response.order_type = order->
type;
948 response.request_time = request_time;
949 response.price = order->
price;
959 response.side = order->
side;
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...
virtual void populateMDBookUpdate(MDBookUpdate &book_update)=0
static SymbolManager & instance()
virtual std::tuple< OrdRejectReason, std::vector< TradeSummaryInfo > > match(Order *order, price_t order_price, qty_t order_qty, OrderBook &book, time_t request_time, time_t event_time, uint64_t seq_num=0, SelfMatchPreventionMode smp_mode=SelfMatchPreventionMode::NONE)=0
queue< Request > request_queue_
FeedInfo feedInfo(md_feed::FeedKind kind, std::string_view name={}) const
This exchange's feed of kind, by the feed's name or, when empty, the exchange's own.
void publishMDOrderUpdate(const symbol_name_t &symbol, const std::vector< MDOrder > &order_updates)
virtual void handleMdUnsubscription(const Request &)
std::shared_ptr< md_feed::MDFeed > md_feed_
void handleNewOrderRequest(const Request &request)
void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel)
Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history,...
uint64_t nextVenueTradeId() noexcept
Public trade ids, one independent sequence per venue.
void applyMarketOrder(Symbol *symbol, const MarketOrderEvent &event)
Rests, changes or removes a market order as a phantom order.
void flushMarketDataCaches(Symbol *symbol)
Publish and clear whatever market data the book produced while handling a request.
void configureMatching(const nlohmann::json &config)
Reads matching_algorithm and pro_rata from the venue's config.
SelfMatchPreventionMode smp_mode_
Self-match prevention mode applied to every symbol on this venue, from the self_match_prevention conf...
virtual void poll()
One iteration of the exchange thread's loop, called continuously between start() and stop().
void publishMDBookUpdate(symid_t sid, OrderBook &order_book, const std::array< uint8_t, 2 > &indices)
uint_fast64_t order_request_cursor_
bool publish_order_updates_
Whether flushMarketDataCaches publishes the per-order (MDUpdateType::ORDER) frames the book produces.
queue< uint8_t > md_queue_
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
void forEachFeed(Fn &&fn) const
Calls fn(MDFeed &) on md_feed_ and each of md_feeds_.
void replayMarketTrade(Symbol *symbol, const MarketTradeEvent &event)
Replays a market trade as an aggressor order at the trade's price and quantity, so a client order que...
std::string instance_
The config's name, one per instance of a venue that has several. Empty without one.
void markMarketChanged(Symbol *symbol)
void reconcilePhantomQty(Symbol *symbol, Side side, price_t price, qty_t target_qty, time_t event_time, uint64_t seq_num, bool end_event)
Adjusts the phantom (market-mirroring) quantity at an existing (side, price) level toward target_qty,...
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
Feeds owned by the exchange and managed by base start()/stop().
void rejectModifyOrderRequest(const Request &request, OrdRejectReason reason)
Exchange(Venue venue, const nlohmann::json &config)
void restMarketOrder(Symbol *symbol, const MarketOrderEvent &event)
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
void publishTradeSummary(Symbol *symbol, const TradeSummaryInfo &trade_summary)
Publishes one trade onto the instrument's public tape and records it in the symbol's recent-trade his...
engine::MatchingConfig matching_
The engine assignMatching hands out. FIFO unless configureMatching says otherwise.
void publishLevelUpdate(const symbol_name_t &symbol, const std::vector< MDLevel > &level_updates)
void rejectMdSubscription(const Request &request, MDSubscriptionRejectReason reason)
std::unordered_map< utils::fixed_string< sizeof(AddOrderMessage::user_id)>, int, utils::StringViewHash, utils::StringViewEq > client_ids_
Keys use the width of AddOrderMessage::user_id.
virtual OrdRejectReason newOrderAdmission() const noexcept
virtual std::vector< FeedInfo > enabledFeeds() const
The market-data feeds the config enables: those in md_feed_ and md_feeds_.
void handleCancelOrderRequest(const Request &request)
int clientIdFor(const char *user_id)
Resolves an order's user_id to the integer identity self-match prevention compares.
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
void sendOrderReplacePending(const Order *order, time_t request_time)
void flushMarketEvents()
Publishes every symbol a market event changed since the last call.
bool matching_keys_unread_
The config sets matching keys and configureMatching has not read them, so start() warns that this ven...
std::array< std::unique_ptr< engine::MatchingEngine >, engine::MatchingEngine::Type::__count__ > matching_engines_
void handleModifyOrderRequest(const Request &request)
void sendOrderCancelPending(const Order *order, time_t request_time)
void sendOrderNewPending(const Order *order, time_t request_time)
std::vector< Symbol * > market_changed_symbols_
Symbols a market event has changed and not yet published.
virtual void handleMdSubscription(const Request &)
void rejectCancelOrderRequest(const Request &request, OrdRejectReason reason)
queue< OrderResponse > response_queue_
void publishMdSubscriptionResponse(const symbol_name_t &symbol, uint8_t channel)
Publishes an accepted subscription response without a snapshot payload.
std::vector< cli::CliEndpoint * > feedCliEndpoints() const
The CLI endpoints of md_feed_ and md_feeds_ (a pcap feed's pcap/<venue>/<feed>).
void rejectNewOrderRequest(const Request &request, OrdRejectReason reason)
std::vector< PhantomReduction > phantom_reductions_
virtual std::string feedName() const
Its name, different from the venue's other feeds'. Empty for a feed without one.
virtual FeedKind feedKind() const noexcept
virtual cli::CliEndpoint * cliEndpoint() noexcept
Where the CLI reaches the feed's own commands, named by the feed.
const char * data() const noexcept
std::string instance_path(std::string_view venue, std::string_view instance)
<venue>/<instance>, or <venue> alone for the one instance of a venue configured without a list of the...
std::string venue_path(std::string_view venue, std::string_view rest={})
<venue>[/<rest>], the venue lowercased (CME -> cme).
std::unique_ptr< MatchingEngine > createMatchingEngine(const MatchingConfig &config, slick::queue< OrderResponse > &response_queue)
Helpers for a venue whose one config entry describes several independent exchange instances,...
FeedKind
Where a feed's market data comes from.
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
uint64_t nextOrderId() noexcept
uint64_t get_current_time_ns()
MDSubscriptionRejectReason
constexpr price_t NULL_PRICE
void setOrderIdentity(OrderResponse &response, const Order &order) noexcept
Fills a response's identity from an order: the symbol/user_id/client_order_id/ order_id header in one...
@ CLIENT_ORDER_ID_ALREADY_EXISTS
@ F_NOT_IN_BOOK
On an MDTrade: this print was never applied to the order book.
utils::fixed_string< sizeof(MarketDataUpdate::symbol)> symbol_name_t
An instrument name at its wire width.
constexpr const char * to_string(FeedState state) noexcept
orderbook::Side to_book_side(Side side)
@ TRADE_SUMMARY
One executed trade.
uint32_t num_level_update
Every order-book change one request (or feed event) produced, in book order.
Payload of a SUB_RESPONSE for a venue's trade channel.
MDTrade trades[0]
The snapshot block, then the update block, each contiguous and each chronological within itself.
utils::fixed_string< 32 > symbol
utils::fixed_string< 37 > client_order_id
utils::fixed_string< 37 > user_id
TimeInForce time_in_force
uint64_t last_update_time
uint64_t request_tag
Request::request_tag of the last request this order accepted, echoed on its responses.
void resetFillAccounting(qty_t new_qty=0) noexcept
AddOrderMessage add_order
uint64_t request_tag
Opaque correlation token, carried onto the order and echoed on every OrderResponse that order produce...
CancelOrderMessage cancel_order
ModifyOrderMessage modify_order
MDSubscriptionMessage md_subscription
std::vector< Trade > Trades
static MatchingConfig from_json(const nlohmann::json &config)
Reads matching_algorithm ("fifo" by default, or "pro_rata") and, for pro-rata, the pro_rata block: lo...
Scratch for reconcilePhantomQty, reused so the reduction path allocates nothing.
One enabled market-data feed, as Exchange::enabledFeeds() reports it.
One of the venue's own orders entering, changing or leaving the book, from an order-by-order feed,...
uint64_t book_order_id
The simulator's id for this order, from utils::nextOrderId(), so it can never collide with a client o...
bool requeue
On CHANGE: the order lost its place, and book_priority is a new one.
price_t price
The price it rests at.
qty_t qty
Remaining visible quantity, 0 on DELETE.
uint64_t book_priority
The order's place in its level's queue: drawn from OrderBook::nextOrderPriority() when it joined,...
One trade the venue reports, with the side that crossed the spread.
utils::RingBuffer< MDTrade > trade_history_
SelfMatchPreventionMode smp_mode_
symbol_name_t symbol_
Stored at wire width so publishing can copy the whole field without reading past the end of a shorter...
engine::MatchingEngine * matching_engine_
std::vector< MDLevel > md_level_update_cache_
std::vector< MDOrder > md_order_update_cache_
void recordTrade(const MDTrade &trade)
Appends a trade to the tape history that serves the subscribe snapshot.
std::shared_ptr< OrderBook > order_book_
qty_t takeTradedQty(Side side, price_t price, time_t as_of)
Returns the quantity traded at (side, price) that a level update stamped as_of does not yet reflect,...
Order * findOrder(uint64_t order_id) const