Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_exchange.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
5#include <coinbase/websocket.hpp>
6#include <utils/timestamp.hpp>
7#include <utils/price.hpp>
8#include <chrono>
12
13using namespace slick::sim;
14using namespace slick::sim::exch;
15using namespace slick::sim::order_gateway;
16using namespace slick::sim::md_publisher;
17
18namespace
19{
20 auto &sym_mgr = SymbolManager::instance();
21}
22
23CoinbaseExchange::CoinbaseExchange(const nlohmann::json &config)
24 : Exchange(Venue::COINBASE, config), coinbase::UserThreadWebsocketCallbacks(), ws_mux_(config.value("md_queue_size", 16777216))
25{
26 md_publisher_ = std::make_unique<CoinbasePublisher>(config["md_publisher"], request_queue_, md_queue_);
27
28 auto &og_config = config["order_gateway"];
29 if (!og_config.contains("rest"))
30 {
31 throw std::runtime_error("COINBASE Exchange order_gateway missing rest config");
32 }
33 order_gateways_.emplace_back(
34 std::make_unique<CoinbaseRestOrderGateway>(og_config["rest"], request_queue_, response_queue_));
35 if (og_config.contains("ws"))
36 {
37 order_gateways_.emplace_back(
38 std::make_unique<CoinbaseWebsocketOrderGateway>(og_config["ws"], request_queue_, response_queue_));
39 }
40
41 if (config.contains("md_feeds"))
42 {
43 for (const auto &md_feed_config : config["md_feeds"])
44 {
45 std::string type = md_feed_config.value("type", "");
46 if (!md_feed_config.value("enabled", true))
47 {
48 LOG_INFO("Coinbase skipping disabled md_feed type {}", type);
49 continue;
50 }
51 if (type == "coinbase_live_ws")
52 {
53 use_live_feed_ = true;
54 }
55 }
56 }
57}
58
59std::vector<FeedInfo> CoinbaseExchange::enabledFeeds() const
60{
61 // Not md_feeds_, which holds a feed per subscription.
62 return use_live_feed_ && enabled_ ? std::vector<FeedInfo>{feedInfo(md_feed::FeedKind::LIVE)}
63 : std::vector<FeedInfo>{};
64}
65
67{
68 if (md_feed_ || !md_feeds_.empty())
69 {
70 // coinbase::UserThreadWebsocketCallbacks::processData - drains whatever the
71 // SDK's network thread buffered into ws_mux_, firing our on* callbacks on
72 // this (the exchange) thread.
73 processData();
74 }
76}
77
78Symbol *CoinbaseExchange::addSymbol(std::string_view product_id)
79{
80 assert(!sym_mgr.getSymbol(product_id, venue_));
81 auto symbol = sym_mgr.createSymbol(product_id, Venue::COINBASE);
82 assert(symbol);
83 assignMatching(symbol); // FIFO: Coinbase never calls configureMatching
84 symbol->createOrderBook<OrderBookType::L2>();
85 return symbol;
86}
87
89{
90 const auto &msg = request.md_subscription;
91 std::string sym = request.symbol;
92 auto *symbol = sym_mgr.getSymbol(sym, venue_);
93 if (!symbol)
94 {
95 symbol = addSymbol(sym);
96 if (use_live_feed_)
97 {
98 switch (static_cast<coinbase::WebSocketChannel>(msg.channel))
99 {
100 case coinbase::WebSocketChannel::LEVEL2:
101 {
102 pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2].emplace(symbol);
103 break;
104 }
105 case coinbase::WebSocketChannel::MARKET_TRADES:
106 {
107 pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES].emplace(symbol);
108 break;
109 }
110 case coinbase::WebSocketChannel::HEARTBEATS:
111 break;
112 case coinbase::WebSocketChannel::TICKER:
113 // No independent ticker quote is mirrored; confirm the channel with an
114 // empty snapshot so its subscriber bookkeeping completes.
115 publishMdSubscriptionResponse(symbol->symbol_, msg.channel);
116 break;
117 default:
118 LOG_WARN("Unsupported channel {} for symbol {}", static_cast<int>(msg.channel), sym);
119 return;
120 }
121 md_feeds_.emplace_back(std::make_shared<md_feed::CoinbaseLiveWSFeed>(ws_mux_, this, std::vector<std::string>{sym}, symbol->id_ * coinbase::ProducerType::_PRODUCER_TYPE_COUNT_));
122 auto &feed = md_feeds_.back();
123 feed->start();
124 map_symbol_feed_.emplace(sym, feed);
125 }
126 else
127 {
128 // TODO: reject?
129 switch (static_cast<coinbase::WebSocketChannel>(msg.channel))
130 {
131 case coinbase::WebSocketChannel::LEVEL2:
132 {
133 symbol->order_book_->populateL2SubscriptionResponse(md_queue_, msg.channel);
134 break;
135 }
136 case coinbase::WebSocketChannel::MARKET_TRADES:
137 {
138 populateMDTradesResponse(symbol);
139 break;
140 }
141 case coinbase::WebSocketChannel::HEARTBEATS:
142 break;
143 case coinbase::WebSocketChannel::TICKER:
144 // Same as above: an empty snapshot is the whole ticker channel.
145 publishMdSubscriptionResponse(symbol->symbol_, msg.channel);
146 break;
147 default:
148 LOG_WARN("Unsupported channel {} for symbol {}", static_cast<int>(msg.channel), sym);
149 return;
150 }
151 }
152 symbol->num_subscriptions_.fetch_add(1, std::memory_order_relaxed);
153 return;
154 }
155 symbol->num_subscriptions_.fetch_add(1, std::memory_order_relaxed);
156 switch (static_cast<coinbase::WebSocketChannel>(msg.channel))
157 {
158 case coinbase::WebSocketChannel::LEVEL2:
159 {
160 auto &pending_l2_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2];
161 if (pending_l2_subscriptions.find(symbol) == pending_l2_subscriptions.end())
162 {
163 // subscription already received, publish snapshot immediately
164 symbol->order_book_->populateL2SubscriptionResponse(md_queue_, msg.channel);
165 }
166 else
167 {
168 // Already pending, do nothing
169 }
170 break;
171 }
172 case coinbase::WebSocketChannel::MARKET_TRADES:
173 {
174 auto &pending_trade_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES];
175 if (pending_trade_subscriptions.find(symbol) == pending_trade_subscriptions.end())
176 {
177 // subscription already received, publish snapshot immediately
178 populateMDTradesResponse(symbol);
179 }
180 else
181 {
182 // Already pending, do nothing
183 }
184 break;
185 }
186 case coinbase::WebSocketChannel::TICKER:
187 {
188 // An already-created symbol answers ticker subscriptions the same way.
189 publishMdSubscriptionResponse(symbol->symbol_, msg.channel);
190 break;
191 }
192 default:
193 break;
194 }
195}
196
198{
199 std::string sym = request.symbol;
200 auto *symbol = sym_mgr.getSymbol(sym, venue_);
201 if (!symbol)
202 {
203 return;
204 }
205 if (symbol->num_subscriptions_.fetch_sub(1, std::memory_order_relaxed) == 1)
206 {
207 auto it_feed = map_symbol_feed_.find(sym);
208 if (it_feed != map_symbol_feed_.end())
209 {
210 auto feed = it_feed->second;
211 feed->stop();
212 md_feeds_.erase(std::remove(md_feeds_.begin(), md_feeds_.end(), feed), md_feeds_.end());
213 map_symbol_feed_.erase(it_feed);
214 }
215 }
216}
217
218uint64_t CoinbaseExchange::nextBookSeqNum(Symbol *symbol, SymbolEventState &state)
219{
220 // OrderBookL3::clear() leaves its sequence where it was, so a reconnect
221 // snapshot inherits whatever the previous session reached. Catch up rather
222 // than regress - a mutation stamped below the book's last sequence is
223 // discarded without a word.
224 const auto book_seq = symbol->order_book_->getLastSeqNum();
225 if (state.next_book_seq_num < book_seq)
226 {
227 state.next_book_seq_num = book_seq;
228 }
229 return ++state.next_book_seq_num;
230}
231
233{
234 const uint64_t now = utils::get_current_time_ns();
235
236 // Process events from all symbols
237 for (auto &[symbol, state] : symbol_event_state_)
238 {
239 auto &pending_events = state.pending_events;
240
241 // Process events from this symbol's priority queue
242 while (!pending_events.empty())
243 {
244 const auto &top_event = pending_events.top();
245
246 bool ready = force;
247 if (!force)
248 {
249 // Condition 1: Event is at least 1 second older than last dispatched event
250 bool safe_by_time_gap = (state.last_event_time > 0) &&
251 (top_event.event_time + utils::ONE_SECOND_NS <= state.last_event_time);
252
253 // Condition 2: Event has been in queue for more than 1 second (timeout)
254 uint64_t time_in_queue = now - top_event.received_time;
255 bool safe_by_timeout = time_in_queue >= utils::ONE_SECOND_NS;
256 ready = safe_by_time_gap || safe_by_timeout;
257 }
258
259 // Release if either condition is met
260 if (ready)
261 {
262 // Copy event before popping (since top() returns const ref)
263 Event event = top_event;
264 pending_events.pop();
265
266 // Dispatch the event. The book is stamped with dispatch order,
267 // never with event.seq_num - this loop pops by event_time, so the
268 // venue's arrival-order sequence regresses here routinely and the
269 // book's guard would drop the mutation. See next_book_seq_num.
270 dispatchEvent(symbol, event, state, nextBookSeqNum(symbol, state));
271
272 // if (!level_update_buffer_.empty()) {
273 // publishLevelUpdate(
274 // symbol->symbol_.c_str(),
275 // level_update_buffer_
276 // );
277 // level_update_buffer_.clear();
278 // }
279
280 state.last_sequence_id = event.sequence_id;
281 state.last_seq_num = event.seq_num;
282 }
283 else
284 {
285 // Top event not ready yet, stop processing this symbol
286 break;
287 }
288 }
289 }
290}
291
292void CoinbaseExchange::dispatchEvent(Symbol *symbol, const Event &event, SymbolEventState &state,
293 uint64_t book_seq_num)
294{
295 if (event.type == EventType::LEVEL_UPDATE)
296 {
297 // Ignore stale events - skip if older than last update
298 if (event.event_time < symbol->order_book_->lastUpdateTime())
299 {
300 LOG_WARN("[CoinbaseExchange] Skipping stale level update for symbol {}: seq_num={}, event_time={}({}), last_update_time={}({}) last_seq_num={}",
301 symbol->symbol_.view(),
302 event.seq_num,
303 utils::format_timestamp_iso8601(event.event_time), event.event_time,
304 utils::format_timestamp_iso8601(symbol->order_book_->lastUpdateTime()), symbol->order_book_->lastUpdateTime(), symbol->order_book_->lastSeqNum());
305 return;
306 }
307
308 // Update last update time before processing
309 // TODO: add fantom order then match
310
311 // auto book_side = to_book_side(side);
312 // if (is_snapshot) {
313 // feed_md_level_quantity_[price] = size;
314 // // Create a phantom order to represent the new L2 level
315 // addOrder(utils::nextOrderId(), book_side, price, size, event_time, nextOrderPriority(), seq_num, is_last_in_batch);
316 // auto [level, index] = getLevel(book_side, price);
317 // return std::make_tuple(index, level->total_quantity, static_cast<uint32_t>(level->orderCount()));
318 // }
319 auto &book = symbol->order_book_;
320
321 auto book_side = to_book_side(event.side);
322 auto [level, index] = symbol->order_book_->getLevel(book_side, event.price);
323 auto action = MDUpdateAction::ACTION_CHANGE;
324 if (!level)
325 {
326 // this is a new level
327 qty_t qty = event.qty;
328 auto order_id = utils::nextOrderId();
329 auto trade_summaries = symbol->matching_engine_->match(event.side, order_id, event.price, qty, *book.get(), event.event_time, book_seq_num);
330 if (qty)
331 {
332 symbol->order_book_->addBookOrder(order_id, book_side, event.price, qty, event.event_time, book_seq_num, event.flags & UpdateFlags::F_END_EVENT);
334 }
335
336 if (!trade_summaries.empty())
337 {
338 for (const auto &summary : trade_summaries)
339 {
340 publishTradeSummary(symbol, summary);
341 }
342 }
343
344 flushMarketDataCaches(symbol);
345 }
346 else
347 {
348 // existing level
349 reconcilePhantomQty(symbol, event.side, event.price, event.qty, event.event_time,
350 book_seq_num, event.flags & UpdateFlags::F_END_EVENT);
351 }
352
353 symbol->order_book_->setLastUpdate(event.event_time, event.seq_num);
354
355 if (!state.last_published_level_seq_num) [[unlikely]]
356 {
357 state.last_published_level_seq_num = event.seq_num;
358 }
359
360 if (!state.level_update_buffer_.empty() &&
361 event.seq_num != state.last_published_level_seq_num)
362 {
364 symbol->symbol_,
365 state.level_update_buffer_);
366 state.last_published_level_seq_num = state.level_update_buffer_.back().seq_num;
367 state.level_update_buffer_.clear();
368 }
369
370 auto [new_level, new_index] = symbol->order_book_->getLevel(book_side, event.price);
371 if (!level && new_level)
372 {
373 index = new_index;
374 }
375 else if (!new_level)
376 {
378 }
379
380 // Publish the level as the book actually holds it, not the venue's raw
381 // figure. Two reasons they diverge:
382 //
383 // - The book may decline to take the update at face value:
384 // reconcilePhantomQty lowers a stale update's target by the quantity a
385 // trade already removed, and the new-level branch above rests only what
386 // survived matching.
387 // - total_quantity includes the simulator's own resting orders. A real
388 // venue's L2 shows your orders too, and both other producers of level
389 // data agree - Symbol::onPriceLevelUpdate forwards the book's level
390 // quantity, and populateL2Snapshot publishes total_quantity.
391 //
392 // Emitting event.qty would leave a client's incrementally-maintained book
393 // disagreeing with the simulator's own, and with any snapshot it re-reads.
394 auto published_qty = new_level ? new_level->total_quantity : qty_t{0};
395 auto published_orders = new_level ? static_cast<uint32_t>(new_level->orderCount()) : 0u;
396
397 state.level_update_buffer_.emplace_back(MDLevel{
398 .event_time = event.event_time,
399 .seq_num = event.seq_num,
400 .price = event.price,
401 .qty = published_qty,
402 .num_orders = published_orders,
403 .level_index = index,
404 .update_action = action,
405 .flags = event.flags,
406 .side = event.side});
407 }
408 else if (event.type == EventType::TRADE)
409 {
410 // The venue's print is replayed as an incoming aggressor order: it takes
411 // liquidity from the book exactly as the real taker did, filling any
412 // simulator order that was ahead of the phantom liquidity it swept. Only
413 // the resulting fills are published - the print itself is never relayed.
414 auto &book = *symbol->order_book_;
415 auto book_side = to_book_side(event.side);
416 auto order_id = utils::nextOrderId();
417
418 qty_t qty = event.qty;
419 auto trade_summaries = symbol->matching_engine_->match(
420 event.side, order_id, event.price, qty, book, event.event_time, book_seq_num);
421
422 if (qty)
423 {
424 // Treated as an aggressor order, so the unfilled remainder rests -
425 // same as the new-level branch above, and with the same order id. It
426 // cannot cross: a remainder exists precisely because nothing was
427 // still crossable at this limit.
428 book.addBookOrder(order_id, book_side, event.price, qty, event.event_time, book_seq_num,
429 event.flags & UpdateFlags::F_END_EVENT);
430 }
431
432 for (const auto &summary : trade_summaries)
433 {
434 // The venue will report the same reduction again in its level update
435 // for this trade; credit it so that update does not remove it twice.
436 symbol->creditTradedQty(opposite_side(event.side), summary.price,
437 summary.phantom_qty, event.event_time);
438 publishTradeSummary(symbol, summary);
439 }
440
441 flushMarketDataCaches(symbol);
442 }
443}
444
445void CoinbaseExchange::populateMDTradesResponse(Symbol *symbol)
446{
447 publishTradeSubscriptionResponse(symbol, coinbase::WebSocketChannel::MARKET_TRADES);
448}
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
void poll() override
One iteration of the exchange thread's loop, called continuously between start() and stop().
void handleMdUnsubscription(const Request &request) override
void processSequencedEvents(bool force=false)
CoinbaseExchange(const nlohmann::json &config)
std::vector< FeedInfo > enabledFeeds() const override
The market-data feeds the config enables: those in md_feed_ and md_feeds_.
void handleMdSubscription(const Request &request) override
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
std::shared_ptr< md_feed::MDFeed > md_feed_
Definition exchange.hpp:184
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
void flushMarketDataCaches(Symbol *symbol)
Publish and clear whatever market data the book produced while handling a request.
Definition exchange.cpp:559
queue< uint8_t > md_queue_
Definition exchange.hpp:183
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
Definition exchange.hpp:195
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
Exchange(Venue venue, const nlohmann::json &config)
Definition exchange.cpp:21
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
void publishLevelUpdate(const symbol_name_t &symbol, const std::vector< MDLevel > &level_updates)
Definition exchange.cpp:579
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
Definition exchange.cpp:254
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::string_view view() const noexcept
Helpers for a venue whose one config entry describes several independent exchange instances,...
Definition exchange.hpp:30
@ LIVE
The venue, as it happens.
Definition md_feed.hpp:14
constexpr uint64_t ONE_SECOND_NS
Definition timestamp.hpp:99
uint64_t nextOrderId() noexcept
Definition order.hpp:10
uint64_t get_current_time_ns()
Definition timestamp.hpp:93
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
Definition timestamp.hpp:9
constexpr Side opposite_side()
Definition order.hpp:39
orderbook::Side to_book_side(Side side)
int_fast64_t qty_t
Definition types.hpp:22
MDSubscriptionMessage md_subscription
Definition messages.hpp:285
void creditTradedQty(Side side, price_t price, qty_t phantom_consumed, time_t event_time)
Records that a trade print consumed phantom_consumed of the phantom liquidity resting at (side,...
Definition symbol.hpp:116
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::shared_ptr< OrderBook > order_book_
Definition symbol.hpp:48