Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
slick::sim::exch::Exchange Class Reference

#include <exchange/exchange.hpp>

Inheritance diagram for slick::sim::exch::Exchange:
Collaboration diagram for slick::sim::exch::Exchange:

Classes

struct  PhantomReduction
 Scratch for reconcilePhantomQty, reused so the reduction path allocates nothing. More...

Public Member Functions

 Exchange (Venue venue, const nlohmann::json &config)
virtual ~Exchange ()
virtual void start ()
virtual void stop ()
queue< Request > & request_queue () noexcept
queue< OrderResponse > & response_queue () noexcept
queue< uint8_t > & md_queue () noexcept
virtual std::vector< cli::CliEndpoint * > cliEndpoints ()
 Where the CLI reaches this exchange's commands (cli/cli_endpoint.hpp), each named <venue>/<instance>[/...], and served on whichever thread owns what they change (for CME and ICE, the order gateways').
std::vector< cli::CliEndpoint * > feedCliEndpoints () const
 The CLI endpoints of md_feed_ and md_feeds_ (a pcap feed's pcap/<venue>/<feed>).
virtual std::vector< FeedInfo > enabledFeeds () const
 The market-data feeds the config enables: those in md_feed_ and md_feeds_.

Protected Member Functions

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.
virtual OrdRejectReason newOrderAdmission () const noexcept
void processRequest ()
void handleNewOrderRequest (const Request &request)
void handleModifyOrderRequest (const Request &request)
void handleCancelOrderRequest (const Request &request)
void rejectMdSubscription (const Request &request, MDSubscriptionRejectReason reason)
void publishMdSubscriptionResponse (const symbol_name_t &symbol, uint8_t channel)
 Publishes an accepted subscription response without a snapshot payload.
void rejectNewOrderRequest (const Request &request, OrdRejectReason reason)
void rejectModifyOrderRequest (const Request &request, OrdRejectReason reason)
void rejectCancelOrderRequest (const Request &request, OrdRejectReason reason)
void sendOrderNewPending (const Order *order, time_t request_time)
void sendOrderReplacePending (const Order *order, time_t request_time)
void sendOrderCancelPending (const Order *order, time_t request_time)
void flushMarketDataCaches (Symbol *symbol)
 Publish and clear whatever market data the book produced while handling a request.
void publishMDBookUpdate (symid_t sid, OrderBook &order_book, const std::array< uint8_t, 2 > &indices)
void publishLevelUpdate (const symbol_name_t &symbol, const std::vector< MDLevel > &level_updates)
void publishMDOrderUpdate (const symbol_name_t &symbol, const std::vector< MDOrder > &order_updates)
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 history, which serves the subscribe snapshot.
void publishTradeSubscriptionResponse (Symbol *symbol, uint8_t channel)
 Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history, split against the book snapshot the subscriber receives with it.
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, leaving the simulator's own orders alone.
void applyMarketOrder (Symbol *symbol, const MarketOrderEvent &event)
 Rests, changes or removes a market order as a phantom order.
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 queued ahead of the market orders it filled is filled first.
void flushMarketEvents ()
 Publishes every symbol a market event changed since the last call.
uint64_t nextVenueTradeId () noexcept
 Public trade ids, one independent sequence per venue.
int clientIdFor (const char *user_id)
 Resolves an order's user_id to the integer identity self-match prevention compares.
void configureMatching (const nlohmann::json &config)
 Reads matching_algorithm and pro_rata from the venue's config.
const engine::MatchingConfig & matchingConfig () const noexcept
void assignMatching (Symbol *symbol)
 Points a new symbol at the venue's configured engine, creating the engine on first use, and stamps the venue's SMP mode on it.
virtual void handleMdSubscription (const Request &)
virtual void handleMdUnsubscription (const Request &)
virtual void poll ()
 One iteration of the exchange thread's loop, called continuously between start() and stop().
template<typename Fn>
void forEachFeed (Fn &&fn) const
 Calls fn(MDFeed &) on md_feed_ and each of md_feeds_.
void restMarketOrder (Symbol *symbol, const MarketOrderEvent &event)
void markMarketChanged (Symbol *symbol)

Protected Attributes

Venue venue_
std::string instance_
 The config's name, one per instance of a venue that has several. Empty without one.
queue< Request > request_queue_
queue< OrderResponse > response_queue_
queue< uint8_t > md_queue_
std::shared_ptr< md_feed::MDFeed > md_feed_
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
 Feeds owned by the exchange and managed by base start()/stop().
std::thread thread_
std::thread md_thread_
std::atomic_bool run_ {true}
uint_fast64_t order_request_cursor_ {0}
std::array< std::unique_ptr< engine::MatchingEngine >, engine::MatchingEngine::Type::__count__ > matching_engines_
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
bool enabled_ = true
bool publish_order_updates_ = false
 Whether flushMarketDataCaches publishes the per-order (MDUpdateType::ORDER) frames the book produces.
uint64_t next_trade_id_ {1}
std::vector< PhantomReduction > phantom_reductions_
std::vector< Symbol * > market_changed_symbols_
 Symbols a market event has changed and not yet published.
SelfMatchPreventionMode smp_mode_ = SelfMatchPreventionMode::NONE
 Self-match prevention mode applied to every symbol on this venue, from the self_match_prevention config key.
engine::MatchingConfig matching_
 The engine assignMatching hands out. FIFO unless configureMatching says otherwise.
bool matching_keys_unread_ = false
 The config sets matching keys and configureMatching has not read them, so start() warns that this venue matches FIFO regardless.
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.
int next_client_id_ = 0

Detailed Description

Definition at line 34 of file exchange.hpp.

Constructor & Destructor Documentation

◆ Exchange()

Exchange::Exchange ( Venue venue,
const nlohmann::json & config )

◆ ~Exchange()

virtual slick::sim::exch::Exchange::~Exchange ( )
inlinevirtual

Definition at line 38 of file exchange.hpp.

References stop().

Member Function Documentation

◆ applyMarketOrder()

void Exchange::applyMarketOrder ( Symbol * symbol,
const MarketOrderEvent & event )
protected

Rests, changes or removes a market order as a phantom order.

The venue's own book is never crossed, so a market order that would cross ours is crossing a client's order. It is matched first, filling the client, and rests with what is left.

Definition at line 792 of file exchange.cpp.

References slick::sim::exch::MarketOrderEvent::action, slick::sim::ACTION_CHANGE, slick::sim::ACTION_DELETE, slick::sim::ACTION_NEW, slick::sim::exch::MarketOrderEvent::book_order_id, markMarketChanged(), slick::sim::exch::Symbol::order_book_, slick::sim::exch::MarketOrderEvent::price, slick::sim::exch::MarketOrderEvent::qty, slick::sim::exch::MarketOrderEvent::requeue, and restMarketOrder().

◆ assignMatching()

void Exchange::assignMatching ( Symbol * symbol)
protected

Points a new symbol at the venue's configured engine, creating the engine on first use, and stamps the venue's SMP mode on it.

Definition at line 254 of file exchange.cpp.

References slick::sim::engine::createMatchingEngine(), matching_, slick::sim::exch::Symbol::matching_engine_, matching_engines_, response_queue_, smp_mode_, and slick::sim::exch::Symbol::smp_mode_.

◆ cliEndpoints()

virtual std::vector< cli::CliEndpoint * > slick::sim::exch::Exchange::cliEndpoints ( )
inlinevirtual

Where the CLI reaches this exchange's commands (cli/cli_endpoint.hpp), each named <venue>/<instance>[/...], and served on whichever thread owns what they change (for CME and ICE, the order gateways').

Empty for a venue with no commands. Valid for the exchange's lifetime.

Definition at line 59 of file exchange.hpp.

◆ clientIdFor()

int Exchange::clientIdFor ( const char * user_id)
protected

Resolves an order's user_id to the integer identity self-match prevention compares.

Ids are assigned on first sight and stable for the life of the process; an empty user_id yields -1, which isSelfMatch treats as "no identity" and never matches, so an unauthenticated client is left out of SMP rather than being lumped in with every other one.

Definition at line 221 of file exchange.cpp.

References client_ids_, next_client_id_, and slick::sim::AddOrderMessage::user_id.

Referenced by handleNewOrderRequest().

◆ configureMatching()

void Exchange::configureMatching ( const nlohmann::json & config)
protected

Reads matching_algorithm and pro_rata from the venue's config.

Opt-in: only a venue that offers pro-rata calls it. Without it every symbol matches FIFO. Throws std::logic_error once a symbol has an engine, since that symbol would keep it.

Definition at line 243 of file exchange.cpp.

References slick::sim::engine::MatchingConfig::from_json(), matching_, matching_engines_, matching_keys_unread_, slick::sim::to_string(), and venue_.

◆ enabledFeeds()

std::vector< FeedInfo > Exchange::enabledFeeds ( ) const
nodiscardvirtual

The market-data feeds the config enables: those in md_feed_ and md_feeds_.

A venue that creates its feeds later says what it will have. Call before start(), as above.

Reimplemented in slick::sim::exch::CoinbaseExchange.

Definition at line 116 of file exchange.cpp.

References enabled_, feedInfo(), slick::sim::md_feed::MDFeed::feedKind(), slick::sim::md_feed::MDFeed::feedName(), and forEachFeed().

◆ feedCliEndpoints()

std::vector< slick::sim::cli::CliEndpoint * > Exchange::feedCliEndpoints ( ) const
nodiscard

The CLI endpoints of md_feed_ and md_feeds_ (a pcap feed's pcap/<venue>/<feed>).

Call before start(): a venue may add feeds on the exchange thread once it runs.

Definition at line 105 of file exchange.cpp.

References slick::sim::md_feed::MDFeed::cliEndpoint(), and forEachFeed().

◆ feedInfo()

FeedInfo Exchange::feedInfo ( md_feed::FeedKind kind,
std::string_view name = {} ) const
nodiscardprotected

This exchange's feed of kind, by the feed's name or, when empty, the exchange's own.

Definition at line 127 of file exchange.cpp.

References instance_, slick::sim::cli::instance_path(), slick::sim::to_string(), venue_, and slick::sim::cli::venue_path().

Referenced by slick::sim::exch::CoinbaseExchange::enabledFeeds(), and enabledFeeds().

◆ flushMarketDataCaches()

void Exchange::flushMarketDataCaches ( Symbol * symbol)
protected

Publish and clear whatever market data the book produced while handling a request.

Every path that can change the book has to end in this call – the caches are drained nowhere else, so an update left behind is not published late, it is published only when some later request happens to flush it, or never at all if none follows.

Definition at line 559 of file exchange.cpp.

References slick::sim::exch::Symbol::md_level_update_cache_, slick::sim::exch::Symbol::md_order_update_cache_, publish_order_updates_, publishLevelUpdate(), publishMDOrderUpdate(), and slick::sim::exch::Symbol::symbol_.

Referenced by flushMarketEvents(), handleCancelOrderRequest(), handleModifyOrderRequest(), and handleNewOrderRequest().

◆ flushMarketEvents()

void Exchange::flushMarketEvents ( )
protected

Publishes every symbol a market event changed since the last call.

Definition at line 875 of file exchange.cpp.

References flushMarketDataCaches(), and market_changed_symbols_.

◆ forEachFeed()

template<typename Fn>
void slick::sim::exch::Exchange::forEachFeed ( Fn && fn) const
inlineprotected

Calls fn(MDFeed &) on md_feed_ and each of md_feeds_.

Definition at line 200 of file exchange.hpp.

References md_feed_, and md_feeds_.

Referenced by enabledFeeds(), and feedCliEndpoints().

◆ handleCancelOrderRequest()

◆ handleMdSubscription()

virtual void slick::sim::exch::Exchange::handleMdSubscription ( const Request & )
inlineprotectedvirtual

Reimplemented in slick::sim::exch::CoinbaseExchange, and slick::sim::exch::HyperliquidExchange.

Definition at line 163 of file exchange.hpp.

Referenced by processRequest().

◆ handleMdUnsubscription()

virtual void slick::sim::exch::Exchange::handleMdUnsubscription ( const Request & )
inlineprotectedvirtual

Reimplemented in slick::sim::exch::CoinbaseExchange, and slick::sim::exch::HyperliquidExchange.

Definition at line 164 of file exchange.hpp.

Referenced by processRequest().

◆ handleModifyOrderRequest()

◆ handleNewOrderRequest()

◆ markMarketChanged()

void Exchange::markMarketChanged ( Symbol * symbol)
protected

Definition at line 884 of file exchange.cpp.

References market_changed_symbols_.

Referenced by applyMarketOrder(), and replayMarketTrade().

◆ matchingConfig()

const engine::MatchingConfig & slick::sim::exch::Exchange::matchingConfig ( ) const
inlineprotectednoexcept

Definition at line 156 of file exchange.hpp.

References matching_.

◆ md_queue()

queue< uint8_t > & slick::sim::exch::Exchange::md_queue ( )
inlinenoexcept

Definition at line 51 of file exchange.hpp.

References md_queue_.

◆ newOrderAdmission()

virtual OrdRejectReason slick::sim::exch::Exchange::newOrderAdmission ( ) const
inlineprotectedvirtualnoexcept

Definition at line 74 of file exchange.hpp.

References slick::sim::NONE.

Referenced by handleModifyOrderRequest(), and handleNewOrderRequest().

◆ nextVenueTradeId()

uint64_t slick::sim::exch::Exchange::nextVenueTradeId ( )
inlineprotectednoexcept

Public trade ids, one independent sequence per venue.

Exchange-thread only, so a plain increment is enough.

Definition at line 142 of file exchange.hpp.

References next_trade_id_.

Referenced by slick::sim::exch::CoinbaseExchange::onMarketTradesSnapshot(), and publishTradeSummary().

◆ poll()

virtual void slick::sim::exch::Exchange::poll ( )
inlineprotectedvirtual

One iteration of the exchange thread's loop, called continuously between start() and stop().

Override it to drain the venue SDK and release any feed events it queued; the base loop calls processRequest() immediately after it on every tick, so an adapter never rewrites the loop itself.

Runs on the exchange thread - the only thread that touches books - so an override may mutate them directly. An adapter with no feed leaves this alone and still serves clients matching against each other.

Reimplemented in slick::sim::exch::CoinbaseExchange, and slick::sim::exch::HyperliquidExchange.

Definition at line 174 of file exchange.hpp.

Referenced by start().

◆ processRequest()

◆ publishLevelUpdate()

void Exchange::publishLevelUpdate ( const symbol_name_t & symbol,
const std::vector< MDLevel > & level_updates )
protected

◆ publishMDBookUpdate()

◆ publishMDOrderUpdate()

void Exchange::publishMDOrderUpdate ( const symbol_name_t & symbol,
const std::vector< MDOrder > & order_updates )
protected

◆ publishMdSubscriptionResponse()

void Exchange::publishMdSubscriptionResponse ( const symbol_name_t & symbol,
uint8_t channel )
protected

Publishes an accepted subscription response without a snapshot payload.

The publisher's channel handler interprets the empty response; ticker subscriptions use it to confirm an empty snapshot.

Definition at line 446 of file exchange.cpp.

References slick::sim::MDSubscriptionResponse::channel, slick::sim::utils::fixed_string< N >::data(), md_queue_, slick::sim::NONE, slick::sim::SUB_RESPONSE, slick::sim::MarketDataUpdate::type, and venue_.

Referenced by slick::sim::exch::CoinbaseExchange::handleMdSubscription().

◆ publishTradeSubscriptionResponse()

void Exchange::publishTradeSubscriptionResponse ( Symbol * symbol,
uint8_t channel )
protected

◆ publishTradeSummary()

◆ reconcilePhantomQty()

void Exchange::reconcilePhantomQty ( Symbol * symbol,
Side side,
price_t price,
qty_t target_qty,
time_t event_time,
uint64_t seq_num,
bool end_event )
protected

Adjusts the phantom (market-mirroring) quantity at an existing (side, price) level toward target_qty, leaving the simulator's own orders alone.

Offsets any reduction a trade print already applied at that price so the same quantity is not removed twice.

Definition at line 715 of file exchange.cpp.

References slick::sim::exch::Symbol::findOrder(), slick::sim::utils::nextOrderId(), slick::sim::exch::Symbol::order_book_, phantom_reductions_, slick::sim::exch::Symbol::takeTradedQty(), and slick::sim::to_book_side().

◆ rejectCancelOrderRequest()

◆ rejectMdSubscription()

◆ rejectModifyOrderRequest()

◆ rejectNewOrderRequest()

◆ replayMarketTrade()

void Exchange::replayMarketTrade ( Symbol * symbol,
const MarketTradeEvent & event )
protected

Replays a market trade as an aggressor order at the trade's price and quantity, so a client order queued ahead of the market orders it filled is filled first.

The venue's order updates for those orders follow and set each to its reported quantity. A remainder does not rest, because the venue reports the aggressor's residual as an order of its own.

Definition at line 861 of file exchange.cpp.

References slick::sim::exch::MarketTradeEvent::aggressor, markMarketChanged(), slick::sim::engine::MatchingEngine::match(), slick::sim::exch::Symbol::matching_engine_, slick::sim::utils::nextOrderId(), slick::sim::exch::Symbol::order_book_, slick::sim::exch::MarketTradeEvent::price, publishTradeSummary(), and slick::sim::exch::MarketTradeEvent::transact_time.

◆ request_queue()

queue< Request > & slick::sim::exch::Exchange::request_queue ( )
inlinenoexcept

Definition at line 45 of file exchange.hpp.

References request_queue_.

◆ response_queue()

queue< OrderResponse > & slick::sim::exch::Exchange::response_queue ( )
inlinenoexcept

Definition at line 48 of file exchange.hpp.

References response_queue_.

◆ restMarketOrder()

◆ sendOrderCancelPending()

◆ sendOrderNewPending()

◆ sendOrderReplacePending()

◆ start()

void Exchange::start ( )
virtual

◆ stop()

void Exchange::stop ( )
virtual

Definition at line 135 of file exchange.cpp.

References md_feed_, md_feeds_, md_publisher_, md_thread_, order_gateways_, run_, and thread_.

Referenced by ~Exchange().

Member Data Documentation

◆ client_ids_

std::unordered_map<utils::fixed_string<sizeof(AddOrderMessage::user_id)>, int, utils::StringViewHash, utils::StringViewEq> slick::sim::exch::Exchange::client_ids_
protected

Keys use the width of AddOrderMessage::user_id.

Transparent functors let clientIdFor look up a string_view without allocating a temporary string, even when user_id exceeds the small-string buffer.

Definition at line 253 of file exchange.hpp.

Referenced by clientIdFor().

◆ enabled_

bool slick::sim::exch::Exchange::enabled_ = true
protected

◆ instance_

std::string slick::sim::exch::Exchange::instance_
protected

The config's name, one per instance of a venue that has several. Empty without one.

Definition at line 180 of file exchange.hpp.

Referenced by Exchange(), and feedInfo().

◆ market_changed_symbols_

std::vector<Symbol *> slick::sim::exch::Exchange::market_changed_symbols_
protected

Symbols a market event has changed and not yet published.

A handful per venue, so a scan beats hashing - for as long as a venue flushes at the end of every packet, as CME and ICE do, which keeps the list to the symbols of one packet. A venue that flushed far less often would make markMarketChanged quadratic in its instrument count, and want a flag on Symbol instead.

Definition at line 237 of file exchange.hpp.

Referenced by flushMarketEvents(), and markMarketChanged().

◆ matching_

engine::MatchingConfig slick::sim::exch::Exchange::matching_
protected

The engine assignMatching hands out. FIFO unless configureMatching says otherwise.

Definition at line 245 of file exchange.hpp.

Referenced by assignMatching(), configureMatching(), and matchingConfig().

◆ matching_engines_

std::array<std::unique_ptr<engine::MatchingEngine>, engine::MatchingEngine::Type::__count__> slick::sim::exch::Exchange::matching_engines_
protected

Definition at line 194 of file exchange.hpp.

Referenced by assignMatching(), and configureMatching().

◆ matching_keys_unread_

bool slick::sim::exch::Exchange::matching_keys_unread_ = false
protected

The config sets matching keys and configureMatching has not read them, so start() warns that this venue matches FIFO regardless.

Definition at line 248 of file exchange.hpp.

Referenced by configureMatching(), and start().

◆ md_feed_

std::shared_ptr<md_feed::MDFeed> slick::sim::exch::Exchange::md_feed_
protected

Definition at line 184 of file exchange.hpp.

Referenced by forEachFeed(), slick::sim::exch::CoinbaseExchange::poll(), start(), and stop().

◆ md_feeds_

std::vector<std::shared_ptr<md_feed::MDFeed> > slick::sim::exch::Exchange::md_feeds_
protected

◆ md_publisher_

std::unique_ptr<md_publisher::MarketDataPublisher> slick::sim::exch::Exchange::md_publisher_
protected

◆ md_queue_

◆ md_thread_

std::thread slick::sim::exch::Exchange::md_thread_
protected

Definition at line 191 of file exchange.hpp.

Referenced by stop().

◆ next_client_id_

int slick::sim::exch::Exchange::next_client_id_ = 0
protected

Definition at line 254 of file exchange.hpp.

Referenced by clientIdFor().

◆ next_trade_id_

uint64_t slick::sim::exch::Exchange::next_trade_id_ {1}
protected

◆ order_gateways_

std::vector<std::unique_ptr<order_gateway::OrderGateway> > slick::sim::exch::Exchange::order_gateways_
protected

◆ order_request_cursor_

uint_fast64_t slick::sim::exch::Exchange::order_request_cursor_ {0}
protected

Definition at line 193 of file exchange.hpp.

Referenced by processRequest().

◆ phantom_reductions_

std::vector<PhantomReduction> slick::sim::exch::Exchange::phantom_reductions_
protected

Definition at line 230 of file exchange.hpp.

Referenced by reconcilePhantomQty().

◆ publish_order_updates_

bool slick::sim::exch::Exchange::publish_order_updates_ = false
protected

Whether flushMarketDataCaches publishes the per-order (MDUpdateType::ORDER) frames the book produces.

Off by default: only a venue with an order-by-order feed reads them, and every other venue would pay md_queue bandwidth for frames its publisher discards. An adapter that publishes MBO sets it in its constructor.

Definition at line 218 of file exchange.hpp.

Referenced by flushMarketDataCaches().

◆ request_queue_

queue<Request> slick::sim::exch::Exchange::request_queue_
protected

◆ response_queue_

◆ run_

std::atomic_bool slick::sim::exch::Exchange::run_ {true}
protected

Definition at line 192 of file exchange.hpp.

Referenced by start(), and stop().

◆ smp_mode_

SelfMatchPreventionMode slick::sim::exch::Exchange::smp_mode_ = SelfMatchPreventionMode::NONE
protected

Self-match prevention mode applied to every symbol on this venue, from the self_match_prevention config key.

Stamped onto each Symbol as it is created.

Definition at line 243 of file exchange.hpp.

Referenced by assignMatching().

◆ thread_

std::thread slick::sim::exch::Exchange::thread_
protected

Definition at line 190 of file exchange.hpp.

Referenced by start(), and stop().

◆ venue_


The documentation for this class was generated from the following files: