Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
exchange.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <slick/queue.hpp>
4#include <slick/object_pool.hpp>
5#include <md_feed/md_feed.hpp>
6#include <string>
7#include <string_view>
8#include <vector>
9#include <memory>
10#include <unordered_map>
11#include <thread>
12#include <array>
13#include <atomic>
14#include <nlohmann/json.hpp>
15#include <common/messages.hpp>
16#include <common/order.hpp>
23#include "feed_info.hpp"
24#include "market_events.hpp"
25
26namespace slick::sim::cli {
27class CliEndpoint;
28}
29
31
32struct Symbol;
33
34class Exchange {
35public:
36 Exchange(Venue venue, const nlohmann::json &config);
37
38 virtual ~Exchange() {
39 stop();
40 }
41
42 virtual void start();
43 virtual void stop();
44
45 queue<Request>& request_queue() noexcept {
46 return request_queue_;
47 }
48 queue<OrderResponse>& response_queue() noexcept {
49 return response_queue_;
50 }
51 queue<uint8_t>& md_queue() noexcept {
52 return md_queue_;
53 }
54
59 virtual std::vector<cli::CliEndpoint *> cliEndpoints() { return {}; }
60
63 [[nodiscard]] std::vector<cli::CliEndpoint *> feedCliEndpoints() const;
64
67 [[nodiscard]] virtual std::vector<FeedInfo> enabledFeeds() const;
68
69protected:
71 [[nodiscard]] FeedInfo feedInfo(md_feed::FeedKind kind, std::string_view name = {}) const;
72 // Venue admission check for new and modify requests, run again when a queued
73 // request reaches the book. Cancels and session recovery skip it.
74 virtual OrdRejectReason newOrderAdmission() const noexcept { return OrdRejectReason::NONE; }
75 void processRequest();
76 void handleNewOrderRequest(const Request &request);
77 void handleModifyOrderRequest(const Request &request);
78 void handleCancelOrderRequest(const Request &request);
79 void rejectMdSubscription(const Request &request, MDSubscriptionRejectReason reason);
83 void publishMdSubscriptionResponse(const symbol_name_t &symbol, uint8_t channel);
84 void rejectNewOrderRequest(const Request &request, OrdRejectReason reason);
85 void rejectModifyOrderRequest(const Request &request, OrdRejectReason reason);
86 void rejectCancelOrderRequest(const Request &request, OrdRejectReason reason);
87 void sendOrderNewPending(const Order *order, time_t request_time);
88 void sendOrderReplacePending(const Order *order, time_t request_time);
89 void sendOrderCancelPending(const Order *order, time_t request_time);
95 void flushMarketDataCaches(Symbol *symbol);
96
97 void publishMDBookUpdate(symid_t sid, OrderBook &order_book, const std::array<uint8_t, 2> &indices);
98 void publishLevelUpdate(const symbol_name_t &symbol, const std::vector<MDLevel> &level_updates);
99 void publishMDOrderUpdate(const symbol_name_t &symbol, const std::vector<MDOrder> &order_updates);
100 // NOTE: there is deliberately no raw trade relay. A venue trade print is
101 // replayed through the matching engine instead, and only the resulting fills
102 // are published - see publishTradeSummary and the venues' trade event handlers.
103
107 void publishTradeSummary(Symbol *symbol, const TradeSummaryInfo &trade_summary);
108
112 void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel);
113
118 void reconcilePhantomQty(Symbol *symbol, Side side, price_t price, qty_t target_qty,
119 time_t event_time, uint64_t seq_num, bool end_event);
120
121 // Order-by-order mirror of the venue's own book, for a venue whose live feed
122 // reports every order (CME MDP 3.0 MBO, ICE iMpact FOD). applyMarketOrder and
123 // replayMarketTrade mark the symbol changed, and flushMarketEvents publishes
124 // the changes once the venue's event closes.
125
130 void applyMarketOrder(Symbol *symbol, const MarketOrderEvent &event);
136 void replayMarketTrade(Symbol *symbol, const MarketTradeEvent &event);
138 void flushMarketEvents();
139
142 uint64_t nextVenueTradeId() noexcept { return next_trade_id_++; }
143
149 int clientIdFor(const char *user_id);
150
155 void configureMatching(const nlohmann::json &config);
156 const engine::MatchingConfig &matchingConfig() const noexcept {
157 return matching_;
158 }
159
161 void assignMatching(Symbol *symbol);
162
163 virtual void handleMdSubscription(const Request &/* request */) {}
164 virtual void handleMdUnsubscription(const Request &/* request */) {}
165
174 virtual void poll() {}
175
176
177protected:
180 std::string instance_;
181 queue<Request> request_queue_;
182 queue<OrderResponse> response_queue_;
183 queue<uint8_t> md_queue_;
184 std::shared_ptr<md_feed::MDFeed> md_feed_;
189 std::vector<std::shared_ptr<md_feed::MDFeed>> md_feeds_;
190 std::thread thread_;
191 std::thread md_thread_;
192 std::atomic_bool run_{true};
193 uint_fast64_t order_request_cursor_{0};
194 std::array<std::unique_ptr<engine::MatchingEngine>, engine::MatchingEngine::Type::__count__> matching_engines_;
195 std::vector<std::unique_ptr<order_gateway::OrderGateway>> order_gateways_;
196 std::unique_ptr<md_publisher::MarketDataPublisher> md_publisher_;
197 bool enabled_ = true;
199 template <typename Fn>
200 void forEachFeed(Fn &&fn) const
201 {
202 if (md_feed_)
203 {
204 fn(*md_feed_);
205 }
206 for (const auto &feed : md_feeds_)
207 {
208 if (feed)
209 {
210 fn(*feed);
211 }
212 }
213 }
214
219 uint64_t next_trade_id_{1};
220
226 uint64_t order_id;
228 uint64_t priority;
229 };
230 std::vector<PhantomReduction> phantom_reductions_;
231
237 std::vector<Symbol *> market_changed_symbols_;
238 void restMarketOrder(Symbol *symbol, const MarketOrderEvent &event);
239 void markMarketChanged(Symbol *symbol);
240
252 std::unordered_map<utils::fixed_string<sizeof(AddOrderMessage::user_id)>, int,
255};
256
257} // end namespace slick::sim::exch
Where the CLI server's commands reach a thread that owns some state (the main thread,...
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
const engine::MatchingConfig & matchingConfig() const noexcept
Definition exchange.hpp:156
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
queue< Request > & request_queue() noexcept
Definition exchange.hpp:45
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
queue< uint8_t > & md_queue() noexcept
Definition exchange.hpp:51
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
queue< OrderResponse > & response_queue() noexcept
Definition exchange.hpp:48
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
virtual std::vector< cli::CliEndpoint * > cliEndpoints()
Where the CLI reaches this exchange's commands (cli/cli_endpoint.hpp), each named <venue>/<instance>[...
Definition exchange.hpp:59
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
A null-terminated character buffer of fixed capacity, stored inline.
slick::sim::exch::Exchange Exchange
Definition main.cpp:42
The CLI commands that switch a gateway's business rejects per ID: REJECT_LOGON, REJECT_NEW_ORDERS and...
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
uint_fast64_t time_t
Definition types.hpp:23
SelfMatchPreventionMode
Definition order.hpp:233
uint16_t symid_t
Definition types.hpp:24
utils::fixed_string< sizeof(MarketDataUpdate::symbol)> symbol_name_t
An instrument name at its wire width.
int_fast64_t qty_t
Definition types.hpp:22
int_fast64_t price_t
Definition types.hpp:21
Which engine a venue's symbols match with.
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,...
One trade the venue reports, with the side that crossed the spread.
Transparent hash/equality for maps keyed by fixed_string.