Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
match_common.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "matching_engine.hpp"
4#include <slick/logger.hpp>
5#include <common/order.hpp>
6#include <utils/order.hpp>
7#include <utils/price.hpp>
8#include <algorithm>
9#include <cassert>
10#include <optional>
11#include <vector>
12
13// Building blocks both engines share. They differ only in which resting orders an
14// aggressor trades with at a price level; the preamble before matching, a single
15// fill, and the trade summaries a match produces are the same.
17
21enum class Reach : uint8_t { Queue, Level };
22
23// Check if incoming order would self-match with book order
24// Returns true if orders are from same client
25inline bool isSelfMatch(const Order* incoming_order, const Order* book_order) {
26 if (book_order == nullptr) {
27 return false; // Book order not found, assume different client
28 }
29
30 // SMP only applies when both orders have valid client_ids
31 if (incoming_order->client_id == -1 || book_order->client_id == -1) {
32 return false;
33 }
34
35 return incoming_order->client_id == book_order->client_id;
36}
37
38// Handle self-match according to Symbol's configured SMP mode
39// Returns true if matching should continue, false if order should be rejected
40inline bool handleSelfMatch(MatchingEngine& engine, const Order* incoming_order, Order* book_order,
41 OrderBook& book, slick::sim::time_t request_time,
42 uint64_t event_time, uint64_t seq_num,
43 SelfMatchPreventionMode smp_mode) {
44 switch (smp_mode) {
46 // Allow self-matching
47 return true;
48
50 // Cancel the resting book order and continue matching. This is a real
51 // cancel, so it takes the same three steps as Symbol::cancelOrder:
52 // remove it from the book, tell its owner, and return it to the pool.
53 // Deleting it from the book alone would leave the client believing the
54 // order was still live and leak the pooled Order.
55 LOG_INFO("{} SMP: Canceling resting order {} (client_id={})",
56 incoming_order->symbol.view(), book_order->order_id.view(), incoming_order->client_id);
57 book.deleteOrder(book_order, event_time, seq_num, false);
58 engine.publishOrderCancel(book_order, request_time);
59 book.freeOrder(book_order);
60 return true; // Continue to next order
61
63 // Reject the incoming order. Reached only as a backstop — the
64 // pre-check in prepareOrder() decides this before anything is mutated.
65 LOG_INFO("{} SMP: Rejecting new order {} due to self-match with resting order {} (client_id={})",
66 incoming_order->symbol.view(), incoming_order->id, book_order->order_id.view(), incoming_order->client_id);
67 return false; // Signal to reject order
68
69 default:
70 return true;
71 }
72}
73
74// Pre-check for CANCEL_NEWEST: would this order reach a resting order of its own?
75//
76// This has to be answered before the order is touched. An amendment mutates
77// price/quantity and reports REPLACED on its way into the matching loop, and a
78// new order is acked there, so discovering the self-match mid-loop would mean
79// telling the client the order was replaced or live and then rejecting it.
80// Only orders the incoming quantity could actually reach are considered.
81template<Side SIDE, Reach REACH>
82bool wouldSelfMatch(const Order* order, price_t order_price, qty_t order_qty, OrderBook& book) {
83 qty_t remaining = order_qty;
84
85 const auto& levels = book.getLevelsL3(static_cast<slick::orderbook::Side>(SIDE));
86 for (const auto& [level_price, level_data] : levels) {
87 if (remaining <= 0) [[unlikely]] {
88 return false;
89 }
90 if (order_price != NULL_PRICE && !utils::isPriceBetterOrEqual<SIDE>(level_price, order_price)) [[unlikely]] {
91 break; // Reached price levels we can't match against
92 }
93
94 for (const auto& book_order : level_data.orders) {
95 if constexpr (REACH == Reach::Queue) {
96 if (remaining <= 0) [[unlikely]] {
97 return false;
98 }
99 }
100 if (isSelfMatch(order, book.findOrder(book_order.order_id))) [[unlikely]] {
101 return true;
102 }
103 if constexpr (REACH == Reach::Queue) {
104 remaining -= std::min<qty_t>(book_order.quantity, remaining);
105 }
106 }
107
108 if constexpr (REACH == Reach::Level) {
109 remaining -= std::min<qty_t>(level_data.total_quantity, remaining);
110 }
111 }
112 return false;
113}
114
115// Pre-check for Fill-Or-Kill: Determine if entire order can be filled
116// Returns true if sufficient liquidity exists (considering SMP). Total crossing
117// liquidity is the same whichever way it is allocated, so this serves both engines.
118template<Side SIDE>
119bool canFillCompletely(const Order* order, price_t order_price, qty_t order_qty, OrderBook& book,
120 SelfMatchPreventionMode smp_mode) {
121 qty_t remaining_check_qty = order_qty;
122
123 // Self-match handling is the only reason to resolve a book order to its full
124 // Order, and that is a hash lookup per resting order. With SMP off nothing
125 // downstream needs it, so the whole scan stays inside the level's own array.
126 const bool check_self_match = smp_mode != SelfMatchPreventionMode::NONE;
127
128 // Get all levels on the opposite side of the book
129 const auto& levels = book.getLevelsL3(static_cast<slick::orderbook::Side>(SIDE));
130
131 // Iterate through price levels in order (best to worst)
132 for (const auto& [level_price, level_data] : levels) {
133 // Check price compatibility - stop if price is worse than our limit
134 if (order_price != NULL_PRICE && !utils::isPriceBetterOrEqual<SIDE>(level_price, order_price)) [[unlikely]] {
135 break; // Reached price levels we can't match against
136 }
137
138 // Check each order in this level
139 for (const auto& book_order : level_data.orders) {
140 // Handle self-matches based on SMP mode (exceptional case)
141 if (check_self_match && isSelfMatch(order, book.findOrder(book_order.order_id))) [[unlikely]] {
142 if (smp_mode == SelfMatchPreventionMode::CANCEL_NEWEST) [[unlikely]] {
143 // CANCEL_NEWEST: Order would be rejected on first self-match
144 return false;
145 }
146 // CANCEL_RESTING: This resting order would be canceled, so skip it.
147 // NONE never gets here - the quantity stays countable because the
148 // order really would trade against itself.
149 LOG_INFO("{} FOK check: Skipping self-match with resting order {} due to SMP (CANCEL_RESTING mode)",
150 order->symbol.view(), book_order.order_id);
151 continue;
152 }
153
154 // Count available quantity (normal path)
155 remaining_check_qty -= std::min<qty_t>(book_order.quantity, remaining_check_qty);
156
157 if (remaining_check_qty == 0) [[likely]] {
158 return true; // Found enough liquidity
159 }
160 }
161 }
162
163 // Every path that finds enough liquidity has already returned, so reaching
164 // here means the book ran out - except for a zero-quantity order, which is
165 // trivially fillable.
166 return remaining_check_qty == 0;
167}
168
173template<Side SIDE, Reach REACH>
174std::optional<OrdRejectReason> prepareOrder(MatchingEngine& engine, Order* order, price_t order_price, qty_t order_qty,
175 OrderBook& book, slick::sim::time_t request_time, SelfMatchPreventionMode smp_mode) {
176 // STEP 0: CANCEL_NEWEST is decided before the order is acked, mutated or
177 // reported on, so a rejected order leaves no trace: no NEW, no REPLACED, no
178 // partial fills, and the stored Order keeps its original price and quantity.
179 // The caller publishes the single terminal REJECTED.
181 // Scan only as deep as this order will really trade. `order_qty` is the
182 // order's *total* quantity, which for a partially filled amendment is
183 // more than its remaining leaves — scanning that far could reach one of
184 // the owner's resting orders the amendment would never touch and reject
185 // a perfectly good fill. Mirror the leaves the matching loop is about to
186 // compute below, without mutating anything yet.
187 qty_t effective_qty = order->leaves_quantity;
188 if (order->status == OrderStatus::PENDING_REPLACE) {
189 effective_qty += order_qty - order->quantity;
190 if (effective_qty < 0) {
191 effective_qty = 0;
192 }
193 }
194
195 if (effective_qty > 0 && wouldSelfMatch<SIDE, REACH>(order, order_price, effective_qty, book)) {
196 LOG_INFO("{} Order {} rejected due to SMP (CANCEL_NEWEST mode)", order->symbol.view(), order->id);
198 }
199 }
200
201 if (order->status == OrderStatus::PENDING_NEW) {
202 engine.publishOrderAck(order, request_time);
203 }
204
205 // STEP 1: Fill-Or-Kill pre-validation
206 if (order->time_in_force == TimeInForce::FILL_OR_KILL) [[unlikely]] {
207 if (!canFillCompletely<SIDE>(order, order_price, order_qty, book, smp_mode)) [[unlikely]] {
208 engine.publishOrderCancel(order, request_time); // Can't fill the order fully, immediate cancel
209 LOG_INFO("{} FOK order {} cannot be completely filled, canceling", order->symbol.view(), order->id);
211 }
212 }
213
214 // STEP 2: apply a pending replace
215 if (order->status == OrderStatus::PENDING_REPLACE) [[unlikely]] {
216 order->quantity = order_qty;
217 order->price = order_price;
218 if (order->cum_quantity >= order_qty) [[unlikely]] {
219 order->leaves_quantity = 0;
220 } else {
221 order->leaves_quantity = order_qty - order->cum_quantity;
222 }
223 engine.publishOrderModify(order, order_price, order_qty, request_time);
224 }
225
226 if (order->leaves_quantity == 0) [[unlikely]] {
227 LOG_INFO("{} Order {} has zero leaves quantity after modification, canceling", order->symbol.view(), order->id);
228 engine.publishOrderCancel(order, request_time);
230 }
231 return std::nullopt;
232}
233
247
252template<Side SIDE>
253void recordTrade(MatchContext& ctx, uint64_t aggressor_id, uint64_t book_order_id, price_t price,
254 qty_t trade_qty, qty_t phantom_qty) {
255 if (ctx.last_fill_price != price) [[unlikely]] {
256 TradeSummaryInfo summary;
257 summary.timestamp = ctx.event_time;
259 summary.aggressor_side = opposite_side<SIDE>(); // SIDE is the resting side, so aggressor is the opposite
260 summary.price = price;
261 summary.qty = trade_qty;
262 summary.phantom_qty = phantom_qty;
263 summary.num_orders = 2;
264 if (ctx.legs_hint > summary.Trades.capacity()) {
265 summary.Trades.reserve(ctx.legs_hint);
266 }
267 summary.Trades.emplace_back(Trade{aggressor_id, trade_qty});
268 summary.Trades.emplace_back(Trade{book_order_id, trade_qty});
269
270 ctx.summaries.emplace_back(std::move(summary));
271 ctx.last_fill_price = price;
272 } else {
273 auto &last_summary = ctx.summaries.back();
274 last_summary.num_orders += 1;
275 last_summary.qty += trade_qty;
276 last_summary.phantom_qty += phantom_qty;
277 last_summary.Trades.front().qty += trade_qty; // Update aggressor trade qty
278 last_summary.Trades.emplace_back(Trade{book_order_id, trade_qty});
279 }
280}
281
287template<Side SIDE>
288bool fillResting(MatchContext& ctx, Order* order, uint64_t book_order_id, Order* full_book_order,
289 price_t price, qty_t trade_qty, qty_t remaining) {
290 LOG_INFO("{} Matching order {} with book order {} for qty {} at price {}", order->symbol.view(), order->id, book_order_id, trade_qty, price);
291 utils::executeOrder(order, price, trade_qty, ctx.event_time);
292 ctx.engine.publishOrderExecution(order, true);
293
294 if (!ctx.book.executeOrder(book_order_id, trade_qty, ctx.event_time, ctx.seq_num, remaining == 0)) [[unlikely]] {
295 // Same hazard as the market-data replay path: a declined execution leaves
296 // the resting order intact, so looping would re-match it. The aggressor has
297 // already been filled and reported by this point, so there is no unwinding
298 // it here - stop and leave the discrepancy loud rather than compounding it.
299 LOG_ERROR("{} book rejected execution of order {} for qty {} at price {} (seq_num={}); abandoning match",
300 order->symbol.view(), book_order_id, trade_qty, price, ctx.seq_num);
301 return false;
302 }
303
304 // A trade has two sides, and when the resting side is one of the
305 // simulator's own orders it belongs to a client who has to hear about it.
306 // book.executeOrder() above booked the fill onto it, but OrderBook holds no
307 // reference to the engine so it cannot publish, and on a complete fill it
308 // only drops the order from the lookup maps - leaving the pooled Order
309 // unreturned. Both are done here, exactly as the market-data replay path
310 // does them.
311 if (full_book_order) [[unlikely]] {
312 ctx.engine.publishOrderExecution(full_book_order, false);
313 if (full_book_order->leaves_quantity == 0) {
314 // Erases whatever the maps still hold and returns it to the pool.
315 ctx.book.deleteOrder(full_book_order);
316 }
317 }
318
319 // A resting order the simulator does not own is phantom liquidity mirroring
320 // the real market. Tracked separately so the exchange can tell how much of
321 // this trade the venue's own level update will also account for.
322 recordTrade<SIDE>(ctx, order->id, book_order_id, price, trade_qty, full_book_order ? qty_t{0} : trade_qty);
323 return true;
324}
325
330template<Side SIDE>
331bool fillRestingFromFeed(MatchContext& ctx, uint64_t aggressor_id, uint64_t book_order_id, price_t price,
332 qty_t trade_qty, qty_t& qty) {
333 LOG_TRACE(" {} Matching {} with book order {} for qty {} at price {}", ctx.book.symbolName().view(),
334 aggressor_id, book_order_id, trade_qty, price);
335
336 auto* our_order = ctx.book.findOrder(book_order_id);
337
338 // Decrement before booking the fill so qty == 0 marks the final fill.
339 // Checking first would always be false while the caller's loop runs, leaving
340 // F_END_EVENT unset and clients waiting for the batch to close.
341 qty -= trade_qty;
342 if (!ctx.book.executeOrder(book_order_id, trade_qty, ctx.event_time, ctx.seq_num, qty == 0)) [[unlikely]] {
343 // The execution failed, so the resting quantity is unchanged. Restore the
344 // aggressor quantity and stop; retrying would repeatedly report fills
345 // against the same liquidity.
346 qty += trade_qty;
347 LOG_ERROR("{} book rejected execution of order {} for qty {} at price {} (seq_num={}); abandoning match with {} unfilled",
348 ctx.book.symbolName().view(), book_order_id, trade_qty, price, ctx.seq_num, qty);
349 return false;
350 }
351
352 if (our_order) {
353 ctx.engine.publishOrderExecution(our_order, false);
354 LOG_INFO("{} order {} filled {}@{}, leaves_qty={}, executed_qty={}, avg_fill_price={}", our_order->symbol.view(), our_order->order_id.view(), to_qty_double(trade_qty), to_price_double(price), to_qty_double(our_order->leaves_quantity), to_qty_double(our_order->cum_quantity), to_price_double(our_order->avg_fill_price));
355 if (our_order->leaves_quantity == 0) {
356 ctx.book.deleteOrder(our_order);
357 }
358 }
359
360 recordTrade<SIDE>(ctx, aggressor_id, book_order_id, price, trade_qty, our_order ? qty_t{0} : trade_qty);
361 return true;
362}
363
366inline void cancelUnrestableRemainder(MatchingEngine& engine, const Order* order, qty_t remaining,
367 slick::sim::time_t request_time) {
368 if (remaining > 0 && !order->restsRemainder()) {
369 engine.publishOrderCancel(order, request_time);
370 LOG_INFO("{} Order {} cannot rest and was not completely filled, canceling remaining qty {}", order->symbol.view(), order->id, remaining);
371 }
372}
373
374} // namespace slick::sim::engine::detail
Order * findOrder(uint64_t id)
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...
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)
void freeOrder(Order *order)
void publishOrderExecution(const Order *order, bool aggressor)
aggressor: the order crossed the spread, as opposed to resting and being hit.
static uint64_t nextTradeId() noexcept
std::string_view view() const noexcept
Reach
How far into a price level an aggressor reaches.
void recordTrade(MatchContext &ctx, uint64_t aggressor_id, uint64_t book_order_id, price_t price, qty_t trade_qty, qty_t phantom_qty)
Adds one fill to the trade summaries, which are aggregated per price level: a new summary when the pr...
bool isSelfMatch(const Order *incoming_order, const Order *book_order)
bool fillRestingFromFeed(MatchContext &ctx, uint64_t aggressor_id, uint64_t book_order_id, price_t price, qty_t trade_qty, qty_t &qty)
One fill of market-data liquidity against a resting order.
void cancelUnrestableRemainder(MatchingEngine &engine, const Order *order, qty_t remaining, slick::sim::time_t request_time)
What cannot rest is cancelled: an IOC's remainder, and a market order's, which would otherwise rest a...
bool canFillCompletely(const Order *order, price_t order_price, qty_t order_qty, OrderBook &book, SelfMatchPreventionMode smp_mode)
bool handleSelfMatch(MatchingEngine &engine, const Order *incoming_order, Order *book_order, OrderBook &book, slick::sim::time_t request_time, uint64_t event_time, uint64_t seq_num, SelfMatchPreventionMode smp_mode)
bool fillResting(MatchContext &ctx, Order *order, uint64_t book_order_id, Order *full_book_order, price_t price, qty_t trade_qty, qty_t remaining)
One fill of a client order against a resting order.
std::optional< OrdRejectReason > prepareOrder(MatchingEngine &engine, Order *order, price_t order_price, qty_t order_qty, OrderBook &book, slick::sim::time_t request_time, SelfMatchPreventionMode smp_mode)
Everything a client order goes through before it matches: the CANCEL_NEWEST pre-check,...
bool wouldSelfMatch(const Order *order, price_t order_price, qty_t order_qty, OrderBook &book)
bool isPriceBetterOrEqual(price_t a, price_t b)
Definition price.hpp:17
void executeOrder(Order *order, price_t price, qty_t executed_quantity, time_t timestamp)
Definition order.hpp:15
constexpr Side opposite_side()
Definition order.hpp:39
constexpr price_t NULL_PRICE
Definition types.hpp:28
uint_fast64_t time_t
Definition types.hpp:23
constexpr double to_price_double(price_t price)
Definition types.hpp:46
SelfMatchPreventionMode
Definition order.hpp:233
int_fast64_t qty_t
Definition types.hpp:22
constexpr double to_qty_double(qty_t qty)
Definition types.hpp:54
int_fast64_t price_t
Definition types.hpp:21
utils::fixed_string< 32 > symbol
Definition order.hpp:289
utils::fixed_string< 37 > order_id
Definition order.hpp:292
bool restsRemainder() const noexcept
Whether what matching leaves of it rests on the book; otherwise it is cancelled.
Definition order.hpp:356
TimeInForce time_in_force
Definition order.hpp:308
OrderStatus status
Definition order.hpp:307
qty_t leaves_quantity
Definition order.hpp:316
std::vector< Trade > Trades
Definition messages.hpp:393
qty_t phantom_qty
Portion of qty that was matched against phantom (market-mirroring) liquidity rather than the simulato...
Definition messages.hpp:391
State one match() call carries through its fills.
size_t legs_hint
Legs a summary started at the current level may reach, aggressor included.
std::vector< TradeSummaryInfo > summaries