Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
exchange.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
2#include "exchange.hpp"
5#include <utils/order.hpp>
6#include <utils/timestamp.hpp>
7#include <algorithm>
8#include <cassert>
9
10using namespace slick::sim::exch;
11using namespace slick::sim;
12using namespace slick::sim::utils;
13using namespace slick::sim::md_publisher;
14using namespace slick::sim::order_gateway;
15
16namespace
17{
18 auto &symbol_mgr = SymbolManager::instance();
19}
20
22 Venue venue,
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))
25{
26 if (!config.contains("order_gateway"))
27 {
28 throw std::runtime_error(std::format("Exchange {} Missing order_gateway config", to_string(venue)));
29 }
30 if (!config.contains("md_publisher"))
31 {
32 throw std::runtime_error(std::format("Exchange {} Missing md_publisher config", to_string(venue)));
33 }
34
35 if (config.contains("self_match_prevention"))
36 {
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")
40 {
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);
44 }
45 else
46 {
47 LOG_INFO("Exchange {} self-match prevention: {}", to_string(venue), to_string(smp_mode_));
48 }
49 }
50 matching_keys_unread_ = config.contains("matching_algorithm") || config.contains("pro_rata");
51}
52
54{
55 if (!enabled_)
56 {
57 LOG_WARN("Exchange {} is disabled, skipping start", to_string(venue_));
58 return;
59 }
60 // Here rather than in the constructor, which cannot know whether the venue's
61 // own constructor goes on to call configureMatching.
63 {
64 LOG_WARN("Exchange {} matches FIFO only; matching_algorithm and pro_rata are ignored", to_string(venue_));
66 }
67
68 run_.store(true, std::memory_order_release);
69
70 for (auto &og : order_gateways_)
71 {
72 og->start();
73 }
74
75 if (md_publisher_)
76 {
77 md_publisher_->start();
78 }
79
80 if (md_feed_)
81 {
82 md_feed_->start();
83 }
84 for (auto &feed : md_feeds_)
85 {
86 feed->start();
87 }
88
89 // start MD thread
90 // if (md_feed_)
91 // {
92 // md_thread_ = std::thread([this]() { processMdData(); });
93 // }
94
95 // The base owns the processing loop. Adapters override poll() to add work
96 // to each iteration.
97 thread_ = std::thread([this]()
98 {
99 while (run_.load(std::memory_order_relaxed)) {
100 poll();
102 } });
103}
104
105std::vector<slick::sim::cli::CliEndpoint *> Exchange::feedCliEndpoints() const
106{
107 std::vector<cli::CliEndpoint *> out;
108 forEachFeed([&out](md_feed::MDFeed &feed)
109 {
110 if (auto *endpoint = feed.cliEndpoint()) {
111 out.push_back(endpoint);
112 } });
113 return out;
114}
115
116std::vector<FeedInfo> Exchange::enabledFeeds() const
117{
118 std::vector<FeedInfo> out;
119 if (enabled_)
120 {
121 forEachFeed([this, &out](md_feed::MDFeed &feed)
122 { out.push_back(feedInfo(feed.feedKind(), feed.feedName())); });
123 }
124 return out;
125}
126
127FeedInfo Exchange::feedInfo(md_feed::FeedKind kind, std::string_view name) const
128{
129 const std::string venue = cli::venue_path(to_string(venue_));
130 return {venue_, kind,
131 name.empty() ? cli::instance_path(venue, instance_.empty() ? venue : instance_)
132 : cli::venue_path(venue, name)};
133}
134
136{
137 // main() and ~Exchange() both call stop(). Guard the whole operation because
138 // CoinbaseLiveWSFeed::stop() unsubscribes upstream and must not run twice.
139 if (!run_.exchange(false, std::memory_order_acq_rel))
140 {
141 return;
142 }
143
144 if (md_thread_.joinable())
145 {
146 md_thread_.join();
147 }
148
149 // Join before touching feeds: poll() reads md_feeds_ on the exchange thread,
150 // and CoinbaseExchange::handleMdUnsubscription erases entries there.
151 if (thread_.joinable())
152 {
153 thread_.join();
154 }
155
156 for (auto &feed : md_feeds_)
157 {
158 feed->stop();
159 }
160 if (md_feed_)
161 {
162 md_feed_->stop();
163 }
164
165 for (auto &og : order_gateways_)
166 {
167 og->stop();
168 }
169 if (md_publisher_)
170 {
171 md_publisher_->stop();
172 }
173}
174
176{
177 // Process a bounded burst per event-loop iteration. Processing one request per poll+read cycle
178 // made latency grow with queue depth even when the book could handle requests back to back. The
179 // limit leaves time for poll() to process venue market data and for the CLI to run.
180 constexpr int max_batch = 1024;
181 for (int processed = 0; processed < max_batch; ++processed)
182 {
183 auto [request, size] = request_queue_.read(order_request_cursor_);
184 if (!request)
185 {
186 return;
187 }
188 switch (request->msg_type)
189 {
191 {
192 handleNewOrderRequest(*request);
193 break;
194 }
196 {
197 handleModifyOrderRequest(*request);
198 break;
199 }
201 {
202 handleCancelOrderRequest(*request);
203 break;
204 }
206 {
207 handleMdSubscription(*request);
208 break;
209 }
211 {
212 handleMdUnsubscription(*request);
213 break;
214 }
215 default:
216 break;
217 }
218 }
219}
220
221int Exchange::clientIdFor(const char *user_id)
222{
223 auto len = strnlen(user_id, sizeof(AddOrderMessage::user_id));
224 if (len == 0)
225 {
226 // No identity to compare, so this order can never self-match.
227 return -1;
228 }
229
230 // Heterogeneous lookup first: this runs once per new order, and the same
231 // handful of users submit all of them, so the hit path must not build a key.
232 std::string_view key(user_id, len);
233 if (auto it = client_ids_.find(key); it != client_ids_.end())
234 {
235 return it->second;
236 }
237
238 // First order from this user - only now is a key worth materialising, and it
239 // is stored inline rather than on the heap.
240 return client_ids_.emplace(key, next_client_id_++).first->second;
241}
242
243void Exchange::configureMatching(const nlohmann::json &config)
244{
245 if (std::ranges::any_of(matching_engines_, [](const auto &slot) { return slot != nullptr; }))
246 {
247 throw std::logic_error(std::format("Exchange {}: configureMatching after a symbol was assigned an engine",
248 to_string(venue_)));
249 }
251 matching_keys_unread_ = false;
252}
253
255{
256 // SymbolManager hands back an existing (venue, name), so a second bind would
257 // move a live symbol onto this exchange's engine and SMP mode.
258 assert(symbol->matching_engine_ == nullptr && "symbol is already bound to an exchange's engine");
259 auto &slot = matching_engines_[matching_.type];
260 if (!slot)
261 {
263 }
264 symbol->matching_engine_ = slot.get();
265 symbol->smp_mode_ = smp_mode_;
266}
267
269{
270 if (const auto reason = newOrderAdmission(); reason != OrdRejectReason::NONE)
271 {
272 rejectNewOrderRequest(request, reason);
273 return;
274 }
275 auto *symbol = symbol_mgr.getSymbol(request.symbol, venue_);
276 if (!symbol)
277 {
279 }
280 else
281 {
282 auto &msg = request.add_order;
283 if (msg.client_order_id[0] != '\0')
284 {
285 auto *order = symbol->order_book_->findOrderByClientOrderId(msg.client_order_id);
286 if (order) [[unlikely]]
287 {
288 LOG_WARN(std::format("ClientOrderId {} already exist", msg.client_order_id));
290 return;
291 }
292 }
293 Order *order = symbol->order_book_->allocateOrder();
294 order->symbol = symbol->symbol_;
295 order->client_order_id = msg.client_order_id;
296 order->user_id = msg.user_id;
297 // Identity for self-match prevention. Scoped to the authenticated user,
298 // matching how real venues scope SMP - to the account, not the connection.
299 order->client_id = clientIdFor(msg.user_id);
300 order->side = msg.side;
301 order->type = msg.type;
302 order->time_in_force = msg.time_in_force;
303 order->price = msg.price;
304 order->resetFillAccounting(msg.qty);
305 order->type = msg.type;
307 order->request_tag = request.request_tag;
308
309 sendOrderNewPending(order, request.time_stamp);
310
311 auto [reject_reason, trade_summaries] = symbol->addOrder(order, request.time_stamp);
312
313 if (!trade_summaries.empty())
314 {
315 for (const auto &summary : trade_summaries)
316 {
317 publishTradeSummary(symbol, summary);
318 }
319 }
320
321 if (reject_reason != OrdRejectReason::NONE && reject_reason != OrdRejectReason::FOK_CANNOT_FILL)
322 {
323 rejectNewOrderRequest(request, reject_reason);
324 }
325
326 flushMarketDataCaches(symbol);
327 }
328}
329
331{
332 if (const auto reason = newOrderAdmission(); reason != OrdRejectReason::NONE)
333 {
334 rejectModifyOrderRequest(request, reason);
335 return;
336 }
337 auto *symbol = symbol_mgr.getSymbol(request.symbol, venue_);
338 if (!symbol)
339 {
341 }
342 else
343 {
344 Order *order;
345 if (request.modify_order.client_order_id[0] != '\0')
346 {
347 order = symbol->findOrderByClientOrderId(request.modify_order.client_order_id);
348 }
349 else
350 {
351 order = symbol->findOrderByOrderId(request.modify_order.order_id);
352 }
353
354 if (!order)
355 {
356 LOG_WARN(std::format("{} OrderId {} not found for modification", symbol->symbol_.view(), request.modify_order.order_id));
358 return;
359 }
362 // The amendment's tag goes on the order for the responses it produces, but a
363 // rejected amendment must not leave it there: the order's later passive fills
364 // answer the last request it actually accepted.
365 const uint64_t accepted_tag = order->request_tag;
366 order->request_tag = request.request_tag;
367 sendOrderReplacePending(order, request.time_stamp);
368 // modifyOrder can return the order to the pool once it is fully filled, so
369 // nothing below reads it unless the amendment was rejected - and a rejected
370 // amendment leaves the order resting.
371 auto [reject_reason, trade_summaries] = symbol->modifyOrder(order, request.modify_order.new_price, request.modify_order.new_qty, request.time_stamp);
372
373 if (!trade_summaries.empty())
374 {
375 for (const auto &summary : trade_summaries)
376 {
377 publishTradeSummary(symbol, summary);
378 }
379 }
380
381 if (reject_reason != OrdRejectReason::NONE)
382 {
383 order->request_tag = accepted_tag;
384 rejectModifyOrderRequest(request, reject_reason);
385 }
386
387 flushMarketDataCaches(symbol);
388 }
389}
390
392{
393 auto *symbol = symbol_mgr.getSymbol(request.symbol, venue_);
394 if (!symbol)
395 {
397 }
398 else
399 {
400 Order *order;
401 if (request.cancel_order.client_order_id[0] != '\0')
402 {
403 order = symbol->findOrderByClientOrderId(request.cancel_order.client_order_id);
404 }
405 else
406 {
407 order = symbol->findOrderByOrderId(request.cancel_order.order_id);
408 }
409
410 if (!order)
411 {
412 LOG_WARN(std::format("{} OrderId {} not found for cancellation", symbol->symbol_.view(), request.cancel_order.order_id));
414 return;
415 }
417 order->request_tag = request.request_tag;
418 sendOrderCancelPending(order, request.time_stamp);
419 symbol->cancelOrder(order, request.time_stamp);
420 // Removing the order shrank a book level, and that level update is sitting
421 // in the symbol's cache. Without this the delta is stranded until the next
422 // add or modify flushes it, so a cancelled level keeps its old quantity on
423 // every subscriber's book -- indefinitely when the cancel is the last
424 // request, which is exactly what withdrawing a quote looks like.
425 flushMarketDataCaches(symbol);
426 }
427}
428
430{
431 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDSubscriptionResponse));
432 auto index = md_queue_.reserve(sz);
433 auto *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
435 update->venue = venue_;
436 memcpy(update->symbol, request.symbol, sizeof(update->symbol));
437 auto *rsp = reinterpret_cast<MDSubscriptionResponse *>(update->data);
438 rsp->channel = request.md_subscription.channel;
439 // The reason was accepted and then dropped, leaving the field holding whatever
440 // the recycled queue slot did - so a reject could arrive claiming NONE, and the
441 // publisher would go on to read a book snapshot this frame never reserved.
442 rsp->reject_reason = reason;
443 md_queue_.publish(index, sz);
444}
445
446void Exchange::publishMdSubscriptionResponse(const symbol_name_t &symbol, uint8_t channel)
447{
448 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDSubscriptionResponse));
449 auto index = md_queue_.reserve(sz);
450 auto *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
452 update->venue = venue_;
453 std::memcpy(update->symbol, symbol.data(), sizeof(update->symbol));
454 auto *rsp = reinterpret_cast<MDSubscriptionResponse *>(update->data);
455 rsp->channel = channel;
456 rsp->reject_reason = MDSubscriptionRejectReason::NONE;
457 md_queue_.publish(index, sz);
458}
459
461{
462 auto index = response_queue_.reserve();
463 auto &response = *response_queue_[index];
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));
466 std::memcpy(response.client_order_id, request.add_order.client_order_id, sizeof(response.client_order_id));
467 std::memset(response.order_id, 0, sizeof(response.order_id));
468 // This reject has no free-text message. Clear the recycled slot so C-string readers cannot read
469 // past text left by the previous report.
470 response.error_message[0] = '\0';
471 response.order_num = 0;
472 response.request_tag = request.request_tag;
473 response.aggressor = false;
474 response.request_time = request.time_stamp;
475 response.response_type = MessageType::REJECT;
476 response.order_status = OrderStatus::REJECTED;
477 response.exec_type = ExecType::REJECTED;
478 response.price = request.add_order.price;
479 response.qty = request.add_order.qty;
480 response.cum_qty = 0;
481 response.leaves_qty = 0;
482 response.reject_reason = reason;
483 response.timestamp = utils::get_current_time_ns();
484 response_queue_.publish(index);
485}
486
488{
489 // Request is a union: reading add_order here would alias ModifyOrderMessage,
490 // putting the order id in the client_order_id field and taking price/qty from
491 // the wrong offsets entirely.
492 const auto &msg = request.modify_order;
493 auto index = response_queue_.reserve();
494 auto &response = *response_queue_[index];
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;
501 response.request_tag = request.request_tag;
502 response.aggressor = false;
503 response.response_type = MessageType::REJECT;
504 response.order_status = OrderStatus::REJECTED;
505 response.exec_type = ExecType::REJECTED;
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;
511 response.timestamp = utils::get_current_time_ns();
512 response.request_time = request.time_stamp;
513 response_queue_.publish(index);
514}
515
517{
518 auto index = response_queue_.reserve();
519 auto &response = *response_queue_[index];
520 std::memcpy(response.symbol, request.symbol, sizeof(response.symbol));
521 // Request is a union: add_order.client_order_id aliases CancelOrderMessage's
522 // order_id, and there is no price/qty on a cancel at all.
523 const auto &msg = request.cancel_order;
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;
529 response.request_tag = request.request_tag;
530 response.aggressor = false;
531 response.response_type = MessageType::REJECT;
532 response.order_status = OrderStatus::REJECTED;
533 response.exec_type = ExecType::REJECTED;
534 response.price = NULL_PRICE;
535 response.qty = 0;
536 response.cum_qty = 0;
537 response.leaves_qty = 0;
538 response.reject_reason = reason;
539 response.timestamp = utils::get_current_time_ns();
540 response.request_time = request.time_stamp;
541 response_queue_.publish(index);
542}
543
544void Exchange::publishMDBookUpdate([[maybe_unused]] symid_t sid, OrderBook &order_book, const std::array<uint8_t, 2> &indices)
545{
546 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDBookUpdate));
547 uint64_t index = md_queue_.reserve(sz);
548 MarketDataUpdate *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
549 update->type = MDUpdateType::BOOK;
550 update->venue = venue_;
551 std::memcpy(update->symbol, order_book.symbolName().data(), sizeof(update->symbol));
552 MDBookUpdate *book_update = reinterpret_cast<MDBookUpdate *>(update->data);
553 book_update->update_index[0] = indices[0];
554 book_update->update_index[1] = indices[1];
555 order_book.populateMDBookUpdate(*book_update);
556 md_queue_.publish(index, sz);
557}
558
560{
561 if (!symbol->md_level_update_cache_.empty())
562 {
564 symbol->md_level_update_cache_.clear();
565 }
566
567 if (!symbol->md_order_update_cache_.empty())
568 {
569 // Published last, so for a venue that publishes order updates the ORDER
570 // frame closes the event - see MDOrderUpdate.
572 {
574 }
575 symbol->md_order_update_cache_.clear();
576 }
577}
578
579void Exchange::publishLevelUpdate(const symbol_name_t &symbol, const std::vector<MDLevel> &level_updates)
580{
581 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDLevelUpdate) + level_updates.size() * sizeof(MDLevel));
582 auto index = md_queue_.reserve(sz);
583 auto *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
584 update->type = MDUpdateType::LEVEL;
585 update->venue = venue_;
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));
590 md_queue_.publish(index, sz);
591}
592
593void Exchange::publishMDOrderUpdate(const symbol_name_t &symbol, const std::vector<MDOrder> &order_updates)
594{
595 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDOrderUpdate) + order_updates.size() * sizeof(MDOrder));
596 auto index = md_queue_.reserve(sz);
597 auto *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
598 update->type = MDUpdateType::ORDER;
599 update->venue = venue_;
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));
604 md_queue_.publish(index, sz);
605}
606
607void Exchange::publishTradeSummary(Symbol *symbol, const TradeSummaryInfo &trade_summary)
608{
609 // The engine's own trade id comes from a single static counter shared by
610 // every engine and every venue, so it cannot serve as the public id. Each
611 // venue stamps its own sequence here, once, so a live print and the same
612 // trade replayed in a snapshot carry identical ids for every client.
613 auto trade_id = nextVenueTradeId();
614
615 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(TradeSummary) + trade_summary.num_orders * sizeof(Trade));
616 auto index = md_queue_.reserve(sz);
617 auto update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
619 update->venue = venue_;
620 std::memcpy(update->symbol, symbol->symbol_.data(), sizeof(update->symbol));
621 auto summary = reinterpret_cast<TradeSummary *>(update->data);
622 summary->timestamp = trade_summary.timestamp;
623 summary->trade_id = trade_id;
624 summary->security_id = symbol->id_;
625 summary->aggressor_side = trade_summary.aggressor_side;
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)
630 {
631 summary->trades[i].order_id = trade_summary.Trades[i].order_id;
632 summary->trades[i].qty = trade_summary.Trades[i].qty;
633 }
634 md_queue_.publish(index, sz);
635
636 symbol->recordTrade(MDTrade{
637 .trade_id = trade_id,
638 .event_time = static_cast<uint64_t>(trade_summary.timestamp),
639 .seq_num = 0,
640 .price = trade_summary.price,
641 .qty = trade_summary.qty,
642 .flags = UpdateFlags::F_NONE,
643 .side = trade_summary.aggressor_side});
644}
645
647{
648 auto &history = symbol->trade_history_;
649 auto num_trades = static_cast<uint32_t>(history.size());
650
651 auto sz = static_cast<uint32_t>(sizeof(MarketDataUpdate) + sizeof(MDSubscriptionResponse) + sizeof(MDTradeSnapshotResponse) + num_trades * sizeof(MDTrade));
652 auto index = md_queue_.reserve(sz);
653 auto *update = reinterpret_cast<MarketDataUpdate *>(md_queue_[index]);
654 std::memcpy(update->symbol, symbol->symbol_.data(), sizeof(update->symbol));
655 update->venue = venue_;
656 update->type = MDUpdateType::SUB_RESPONSE;
657
658 auto *response = reinterpret_cast<MDSubscriptionResponse *>(update->data);
659 response->channel = channel;
660 response->reject_reason = MDSubscriptionRejectReason::NONE;
661
662 // A trade the book absorbed is settled history for this subscriber whatever
663 // its timestamp, because the L2 snapshot they receive is generated from that
664 // same book. Only a print the simulator never applied depends on timing, and
665 // then on whether the book's own data reaches it: `lastUpdateTime()` tracks
666 // level updates only, so it cannot stand in for trade application here.
667 auto book_time = symbol->order_book_ ? symbol->order_book_->lastUpdateTime() : 0;
668
669 auto reflected_in_book = [book_time](const MDTrade &trade) {
670 return !(trade.flags & UpdateFlags::F_NOT_IN_BOOK) || trade.event_time <= book_time;
671 };
672
673 auto *snapshot = reinterpret_cast<MDTradeSnapshotResponse *>(response->data);
674 auto *trades = snapshot->trades;
675 uint32_t num_snapshot = 0;
676 uint32_t num_update = 0;
677
678 // The consumer reads the two blocks as contiguous ranges, so they must be
679 // written that way — hence two passes rather than one. Classification is not
680 // monotonic over the history: an applied trade can follow an unapplied print
681 // that is newer than book_time, so a single pass in history order would
682 // interleave the blocks and silently swap their contents. Each pass walks the
683 // history in order, so both blocks stay chronological within themselves.
684 for (uint32_t i = 0; i < num_trades; ++i)
685 {
686 const auto *trade = history[i];
687 if (trade == nullptr) [[unlikely]]
688 {
689 continue;
690 }
691 if (reflected_in_book(*trade))
692 {
693 *trades++ = *trade;
694 ++num_snapshot;
695 }
696 }
697 for (uint32_t i = 0; i < num_trades; ++i)
698 {
699 const auto *trade = history[i];
700 if (trade == nullptr) [[unlikely]]
701 {
702 continue;
703 }
704 if (!reflected_in_book(*trade))
705 {
706 *trades++ = *trade;
707 ++num_update;
708 }
709 }
710 snapshot->num_snapshot = num_snapshot;
711 snapshot->num_update = num_update;
712 md_queue_.publish(index, sz);
713}
714
715void Exchange::reconcilePhantomQty(Symbol *symbol, Side side, price_t price, qty_t target_qty,
716 time_t event_time, uint64_t seq_num, bool end_event)
717{
718 auto &book = *symbol->order_book_;
719 auto [level, index] = book.getLevel(to_book_side(side), price);
720 if (!level)
721 {
722 return;
723 }
724
725 // A trade print and the venue's level update for it describe the same event.
726 // The usual case needs no help: the update carries the post-trade quantity
727 // and the book has already absorbed the trade, so the two agree and nothing
728 // moves. The exception is a trade this update is too old to have seen - the
729 // update still reports the pre-trade quantity there, and taking it at face
730 // value would add that quantity back only for the next update to remove it
731 // again. Offset by exactly the trades it has not accounted for. Timestamps
732 // that tie count as reflecting the trade: a venue emits the print and its
733 // level update together, and the sequencer applies the trade first.
734 auto unreflected = symbol->takeTradedQty(side, price, event_time);
735 if (unreflected > 0)
736 {
737 target_qty = target_qty > unreflected ? target_qty - unreflected : 0;
738 }
739
740 auto md_level_qty = book.getMDLevelQty(price);
741 if (target_qty > md_level_qty)
742 {
743 // Level qty increased, assume new orders added at the back. Create new phantom order to represent then increment
744 auto size = target_qty - md_level_qty;
745 // end_event has to reach the book, exactly as the decrease branch below
746 // passes it: it becomes ChangeFlag::LastInBatch, which Symbol::onPriceLevelUpdate
747 // republishes as F_END_EVENT. Defaulting it to true closed the batch early
748 // for every increase that was not the last update in its batch.
749 book.addBookOrder(utils::nextOrderId(), to_book_side(side), price, size, event_time, seq_num, end_event);
750 }
751 else if (target_qty < md_level_qty)
752 {
753 // Level qty decreased. Always assume the worst case, that the quantity decreased at the back.
754 //
755 // Choose every reduction before applying any of them. `modifyOrder(..., 0)`
756 // delegates to deleteOrder, which unlinks the order from the intrusive list
757 // `level->orders` exposes - so advancing the iterator past the order just
758 // removed is undefined, and in practice the walk ended there. Everything
759 // ahead of it was stranded: a level the venue had retired outright kept
760 // whatever its earlier phantom orders held, and no later update could clear
761 // it, because reconcile measured a level quantity that by then agreed with
762 // the venue's. That is a stale level resting at a price the market has left.
763 auto diff = md_level_qty - target_qty;
764 phantom_reductions_.clear();
765 for (auto it = level->orders.rbegin(); it != level->orders.rend() && diff > 0; ++it)
766 {
767 auto &order = *it;
768 if (symbol->findOrder(order.order_id))
769 {
770 // Belongs to the simulator's own user - never touch it.
771 continue;
772 }
773
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});
779 diff -= to_reduce;
780 }
781
782 for (std::size_t i = 0; i < phantom_reductions_.size(); ++i)
783 {
784 const auto &reduction = phantom_reductions_[i];
785 book.modifyOrder(reduction.order_id, price, reduction.new_qty, event_time,
786 reduction.priority, seq_num,
787 end_event && (i + 1 == phantom_reductions_.size()));
788 }
789 }
790}
791
793{
794 auto &book = *symbol->order_book_;
795 const auto timestamp = event.transact_time;
796
797 switch (event.action)
798 {
800 restMarketOrder(symbol, event);
801 break;
803 // Already gone if a client order or a replayed trade took all of it.
804 book.deleteOrder(event.book_order_id, timestamp);
805 break;
807 {
808 // OrderBook::findOrder answers for the simulator's own orders only.
809 const auto *resting = book.OrderBookL3::findOrder(event.book_order_id);
810 if (resting && !event.requeue)
811 {
812 // The venue's quantity wins: liquidity a client took from this order,
813 // and the market did not, comes back in place. Equal quantities are a
814 // no-op that publishes nothing.
815 book.modifyOrder(event.book_order_id, event.price, event.qty, timestamp, resting->priority);
816 }
817 else
818 {
819 // Requeued, or taken entirely by a client order while the venue still
820 // reports it. Either way it rests under the event's book priority. A
821 // requeue carries a new one and joins the back. A taken order carries
822 // the one it had and goes back where it was.
823 if (resting)
824 {
825 book.deleteOrder(event.book_order_id, timestamp);
826 }
827 restMarketOrder(symbol, event);
828 }
829 break;
830 }
831 }
832 markMarketChanged(symbol);
833}
834
836{
837 auto &book = *symbol->order_book_;
838 // OrderBookL3 reads a priority of 0 as "use the timestamp", which would sort this
839 // order against the clients' sequence-numbered priorities instead of beside them,
840 // and a null price would rest the phantom at the top of the book for good.
841 assert(event.book_priority != 0);
842 assert(event.price != NULL_PRICE);
843 qty_t qty = event.qty;
844 for (const auto &trade : symbol->matching_engine_->match(event.side, event.book_order_id, event.price, qty, book,
845 event.transact_time))
846 {
847 publishTradeSummary(symbol, trade);
848 }
849 if (qty > 0)
850 {
851 // The level sorts by book priority, so a restored order lands back in
852 // place only under its own. addBookOrder would draw a fresh one.
853 // A false here means the id was already resting: the venue repeated an order
854 // it never removed, and the mirror would silently drop this quantity.
855 [[maybe_unused]] const bool added = book.OrderBookL3::addOrder(
856 event.book_order_id, to_book_side(event.side), event.price, qty, event.transact_time, event.book_priority);
857 assert(added);
858 }
859}
860
862{
863 // The aggressor is not an order: its id only names the first leg of the trade
864 // summary, exactly as the level feeds' replay does, so it is drawn from the same
865 // sequence and can never collide with a resting order.
866 qty_t qty = event.qty;
867 for (const auto &trade : symbol->matching_engine_->match(event.aggressor, utils::nextOrderId(), event.price, qty,
868 *symbol->order_book_, event.transact_time))
869 {
870 publishTradeSummary(symbol, trade);
871 }
872 markMarketChanged(symbol);
873}
874
876{
877 for (auto *symbol : market_changed_symbols_)
878 {
879 flushMarketDataCaches(symbol);
880 }
882}
883
885{
886 // A scan rather than a hash: the list holds only the symbols one event touched
887 // before the venue flushed (CME and ICE flush at the end of every packet), which is
888 // a handful. A venue that flushed far less often would want a per-symbol flag.
889 if (std::find(market_changed_symbols_.begin(), market_changed_symbols_.end(), symbol) ==
891 {
892 market_changed_symbols_.push_back(symbol);
893 }
894}
895
896void Exchange::sendOrderNewPending(const Order *order, time_t request_time)
897{
898 auto index = response_queue_.reserve();
899 auto &response = *response_queue_[index];
900 setOrderIdentity(response, *order);
901 response.response_type = MessageType::EXECUTION_REPORT;
902 response.exec_type = ExecType::NEW;
903 response.order_status = OrderStatus::PENDING_NEW;
904 response.order_type = order->type;
905 response.price = order->price;
906 response.avg_fill_price = order->avg_fill_price;
907 response.qty = order->quantity;
908 response.cum_qty = 0;
909 response.leaves_qty = order->leaves_quantity;
910 assert(response.leaves_qty == response.qty);
911 response.timestamp = order->created_time;
912 response.request_time = request_time;
913 response.side = order->side;
914 response.post_only = order->post_only;
915 response_queue_.publish(index);
916}
917
918void Exchange::sendOrderReplacePending(const Order *order, time_t request_time)
919{
920 auto index = response_queue_.reserve();
921 auto &response = *response_queue_[index];
922 setOrderIdentity(response, *order);
923 response.response_type = MessageType::EXECUTION_REPORT;
924 response.exec_type = ExecType::PENDING_REPLACE;
925 response.order_status = OrderStatus::PENDING_REPLACE;
926 response.order_type = order->type;
927 response.request_time = request_time;
928 response.price = order->price;
929 response.avg_fill_price = order->avg_fill_price;
930 response.qty = order->quantity;
931 response.cum_qty = 0;
932 response.leaves_qty = order->leaves_quantity;
933 response.timestamp = order->created_time;
934 response.side = order->side;
935 response.post_only = order->post_only;
936 response_queue_.publish(index);
937}
938
939void Exchange::sendOrderCancelPending(const Order *order, time_t request_time)
940{
941 auto index = response_queue_.reserve();
942 auto &response = *response_queue_[index];
943 setOrderIdentity(response, *order);
944 response.response_type = MessageType::EXECUTION_REPORT;
945 response.exec_type = ExecType::PENDING_CANCEL;
946 response.order_status = OrderStatus::PENDING_CANCEL;
947 response.order_type = order->type;
948 response.request_time = request_time;
949 response.price = order->price;
950 response.avg_fill_price = order->avg_fill_price;
951 response.last_fill_price = order->last_fill_price;
952 response.last_qty = order->last_fill_qty;
953 response.qty = order->quantity;
954 response.cum_qty = order->cum_quantity;
955 response.leaves_qty = order->leaves_quantity;
956 // After a partial fill, leaves_qty is less than the original quantity. The old qty == leaves
957 // assert aborted the exchange thread and process when the client cancelled the remainder.
958 response.timestamp = order->created_time;
959 response.side = order->side;
960 response.post_only = order->post_only;
961 response_queue_.publish(index);
962}
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_
Definition exchange.hpp:181
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.
Definition exchange.cpp:127
void publishMDOrderUpdate(const symbol_name_t &symbol, const std::vector< MDOrder > &order_updates)
Definition exchange.cpp:593
virtual void handleMdUnsubscription(const Request &)
Definition exchange.hpp:164
std::shared_ptr< md_feed::MDFeed > md_feed_
Definition exchange.hpp:184
void handleNewOrderRequest(const Request &request)
Definition exchange.cpp:268
void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel)
Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history,...
Definition exchange.cpp:646
uint64_t nextVenueTradeId() noexcept
Public trade ids, one independent sequence per venue.
Definition exchange.hpp:142
void applyMarketOrder(Symbol *symbol, const MarketOrderEvent &event)
Rests, changes or removes a market order as a phantom order.
Definition exchange.cpp:792
void flushMarketDataCaches(Symbol *symbol)
Publish and clear whatever market data the book produced while handling a request.
Definition exchange.cpp:559
void configureMatching(const nlohmann::json &config)
Reads matching_algorithm and pro_rata from the venue's config.
Definition exchange.cpp:243
SelfMatchPreventionMode smp_mode_
Self-match prevention mode applied to every symbol on this venue, from the self_match_prevention conf...
Definition exchange.hpp:243
virtual void poll()
One iteration of the exchange thread's loop, called continuously between start() and stop().
Definition exchange.hpp:174
void publishMDBookUpdate(symid_t sid, OrderBook &order_book, const std::array< uint8_t, 2 > &indices)
Definition exchange.cpp:544
uint_fast64_t order_request_cursor_
Definition exchange.hpp:193
bool publish_order_updates_
Whether flushMarketDataCaches publishes the per-order (MDUpdateType::ORDER) frames the book produces.
Definition exchange.hpp:218
queue< uint8_t > md_queue_
Definition exchange.hpp:183
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
Definition exchange.hpp:195
void forEachFeed(Fn &&fn) const
Calls fn(MDFeed &) on md_feed_ and each of md_feeds_.
Definition exchange.hpp:200
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...
Definition exchange.cpp:861
std::string instance_
The config's name, one per instance of a venue that has several. Empty without one.
Definition exchange.hpp:180
void markMarketChanged(Symbol *symbol)
Definition exchange.cpp:884
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,...
Definition exchange.cpp:715
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
Feeds owned by the exchange and managed by base start()/stop().
Definition exchange.hpp:189
void rejectModifyOrderRequest(const Request &request, OrdRejectReason reason)
Definition exchange.cpp:487
Exchange(Venue venue, const nlohmann::json &config)
Definition exchange.cpp:21
void restMarketOrder(Symbol *symbol, const MarketOrderEvent &event)
Definition exchange.cpp:835
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
Definition exchange.hpp:196
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...
Definition exchange.cpp:607
engine::MatchingConfig matching_
The engine assignMatching hands out. FIFO unless configureMatching says otherwise.
Definition exchange.hpp:245
void publishLevelUpdate(const symbol_name_t &symbol, const std::vector< MDLevel > &level_updates)
Definition exchange.cpp:579
void rejectMdSubscription(const Request &request, MDSubscriptionRejectReason reason)
Definition exchange.cpp:429
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.
Definition exchange.hpp:253
virtual OrdRejectReason newOrderAdmission() const noexcept
Definition exchange.hpp:74
virtual std::vector< FeedInfo > enabledFeeds() const
The market-data feeds the config enables: those in md_feed_ and md_feeds_.
Definition exchange.cpp:116
void handleCancelOrderRequest(const Request &request)
Definition exchange.cpp:391
int clientIdFor(const char *user_id)
Resolves an order's user_id to the integer identity self-match prevention compares.
Definition exchange.cpp:221
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
Definition exchange.cpp:254
void sendOrderReplacePending(const Order *order, time_t request_time)
Definition exchange.cpp:918
void flushMarketEvents()
Publishes every symbol a market event changed since the last call.
Definition exchange.cpp:875
bool matching_keys_unread_
The config sets matching keys and configureMatching has not read them, so start() warns that this ven...
Definition exchange.hpp:248
std::array< std::unique_ptr< engine::MatchingEngine >, engine::MatchingEngine::Type::__count__ > matching_engines_
Definition exchange.hpp:194
void handleModifyOrderRequest(const Request &request)
Definition exchange.cpp:330
void sendOrderCancelPending(const Order *order, time_t request_time)
Definition exchange.cpp:939
void sendOrderNewPending(const Order *order, time_t request_time)
Definition exchange.cpp:896
std::vector< Symbol * > market_changed_symbols_
Symbols a market event has changed and not yet published.
Definition exchange.hpp:237
virtual void handleMdSubscription(const Request &)
Definition exchange.hpp:163
void rejectCancelOrderRequest(const Request &request, OrdRejectReason reason)
Definition exchange.cpp:516
queue< OrderResponse > response_queue_
Definition exchange.hpp:182
void publishMdSubscriptionResponse(const symbol_name_t &symbol, uint8_t channel)
Publishes an accepted subscription response without a snapshot payload.
Definition exchange.cpp:446
std::atomic_bool run_
Definition exchange.hpp:192
std::vector< cli::CliEndpoint * > feedCliEndpoints() const
The CLI endpoints of md_feed_ and md_feeds_ (a pcap feed's pcap/<venue>/<feed>).
Definition exchange.cpp:105
void rejectNewOrderRequest(const Request &request, OrdRejectReason reason)
Definition exchange.cpp:460
std::vector< PhantomReduction > phantom_reductions_
Definition exchange.hpp:230
virtual std::string feedName() const
Its name, different from the venue's other feeds'. Empty for a feed without one.
Definition md_feed.hpp:34
virtual FeedKind feedKind() const noexcept
Definition md_feed.hpp:31
virtual cli::CliEndpoint * cliEndpoint() noexcept
Where the CLI reaches the feed's own commands, named by the feed.
Definition md_feed.hpp:38
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,...
Definition exchange.hpp:30
FeedKind
Where a feed's market data comes from.
Definition md_feed.hpp:13
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
Definition decimal.hpp:9
uint64_t nextOrderId() noexcept
Definition order.hpp:10
uint64_t get_current_time_ns()
Definition timestamp.hpp:93
constexpr price_t NULL_PRICE
Definition types.hpp:28
uint_fast64_t time_t
Definition types.hpp:23
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...
Definition messages.hpp:368
uint16_t symid_t
Definition types.hpp:24
@ 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.
int_fast64_t qty_t
Definition types.hpp:22
int_fast64_t price_t
Definition types.hpp:21
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
Definition order.hpp:289
utils::fixed_string< 37 > client_order_id
Definition order.hpp:291
utils::fixed_string< 37 > user_id
Definition order.hpp:290
price_t avg_fill_price
Definition order.hpp:317
OrderType type
Definition order.hpp:306
qty_t last_fill_qty
Definition order.hpp:321
uint64_t created_time
Definition order.hpp:327
TimeInForce time_in_force
Definition order.hpp:308
uint64_t last_update_time
Definition order.hpp:328
OrderStatus status
Definition order.hpp:307
qty_t leaves_quantity
Definition order.hpp:316
uint64_t request_tag
Request::request_tag of the last request this order accepted, echoed on its responses.
Definition order.hpp:304
void resetFillAccounting(qty_t new_qty=0) noexcept
Definition order.hpp:338
price_t last_fill_price
Definition order.hpp:320
AddOrderMessage add_order
Definition messages.hpp:282
uint64_t request_tag
Opaque correlation token, carried onto the order and echoed on every OrderResponse that order produce...
Definition messages.hpp:280
CancelOrderMessage cancel_order
Definition messages.hpp:284
ModifyOrderMessage modify_order
Definition messages.hpp:283
MDSubscriptionMessage md_subscription
Definition messages.hpp:285
std::vector< Trade > Trades
Definition messages.hpp:393
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.
Definition exchange.hpp:225
One enabled market-data feed, as Exchange::enabledFeeds() reports it.
Definition feed_info.hpp:13
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_
Definition symbol.hpp:54
SelfMatchPreventionMode smp_mode_
Definition symbol.hpp:50
symbol_name_t symbol_
Stored at wire width so publishing can copy the whole field without reading past the end of a shorter...
Definition symbol.hpp:46
engine::MatchingEngine * matching_engine_
Definition symbol.hpp:47
std::vector< MDLevel > md_level_update_cache_
Definition symbol.hpp:51
std::vector< MDOrder > md_order_update_cache_
Definition symbol.hpp:52
void recordTrade(const MDTrade &trade)
Appends a trade to the tape history that serves the subscribe snapshot.
Definition symbol.hpp:169
std::shared_ptr< OrderBook > order_book_
Definition symbol.hpp:48
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,...
Definition symbol.hpp:140
Order * findOrder(uint64_t order_id) const
Definition symbol.hpp:198