Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_feed_callbacks.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
5#include <utils/timestamp.hpp>
6#include <charconv>
7
8using namespace slick::sim::exch;
9using namespace slick::sim;
10
11namespace
12{
13 auto &sym_mgr = SymbolManager::instance();
14}
15
17{
18 LOG_INFO("WebSocket {:p} market data connected", (void *)client);
19}
20
22{
23 LOG_INFO("WebSocket {:p} market data disconnected", (void *)client);
24
25 // Find the feed that owns this client
26 std::shared_ptr<md_feed::MDFeed> disconnected_feed;
27 for (auto &feed : md_feeds_)
28 {
29 auto *live_feed = dynamic_cast<md_feed::CoinbaseLiveWSFeed *>(feed.get());
30 if (live_feed && live_feed->getClient() == client)
31 {
32 disconnected_feed = feed;
33 break;
34 }
35 }
36
37 if (!disconnected_feed)
38 {
39 LOG_WARN("WebSocket {:p} disconnected but no matching feed found", (void *)client);
40 return;
41 }
42
43 // Collect symbols associated with this feed
44 std::vector<std::string> symbols;
45 for (auto &[sym, feed] : map_symbol_feed_)
46 {
47 if (feed == disconnected_feed)
48 {
49 symbols.push_back(sym);
50 }
51 }
52
53 if (symbols.empty())
54 {
55 return;
56 }
57
58 // Mark symbols as pending subscription so the snapshot is re-requested on reconnect
59 for (const auto &sym : symbols)
60 {
61 auto *symbol = sym_mgr.getSymbol(sym, venue_);
62 if (symbol)
63 {
64 pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2].emplace(symbol);
65 pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES].emplace(symbol);
66 symbol->clearTradeHistory();
67 }
68 }
69
70 // Restart the existing feed. WebSocketClient registers producers in its
71 // constructor, and the multiplexer cannot unregister them. A replacement with
72 // the same ids would throw std::invalid_argument on the exchange thread; new
73 // ids would leak the old 64MB market-data and 16MB user-data rings.
74 // start() calls subscribe(), which reopens a socket past CONNECTED and resends
75 // the subscription.
76 disconnected_feed->start();
77
78 LOG_INFO("WebSocket {:p} restarted market data feed for {} symbol(s)", (void *)client, symbols.size());
79}
80
82{
83 LOG_INFO("WebSocket {:p} user data connected", (void *)client);
84}
85
87{
88 LOG_INFO("WebSocket {:p} user data disonnected", (void *)client);
89}
90
91void CoinbaseExchange::onLevel2Snapshot(WebSocketClient * /* client */, uint64_t seq_num, const coinbase::Level2UpdateBatch &snapshot)
92{
93 auto *symbol = sym_mgr.getSymbol(snapshot.product_id, venue_);
94 if (!symbol) [[unlikely]]
95 {
96 return;
97 }
98
99 auto &pending_l2_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2];
100 auto it = pending_l2_subscriptions.find(symbol);
101 // Rebuild through clearMDOrders(), as Hyperliquid does. Plain clear() unlinks
102 // orders without notifying observers: phantom totals would stay stale and
103 // simulator orders would disappear from the book but remain in the lookup maps.
104 // clearMDOrders() resets those totals and preserves active simulator orders.
105 symbol->order_book_->clearMDOrders();
106
107 // Discard events for the old book before rebuilding. poll() processes these
108 // callbacks before processSequencedEvents(), so an old trade could otherwise
109 // consume fresh liquidity and produce false fills. The TRADE branch has no
110 // stale-timestamp guard; the level guard sees only the rebuilt book.
111 // Callbacks run in arrival order on the exchange thread, so every event queued
112 // here predates this snapshot. Later arrivals will be queued after the reset.
113 auto &state = symbol_event_state_[symbol];
114 state.pending_events = {};
115
116 // Discard the pending level batch too. It describes the old book and would
117 // otherwise be flushed after the snapshot when the sequence changes. Reset the
118 // publish boundary so the next event starts a new batch.
119 state.level_update_buffer_.clear();
120 state.last_published_level_seq_num = 0;
121
122 // One stamp for the whole snapshot: every update in it shares a sequence, and
123 // equal sequences pass the book's guard. It comes from the same counter the
124 // dispatch loop uses - this path bypasses the event queue entirely, and the two
125 // must not stamp the book out of different sequence spaces.
126 const uint64_t book_seq_num = nextBookSeqNum(symbol, state);
127 std::vector<MDLevel> level_updates;
128 std::vector<MDTrade> trade_updates;
129
130 for (auto it_update = snapshot.updates.rbegin(), it_last = std::prev(snapshot.updates.rend()); it_update != snapshot.updates.rend(); ++it_update)
131 {
132 auto &update = *it_update;
133 auto price = to_price_t(update.price_level);
134 auto side = static_cast<Side>(update.side);
135 auto book_side = to_book_side(side);
136 auto qty = to_qty_t(update.new_quantity);
137
138 auto order_id = utils::nextOrderId();
139 auto trade_summaries = symbol->matching_engine_->match(side, order_id, price, qty, *symbol->order_book_.get(), update.event_time, book_seq_num);
140 if (qty)
141 {
142 symbol->order_book_->addBookOrder(order_id, book_side, price, qty, update.event_time, book_seq_num, it_update == it_last);
143 }
144
145 if (!trade_summaries.empty())
146 {
147 for (const auto &summary : trade_summaries)
148 {
149 publishTradeSummary(symbol, summary);
150 }
151 }
152
153 // No incremental row is buffered for a snapshot level. populateL2Snapshot()
154 // below already publishes the rebuilt book in full, so these only duplicated
155 // it - arriving later, whenever the next event happened to change sequence,
156 // and carrying a level_index read while the rebuild was still in progress and
157 // therefore wrong by the time the level settled.
158
159 if (update.event_time > symbol->order_book_->lastUpdateTime())
160 {
161 symbol->order_book_->setLastUpdate(update.event_time, seq_num);
162 }
163 }
164
165 if (it != pending_l2_subscriptions.end())
166 {
167 symbol->order_book_->populateL2SubscriptionResponse(md_queue_, coinbase::WebSocketChannel::LEVEL2);
168 pending_l2_subscriptions.erase(it);
169 symbol->md_level_update_cache_.clear();
170 // TODO: publish MD order update
171 symbol->md_order_update_cache_.clear();
172 }
173 else
174 {
175 symbol->order_book_->populateL2Snapshot(md_queue_);
176 symbol->md_level_update_cache_.clear();
177 // TODO: publish MD order update
178 symbol->md_order_update_cache_.clear();
179 }
180
181 // publishMDBookUpdate(symbol->id_, *symbol->order_book_.get(), indices);
182 LOG_DEBUG(symbol->order_book_->to_string());
183}
184
185void CoinbaseExchange::onLevel2Updates(WebSocketClient * /* client */, uint64_t seq_num, const coinbase::Level2UpdateBatch &update_batch)
186{
187 auto *symbol = sym_mgr.getSymbol(update_batch.product_id, venue_);
188 if (!symbol) [[unlikely]]
189 {
190 return;
191 }
192
193 // Get or create event state for this symbol
194 auto &state = symbol_event_state_[symbol];
195
196 // Add each update to per-symbol pending_events queue.
197 //
198 // Both enqueue loops in this file walk their batch in reverse *dispatch* order:
199 // the element visited first takes the lowest sequence_id, and EventCompare pops
200 // the highest first, so the element enqueued first is dispatched last. The
201 // end-of-event marker therefore belongs on the element the loop visits first.
202 // `std::prev(rend())` is the opposite one - enqueued last, dispatched *first* -
203 // so marking it closed every batch on its opening update, and a client batching
204 // until the marker acted on one update out of the whole batch.
205 //
206 // onLevel2Snapshot is not the same shape: it applies its batch inline with no
207 // queue to reverse it, so the equivalent test there really is the final element.
208 const auto it_dispatched_last = update_batch.updates.rbegin();
209 for (auto it = update_batch.updates.rbegin(); it != update_batch.updates.rend(); ++it)
210 {
211 auto &update = *it;
212 Event evt;
213 evt.type = EventType::LEVEL_UPDATE;
214 evt.event_time = update.event_time; // Use Coinbase timestamp
215 evt.sequence_id = state.next_sequence_id++; // Internal counter
216 evt.seq_num = seq_num;
217 evt.received_time = utils::get_current_time_ns();
218 evt.price = to_price_t(update.price_level);
219 evt.qty = to_qty_t(update.new_quantity);
220 evt.side = static_cast<Side>(update.side);
221 evt.flags = it == it_dispatched_last ? UpdateFlags::F_END_EVENT : UpdateFlags::F_NONE;
222
223 // Update last_event_time to track latest event_time seen
224 if (state.last_event_time < evt.event_time)
225 {
226 state.last_event_time = evt.event_time;
227 }
228
229 // LOG_DEBUG("Received L2 update for symbol {}: price={}, qty={}, side={}, event_time={}, seq_num={}, flags={}",
230 // symbol->symbol_.view(), evt.price, evt.qty, evt.side, evt.event_time, evt.seq_num, evt.flags);
231
232 // Add to per-symbol priority queue
233 state.pending_events.push(std::move(evt));
234 }
235}
236
237void CoinbaseExchange::onMarketTradesSnapshot(WebSocketClient * /* client */, uint64_t seq_num, const std::vector<coinbase::MarketTrade> &snapshots)
238{
239 auto &pending_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES];
240 if (pending_subscriptions.empty() || snapshots.empty())
241 {
242 return;
243 }
244 Symbol *symbol = sym_mgr.getSymbol(snapshots[0].product_id, venue_);
245 if (!symbol || !pending_subscriptions.contains(symbol))
246 {
247 return;
248 }
249
250 // These prints happened before we were listening, so they only seed the
251 // history that serves the subscribe snapshot - they are never fed to the
252 // matching engine. Coinbase sends them newest first, so walk in reverse to
253 // store them chronologically.
254 for (auto i = static_cast<int32_t>(snapshots.size()) - 1; i >= 0; i--)
255 {
256 const auto &trade = snapshots[i];
257
258 // Keep the venue's own trade id, and keep the ids this exchange mints
259 // afterwards continuing the venue's sequence rather than colliding with it.
260 uint64_t trade_id = 0;
261 auto [_, ec] = std::from_chars(trade.trade_id.data(), trade.trade_id.data() + trade.trade_id.size(), trade_id);
262 if (ec != std::errc{})
263 {
264 trade_id = nextVenueTradeId();
265 }
266 else if (trade_id >= next_trade_id_)
267 {
268 next_trade_id_ = trade_id + 1;
269 }
270
271 symbol->recordTrade(MDTrade{
272 .trade_id = trade_id,
273 .event_time = trade.time,
274 .seq_num = seq_num,
275 .price = to_price_t(trade.price),
276 .qty = to_qty_t(trade.size),
277 // Never matched into the book, so whether a subscriber's book
278 // snapshot reflects this print depends on its timestamp.
280 .side = static_cast<Side>(trade.side)});
281 }
282
283 publishTradeSubscriptionResponse(symbol, coinbase::WebSocketChannel::MARKET_TRADES);
284 pending_subscriptions.erase(symbol);
285}
286
287void CoinbaseExchange::onMarketTrades(WebSocketClient * /* client */, uint64_t seq_num, const std::vector<coinbase::MarketTrade> &trades)
288{
289 // Coinbase sends market_trades newest-first, so this loop runs forward and the
290 // batch is dispatched back-to-front - see onLevel2Updates. trades.begin() is
291 // enqueued first and therefore dispatched last, so it carries the marker.
292 for (auto it = trades.begin(); it != trades.end(); ++it)
293 {
294 const auto &trade = *it;
295 auto *symbol = sym_mgr.getSymbol(trade.product_id, venue_);
296 if (!symbol) [[unlikely]]
297 {
298 continue;
299 }
300
301 // Get or create event state for this symbol
302 auto &state = symbol_event_state_[symbol];
303
304 Event evt;
305 evt.type = EventType::TRADE;
306 evt.event_time = trade.time;
307 evt.seq_num = seq_num;
308 evt.sequence_id = state.next_sequence_id++; // Internal counter
309 evt.received_time = utils::get_current_time_ns();
310 evt.price = to_price_t(trade.price);
311 evt.qty = to_qty_t(trade.size);
312 evt.side = static_cast<Side>(trade.side);
313 evt.flags = it == trades.begin() ? UpdateFlags::F_END_EVENT : UpdateFlags::F_NONE;
314
315 // Update last_event_time to track latest event_time seen
316 if (state.last_event_time < evt.event_time)
317 {
318 state.last_event_time = evt.event_time;
319 }
320
321 // Add to per-symbol priority queue
322 state.pending_events.push(std::move(evt));
323 }
324}
325
327{
328 LOG_WARN("CoinbaseExchange Market Data Gap detected");
329}
331{
332 LOG_WARN("CoinbaseExchange User Data Gap detected");
333}
335{
336 LOG_ERROR("Websocket {:p} onMarketDataError {}", (void *)client, std::move(err));
337}
338
340{
341 LOG_ERROR("Websocket {:p} onUserDataError {}", (void *)client, std::move(err));
342}
static SymbolManager & instance()
void onLevel2Snapshot(WebSocketClient *client, uint64_t seq_num, const coinbase::Level2UpdateBatch &snapshot) override
void onUserDataError(WebSocketClient *client, std::string &&err) override
void onLevel2Updates(WebSocketClient *client, uint64_t seq_num, const coinbase::Level2UpdateBatch &updates) override
void onMarketDataError(WebSocketClient *client, std::string &&err) override
void onUserDataConnected(WebSocketClient *client) override
void onMarketDataDisconnected(WebSocketClient *client) override
void onMarketDataConnected(WebSocketClient *client) override
void onUserDataDisconnected(WebSocketClient *client) override
void onUserDataGap(WebSocketClient *client) override
void onMarketDataGap(WebSocketClient *client) override
void onMarketTradesSnapshot(WebSocketClient *client, uint64_t seq_num, const std::vector< coinbase::MarketTrade > &snapshots) override
void onMarketTrades(WebSocketClient *client, uint64_t seq_num, const std::vector< coinbase::MarketTrade > &trades) override
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
uint64_t nextVenueTradeId() noexcept
Public trade ids, one independent sequence per venue.
Definition exchange.hpp:142
queue< uint8_t > md_queue_
Definition exchange.hpp:183
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 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
Helpers for a venue whose one config entry describes several independent exchange instances,...
Definition exchange.hpp:30
coinbase::WebSocketClient WebSocketClient
uint64_t nextOrderId() noexcept
Definition order.hpp:10
uint64_t get_current_time_ns()
Definition timestamp.hpp:93
constexpr price_t to_price_t(double price)
Scales a decimal into the fixed-point representation, rounding to the nearest tick rather than trunca...
Definition types.hpp:42
@ F_NOT_IN_BOOK
On an MDTrade: this print was never applied to the order book.
orderbook::Side to_book_side(Side side)
constexpr qty_t to_qty_t(double qty)
Definition types.hpp:50
void recordTrade(const MDTrade &trade)
Appends a trade to the tape history that serves the subscribe snapshot.
Definition symbol.hpp:169