1#include <slick/logger.hpp>
5#include <coinbase/websocket.hpp>
28 auto &og_config = config[
"order_gateway"];
29 if (!og_config.contains(
"rest"))
31 throw std::runtime_error(
"COINBASE Exchange order_gateway missing rest config");
35 if (og_config.contains(
"ws"))
41 if (config.contains(
"md_feeds"))
43 for (
const auto &md_feed_config : config[
"md_feeds"])
45 std::string type = md_feed_config.value(
"type",
"");
46 if (!md_feed_config.value(
"enabled",
true))
48 LOG_INFO(
"Coinbase skipping disabled md_feed type {}", type);
51 if (type ==
"coinbase_live_ws")
53 use_live_feed_ =
true;
63 : std::vector<FeedInfo>{};
78Symbol *CoinbaseExchange::addSymbol(std::string_view product_id)
80 assert(!sym_mgr.getSymbol(product_id,
venue_));
91 std::string sym = request.
symbol;
92 auto *symbol = sym_mgr.getSymbol(sym,
venue_);
95 symbol = addSymbol(sym);
98 switch (
static_cast<coinbase::WebSocketChannel
>(msg.channel))
100 case coinbase::WebSocketChannel::LEVEL2:
102 pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2].emplace(symbol);
105 case coinbase::WebSocketChannel::MARKET_TRADES:
107 pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES].emplace(symbol);
110 case coinbase::WebSocketChannel::HEARTBEATS:
112 case coinbase::WebSocketChannel::TICKER:
118 LOG_WARN(
"Unsupported channel {} for symbol {}",
static_cast<int>(msg.channel), sym);
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_));
124 map_symbol_feed_.emplace(sym, feed);
129 switch (
static_cast<coinbase::WebSocketChannel
>(msg.channel))
131 case coinbase::WebSocketChannel::LEVEL2:
133 symbol->order_book_->populateL2SubscriptionResponse(
md_queue_, msg.channel);
136 case coinbase::WebSocketChannel::MARKET_TRADES:
138 populateMDTradesResponse(symbol);
141 case coinbase::WebSocketChannel::HEARTBEATS:
143 case coinbase::WebSocketChannel::TICKER:
148 LOG_WARN(
"Unsupported channel {} for symbol {}",
static_cast<int>(msg.channel), sym);
152 symbol->num_subscriptions_.fetch_add(1, std::memory_order_relaxed);
155 symbol->num_subscriptions_.fetch_add(1, std::memory_order_relaxed);
156 switch (
static_cast<coinbase::WebSocketChannel
>(msg.channel))
158 case coinbase::WebSocketChannel::LEVEL2:
160 auto &pending_l2_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::LEVEL2];
161 if (pending_l2_subscriptions.find(symbol) == pending_l2_subscriptions.end())
164 symbol->order_book_->populateL2SubscriptionResponse(
md_queue_, msg.channel);
172 case coinbase::WebSocketChannel::MARKET_TRADES:
174 auto &pending_trade_subscriptions = pending_md_subscription_[coinbase::WebSocketChannel::MARKET_TRADES];
175 if (pending_trade_subscriptions.find(symbol) == pending_trade_subscriptions.end())
178 populateMDTradesResponse(symbol);
186 case coinbase::WebSocketChannel::TICKER:
199 std::string sym = request.
symbol;
200 auto *symbol = sym_mgr.getSymbol(sym,
venue_);
205 if (symbol->num_subscriptions_.fetch_sub(1, std::memory_order_relaxed) == 1)
207 auto it_feed = map_symbol_feed_.find(sym);
208 if (it_feed != map_symbol_feed_.end())
210 auto feed = it_feed->second;
213 map_symbol_feed_.erase(it_feed);
218uint64_t CoinbaseExchange::nextBookSeqNum(
Symbol *symbol, SymbolEventState &state)
224 const auto book_seq = symbol->
order_book_->getLastSeqNum();
225 if (state.next_book_seq_num < book_seq)
227 state.next_book_seq_num = book_seq;
229 return ++state.next_book_seq_num;
237 for (
auto &[symbol, state] : symbol_event_state_)
239 auto &pending_events = state.pending_events;
242 while (!pending_events.empty())
244 const auto &top_event = pending_events.top();
250 bool safe_by_time_gap = (state.last_event_time > 0) &&
254 uint64_t time_in_queue = now - top_event.received_time;
256 ready = safe_by_time_gap || safe_by_timeout;
263 Event
event = top_event;
264 pending_events.pop();
270 dispatchEvent(symbol, event, state, nextBookSeqNum(symbol, state));
280 state.last_sequence_id =
event.sequence_id;
281 state.last_seq_num =
event.seq_num;
292void CoinbaseExchange::dispatchEvent(
Symbol *symbol,
const Event &event, SymbolEventState &state,
293 uint64_t book_seq_num)
298 if (event.event_time < symbol->
order_book_->lastUpdateTime())
300 LOG_WARN(
"[CoinbaseExchange] Skipping stale level update for symbol {}: seq_num={}, event_time={}({}), last_update_time={}({}) last_seq_num={}",
322 auto [level, index] = symbol->
order_book_->getLevel(book_side, event.price);
327 qty_t qty =
event.qty;
329 auto trade_summaries = symbol->
matching_engine_->
match(event.side, order_id, event.price, qty, *book.get(), event.event_time, book_seq_num);
336 if (!trade_summaries.empty())
338 for (
const auto &summary : trade_summaries)
353 symbol->
order_book_->setLastUpdate(event.event_time, event.seq_num);
355 if (!state.last_published_level_seq_num) [[unlikely]]
357 state.last_published_level_seq_num =
event.seq_num;
360 if (!state.level_update_buffer_.empty() &&
361 event.seq_num != state.last_published_level_seq_num)
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();
370 auto [new_level, new_index] = symbol->
order_book_->getLevel(book_side, event.price);
371 if (!level && new_level)
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;
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});
418 qty_t qty =
event.qty;
420 event.side, order_id, event.price, qty, book, event.event_time, book_seq_num);
428 book.addBookOrder(order_id, book_side, event.price, qty, event.event_time, book_seq_num,
432 for (
const auto &summary : trade_summaries)
437 summary.phantom_qty, event.event_time);
445void CoinbaseExchange::populateMDTradesResponse(
Symbol *symbol)
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_
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.
std::shared_ptr< md_feed::MDFeed > md_feed_
void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel)
Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history,...
void flushMarketDataCaches(Symbol *symbol)
Publish and clear whatever market data the book produced while handling a request.
queue< uint8_t > md_queue_
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
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,...
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
Feeds owned by the exchange and managed by base start()/stop().
Exchange(Venue venue, const nlohmann::json &config)
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
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...
void publishLevelUpdate(const symbol_name_t &symbol, const std::vector< MDLevel > &level_updates)
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
queue< OrderResponse > response_queue_
void publishMdSubscriptionResponse(const symbol_name_t &symbol, uint8_t channel)
Publishes an accepted subscription response without a snapshot payload.
std::string_view view() const noexcept
Helpers for a venue whose one config entry describes several independent exchange instances,...
@ LIVE
The venue, as it happens.
constexpr uint64_t ONE_SECOND_NS
uint64_t nextOrderId() noexcept
uint64_t get_current_time_ns()
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
constexpr Side opposite_side()
orderbook::Side to_book_side(Side side)
MDSubscriptionMessage md_subscription
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,...
symbol_name_t symbol_
Stored at wire width so publishing can copy the whole field without reading past the end of a shorter...
engine::MatchingEngine * matching_engine_
std::shared_ptr< OrderBook > order_book_