Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
pro_rata_matching_engine.cpp
Go to the documentation of this file.
2#include "match_common.hpp"
3#include <utils/math.hpp>
4
5using namespace slick::sim;
6using namespace slick::sim::engine;
7using namespace slick::sim::engine::detail;
8using namespace slick::sim::utils;
9
10namespace {
11
13inline qty_t share_of(qty_t a, qty_t b, qty_t c) noexcept {
14 return static_cast<qty_t>(mul_div_floor(static_cast<uint64_t>(a), static_cast<uint64_t>(b), static_cast<uint64_t>(c)));
15}
16
17} // namespace
18
19ProRataMatchingEngine::ProRataMatchingEngine(slick::queue<OrderResponse> &response_queue, const ProRataConfig &config)
20 : MatchingEngine(response_queue)
21 , config_(config)
22{
23 // Not an assert: a zero lot divides by zero and a percentage over 100
24 // over-allocates, and Release builds would carry on with either.
25 config_.validate();
26 allocations_.reserve(256);
27}
28
29void ProRataMatchingEngine::allocate(const slick::orderbook::detail::PriceLevelL3 &level, qty_t qty, OrderBook &book, bool resolve) {
30 allocations_.clear();
31 qty_t total = 0;
32 for (const auto &book_order : level.orders) {
33 allocations_.push_back({book_order.order_id, book_order.quantity, 0,
34 resolve ? book.findOrder(book_order.order_id) : nullptr});
35 total += book_order.quantity;
36 }
37
38 if (qty >= total) {
39 // The aggressor takes the whole level, so there is nothing to split.
40 for (auto &a : allocations_) {
41 a.qty = a.size;
42 }
43 return;
44 }
45
46 // From here qty < total, so every step below can place all it is given.
47 qty_t left = qty;
48
49 // 1. The FIFO slice.
50 if (config_.fifo_percent > 0) {
51 qty_t fifo = floorLot(share_of(qty, config_.fifo_percent, 100));
52 left -= fifo;
53 for (auto &a : allocations_) {
54 if (fifo == 0) {
55 break;
56 }
57 a.qty = std::min(fifo, a.size);
58 fifo -= a.qty;
59 }
60 }
61
62 // 2. Pro-rata on what each order still has, against what the level still has.
63 if (left > 0) {
64 const qty_t pro_rata = left;
65 const qty_t base = total - (qty - left);
66 for (auto &a : allocations_) {
67 qty_t share = floorLot(share_of(pro_rata, a.size - a.qty, base));
68 if (share < config_.min_allocation) {
69 share = 0;
70 }
71 a.qty += share;
72 left -= share;
73 }
74 }
75
76 // 3. Whatever is left goes FIFO, with no minimum. On a level of many small
77 // orders every share can round to zero, so this can be most of `qty`.
78 for (auto &a : allocations_) {
79 if (left == 0) {
80 break;
81 }
82 const qty_t extra = std::min(left, a.size - a.qty);
83 a.qty += extra;
84 left -= extra;
85 }
86 assert(left == 0);
87}
88
89template<Side SIDE>
90std::tuple<OrdRejectReason, std::vector<TradeSummaryInfo>> ProRataMatchingEngine::matchOrder(Order* order, price_t order_price, qty_t order_qty, OrderBook &book, slick::sim::time_t request_time, slick::sim::time_t event_time, uint64_t seq_num, SelfMatchPreventionMode smp_mode) {
91 if (auto done = prepareOrder<SIDE, Reach::Level>(*this, order, order_price, order_qty, book, request_time, smp_mode)) {
92 return std::make_tuple(*done, std::vector<TradeSummaryInfo>{});
93 }
94
95 MatchContext ctx{*this, book, event_time, seq_num};
96 const bool check_self_match = smp_mode != SelfMatchPreventionMode::NONE;
97 order_qty = order->leaves_quantity;
98 bool abandoned = false;
99
100 while (order_qty > 0 && !abandoned) {
101 auto best_level = book.getBestLevel<static_cast<slick::orderbook::Side>(SIDE)>();
102 if (!best_level || (order_price != NULL_PRICE && !isPriceBetterOrEqual<SIDE>(best_level->price, order_price))) {
103 break;
104 }
105 assert(!best_level->orders.empty() && "Price level has no orders");
106
107 const price_t level_price = best_level->price;
108 allocate(*best_level, order_qty, book, check_self_match);
109 ctx.legs_hint = allocations_.size() + 1;
110
111 if (check_self_match) [[unlikely]] {
112 // Pro-rata can allocate to any order on the level, so every own order on
113 // it is a self-match, not just those the quantity reaches in queue order.
114 bool cancelled = false;
115 for (const auto &a : allocations_) {
116 if (!isSelfMatch(order, a.order)) {
117 continue;
118 }
119 if (!handleSelfMatch(*this, order, a.order, book, request_time, event_time, seq_num, smp_mode)) {
120 // CANCEL_NEWEST backstop: prepareOrder should already have rejected this.
121 return std::make_tuple(OrdRejectReason::SMP, std::move(ctx.summaries));
122 }
123 cancelled = true;
124 }
125 if (cancelled) {
126 continue; // the level changed, and may be gone
127 }
128 }
129
130 for (const auto &a : allocations_) {
131 if (a.qty == 0) {
132 continue;
133 }
134 order_qty -= a.qty;
135 auto *full_book_order = check_self_match ? a.order : book.findOrder(a.order_id);
136 if (!fillResting<SIDE>(ctx, order, a.order_id, full_book_order, level_price, a.qty, order_qty)) [[unlikely]] {
137 abandoned = true;
138 break;
139 }
140 }
141 }
142
143 cancelUnrestableRemainder(*this, order, order_qty, request_time);
144 return std::make_tuple(OrdRejectReason::NONE, std::move(ctx.summaries));
145}
146
147template<Side SIDE>
148std::vector<TradeSummaryInfo> ProRataMatchingEngine::matchFeed(uint64_t order_id, price_t price, qty_t &qty, OrderBook &book, slick::sim::time_t event_time, uint64_t seq_num) {
149 MatchContext ctx{*this, book, event_time, seq_num};
150
151 while (qty > 0) {
152 auto best_level = book.getBestLevel<static_cast<slick::orderbook::Side>(SIDE)>();
153 if (!best_level || (price != NULL_PRICE && !isPriceBetterOrEqual<SIDE>(best_level->price, price))) {
154 break;
155 }
156 assert(!best_level->orders.empty() && "Price level has no orders");
157
158 const price_t level_price = best_level->price;
159 allocate(*best_level, qty, book, false);
160 ctx.legs_hint = allocations_.size() + 1;
161 for (const auto &a : allocations_) {
162 if (a.qty == 0) {
163 continue;
164 }
165 if (!fillRestingFromFeed<SIDE>(ctx, order_id, a.order_id, level_price, a.qty, qty)) [[unlikely]] {
166 return std::move(ctx.summaries);
167 }
168 }
169 }
170
171 return std::move(ctx.summaries);
172}
173
174std::tuple<OrdRejectReason, std::vector<TradeSummaryInfo>> ProRataMatchingEngine::match(Order* order, price_t order_price, qty_t order_qty, OrderBook &book, slick::sim::time_t request_time, slick::sim::time_t event_time, uint64_t seq_num, SelfMatchPreventionMode smp_mode) {
175 return order->side == Side::BUY
176 ? matchOrder<Side::SELL>(order, order_price, order_qty, book, request_time, event_time, seq_num, smp_mode)
177 : matchOrder<Side::BUY>(order, order_price, order_qty, book, request_time, event_time, seq_num, smp_mode);
178}
179
180std::vector<TradeSummaryInfo> ProRataMatchingEngine::match(Side side, uint64_t order_id, price_t price, qty_t &qty, OrderBook &book, slick::sim::time_t event_time, uint64_t seq_num) {
181 return side == Side::BUY
182 ? matchFeed<Side::SELL>(order_id, price, qty, book, event_time, seq_num)
183 : matchFeed<Side::BUY>(order_id, price, qty, book, event_time, seq_num);
184}
Order * findOrder(uint64_t id)
MatchingEngine(slick::queue< OrderResponse > &response_queue)
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) override
ProRataMatchingEngine(slick::queue< OrderResponse > &response_queue, const ProRataConfig &config={})
const ProRataConfig & config() const noexcept
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 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,...
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
Definition decimal.hpp:9
bool isPriceBetterOrEqual(price_t a, price_t b)
Definition price.hpp:17
uint64_t mul_div_floor(uint64_t a, uint64_t b, uint64_t c) noexcept
floor(a * b / c), with the product held at 128 bits.
Definition math.hpp:19
constexpr price_t NULL_PRICE
Definition types.hpp:28
uint_fast64_t time_t
Definition types.hpp:23
SelfMatchPreventionMode
Definition order.hpp:233
int_fast64_t qty_t
Definition types.hpp:22
int_fast64_t price_t
Definition types.hpp:21
qty_t leaves_quantity
Definition order.hpp:316
Pro-rata allocation rules. Quantities use the venue's fixed-point scale.
size_t legs_hint
Legs a summary started at the current level may reach, aggressor included.
std::vector< TradeSummaryInfo > summaries