1#include <slick/logger.hpp>
109void CoinbasePublisher::setup_routes(uWS::App &app) {
112 .compression = uWS::SHARED_COMPRESSOR,
113 .maxPayloadLength = 1 << 24,
115 .maxBackpressure = 1 << 25,
120 .open = [
this](
auto *ws) {
122 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
125 ws->getUserData()->seq_num = 0;
126 clients_.emplace(ws);
127 LOG_INFO(
"CoinbasePublisher WebSocket client connected");
130 .message = [
this](
auto *ws, std::string_view message, uWS::OpCode ) {
131 handle_message(ws, message);
134 .drain = [](
auto *) {
138 .ping = [](
auto *ws, std::string_view ) {
141 LOG_TRACE(
"CoinbasePublisher Received ping from client {:p}", (
void*)ws);
144 .pong = [
this](
auto *ws, std::string_view ) {
146 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
147 LOG_TRACE(
"CoinbasePublisher Received pong from client {:p}", (
void*)ws);
150 .close = [
this](
auto *ws,
int code, std::string_view message) {
151 handle_close(ws, code, message);
191void CoinbasePublisher::publish_market_data_update(MarketDataUpdate *update) {
192 switch(update->
type) {
196 publish_level_update(update);
199 publish_order_update(update);
202 publish_subscription_response(update);
205 publish_level_snapshot(update);
208 publish_trade_summary(update);
211 LOG_WARN(
"Received unknown or invalid market data update type: {}",
static_cast<int>(update->
type));
216void CoinbasePublisher::handle_message(wsT *ws, std::string_view message) {
218 json msg = json::parse(message);
221 if (msg.contains(
"type") && msg[
"type"] ==
"subscribe") {
223 auto *user_data = ws->getUserData();
225 if (!clients_.contains(ws)) {
226 user_data->seq_num = 0;
227 clients_.emplace(ws);
230 auto &channel = msg[
"channel"].get_ref<std::string&>();
232 const bool carries_products = channel ==
"level2" || channel ==
"market_trades" || channel ==
"ticker";
233 if (carries_products && (!msg.contains(
"product_ids") || !msg[
"product_ids"].is_array())) {
236 send_error(ws, std::format(
"channel `{}` requires product_ids", channel));
240 if (channel ==
"level2") {
241 for (
auto &prod : msg[
"product_ids"]) {
242 LOG_INFO(
"Client {:p} subscribe level2: {}", ws, prod.get<std::string_view>());
245 std::string symbol = prod.get<std::string>();
248 auto channel_index =
static_cast<uint8_t
>(coinbase::WebSocketChannel::LEVEL2);
249 request->md_subscription.channel = channel_index;
250 request->md_subscription.client = (
void*)ws;
252 auto& channel_map = subscription_info_[channel_index];
253 auto &subscriptions = channel_map[symbol];
254 subscriptions.emplace(ws);
255 user_data->subscription_info[channel_index].active_subscriptions.emplace(symbol);
256 user_data->subscription_info[channel_index].pending_subscriptions.emplace(symbol);
257 symbol_channel_client_[symbol].emplace(channel_index, ws);
260 else if (channel ==
"market_trades") {
261 for (
auto &prod : msg[
"product_ids"]) {
262 LOG_INFO(
"Client {:p} subscribe market_trades: {}", ws, prod.get<std::string_view>());
265 std::string symbol = prod.get<std::string>();
268 auto channel_index =
static_cast<uint8_t
>(coinbase::WebSocketChannel::MARKET_TRADES);
269 request->md_subscription.channel = channel_index;
270 request->md_subscription.client = (
void*)ws;
272 auto& channel_map = subscription_info_[channel_index];
273 auto &subscriptions = channel_map[symbol];
274 subscriptions.emplace(ws);
275 user_data->subscription_info[channel_index].active_subscriptions.emplace(symbol);
276 user_data->subscription_info[channel_index].pending_subscriptions.emplace(symbol);
277 symbol_channel_client_[symbol].emplace(channel_index, ws);
280 else if (channel ==
"ticker") {
281 for (
auto &prod : msg[
"product_ids"]) {
282 LOG_INFO(
"Client {:p} subscribe ticker: {}", ws, prod.get<std::string_view>());
285 std::string symbol = prod.get<std::string>();
288 auto channel_index =
static_cast<uint8_t
>(coinbase::WebSocketChannel::TICKER);
289 request->md_subscription.channel = channel_index;
290 request->md_subscription.client = (
void*)ws;
292 auto& channel_map = subscription_info_[channel_index];
293 auto &subscriptions = channel_map[symbol];
294 subscriptions.emplace(ws);
295 user_data->subscription_info[channel_index].active_subscriptions.emplace(symbol);
296 user_data->subscription_info[channel_index].pending_subscriptions.emplace(symbol);
297 symbol_channel_client_[symbol].emplace(channel_index, ws);
300 else if (channel ==
"heartbeats") {
301 user_data->subscribed_heartbeat =
true;
303 {
"channel",
"subscriptions"},
306 {
"sequence_num", user_data->seq_num++},
309 {
"heartbeats", {
"heartbeats"}}
313 ws->send(response.dump(), uWS::OpCode::TEXT);
318 {
"message", std::format(
"channel `{}` is not supported", channel)},
320 ws->send(response.dump(), uWS::OpCode::TEXT);
326 {
"message", std::format(
"type `{}` is not supported", msg.value<std::string>(
"type",
""))},
328 ws->send(response.dump(), uWS::OpCode::TEXT);
330 }
catch (
const json::parse_error& e) {
331 send_error(ws, std::string(
"Invalid JSON: ") + e.what());
336 auto now = std::chrono::steady_clock::now();
337 std::vector<wsT*> disconnected_clients;
340 for (
auto it = clients_.begin(); it != clients_.end();) {
342 auto* user_data = ws->getUserData();
345 auto time_since_pong = std::chrono::duration_cast<std::chrono::seconds>(
346 now - user_data->last_pong);
350 LOG_WARN(
"Client {:p} failed heartbeat check (last_pong: {}s ago), disconnecting",
351 ws, time_since_pong.count());
353 disconnected_clients.push_back(ws);
354 it = clients_.erase(it);
358 if (user_data->subscribed_heartbeat) {
362 {
"heartbeat_counter", user_data->heartbeat_count++}
365 {
"channel",
"heartbeats"},
368 {
"sequence_num", user_data->seq_num++},
371 ws->send(ping_msg.dump(), uWS::OpCode::TEXT);
375 ws->send(
"", uWS::OpCode::PING);
376 LOG_TRACE(
"Sent heartbeat to client {:p}", ws);
381 if (!disconnected_clients.empty()) {
382 LOG_INFO(
"Disconnected {} stale clients", disconnected_clients.size());
386void CoinbasePublisher::handle_close(wsT *ws,
int code, std::string_view message) {
387 LOG_INFO(
"Client {:p} disconnected: code={}, msg={}", ws, code, message);
392void CoinbasePublisher::unsubscribe_md(wsT *ws) {
393 for (
auto channel = 0; channel < static_cast<int>(coinbase::WebSocketChannel::_CHANNEL_COUNT_); ++channel) {
394 auto *user_data = ws->getUserData();
395 for (
const auto &symbol : user_data->subscription_info[channel].active_subscriptions) {
396 LOG_INFO(
"Client {:p} unsubscribe channel {}: {}", ws, coinbase::to_string(
static_cast<coinbase::WebSocketChannel
>(channel)), symbol);
401 request->md_subscription.channel =
static_cast<uint8_t
>(channel);
402 request->md_subscription.client = (
void*)ws;
405 auto it = symbol_channel_client_.find(symbol);
406 if (it != symbol_channel_client_.end()) {
407 auto range = it->second.equal_range(
static_cast<uint8_t
>(channel));
408 for (
auto itr = range.first; itr != range.second; ) {
409 if (itr->second == ws) {
410 itr = it->second.erase(itr);
416 if (it->second.empty()) {
417 symbol_channel_client_.erase(it);
420 subscription_info_[channel][symbol].erase(ws);
422 user_data->subscription_info[channel].active_subscriptions.clear();
423 user_data->subscription_info[channel].pending_subscriptions.clear();
424 user_data->subscription_info[channel].received_subscriptions.clear();
428void CoinbasePublisher::send_error(wsT *ws,
const std::string& error_msg) {
431 {
"message", error_msg}
433 ws->send(error.dump(), uWS::OpCode::TEXT);
434 LOG_ERROR(
"WebSocket error: {}", error_msg);
437void CoinbasePublisher::publish_subscription_response(MarketDataUpdate *update) {
438 auto *response =
reinterpret_cast<MDSubscriptionResponse*
>(update->
data);
439 auto &channel_sub = subscription_info_[response->channel];
440 auto it = channel_sub.find(update->
symbol);
441 if (it != channel_sub.end()) {
442 if (it->second.empty()) {
451 auto message = std::format(
"Subscription to {} rejected: {}",
454 for (
auto *ws : it->second) {
455 send_error(ws, message);
461 auto channel =
static_cast<coinbase::WebSocketChannel
>(response->channel);
463 if (channel == coinbase::WebSocketChannel::LEVEL2) {
465 auto *snapshot =
reinterpret_cast<BookSnapshot*
>(response->data);
466 auto *levels =
reinterpret_cast<MDLevel*
>(snapshot->levels);
469 json::array_t updates;
471 auto total_levels = snapshot->num_bid + snapshot->num_ask;
474 for (; i < snapshot->num_bid; ++i) {
482 for (; i < total_levels; ++i) {
492 {
"channel",
"l2_data"},
496 {
"type",
"snapshot"},
497 {
"product_id", update->
symbol},
502 else if (channel == coinbase::WebSocketChannel::MARKET_TRADES) {
503 auto *trade_response =
reinterpret_cast<MDTradeSnapshotResponse*
>(response->data);
506 trade_response->num_snapshot,
true);
507 if (trade_response->num_update) {
512 trade_response->trades + trade_response->num_snapshot,
513 trade_response->num_update,
false);
516 else if (channel == coinbase::WebSocketChannel::TICKER) {
519 {
"channel",
"ticker"},
523 {
"type",
"snapshot"},
524 {
"tickers", json::array()}
529 LOG_WARN(
"Subscription response for unsupported channel: {}", coinbase::to_string(channel));
535 SequencedMessage snapshot_payload(snapshot_msg);
536 std::optional<SequencedMessage> update_payload;
537 if (!update_msg.is_null()) {
538 update_payload.emplace(update_msg);
541 for (
const auto &ws : it->second) {
542 auto *user_data = ws->getUserData();
543 auto &subscription_info = user_data->subscription_info[response->channel];
544 auto it_sym = subscription_info.pending_subscriptions.find(update->
symbol);
545 if (it_sym != subscription_info.pending_subscriptions.end()) {
546 subscription_info.pending_subscriptions.erase(it_sym);
547 subscription_info.received_subscriptions.emplace_back(update->
symbol);
549 ws->send(snapshot_payload.render(user_data->seq_num++), uWS::OpCode::TEXT);
551 LOG_DEBUG(
"CoinbasePublisher send {} snapshot", update->
symbol);
553 if (update_payload) {
554 ws->send(update_payload->render(user_data->seq_num++), uWS::OpCode::TEXT);
557 if (subscription_info.pending_subscriptions.empty()) {
559 json subscription_msg = {
560 {
"channel",
"subscriptions"},
563 {
"sequence_num", user_data->seq_num++},
566 {coinbase::to_string(channel), subscription_info.received_subscriptions}
571 for (
auto i = 0u; i < coinbase::WebSocketChannel::_CHANNEL_COUNT_; ++i) {
572 if (i == response->channel) {
575 auto &other_sub_info = user_data->subscription_info[i];
576 if (!other_sub_info.received_subscriptions.empty()) {
577 subscription_msg[
"events"][0][
"subscriptions"][coinbase::to_string(
static_cast<coinbase::WebSocketChannel
>(i))] = other_sub_info.received_subscriptions;
580 ws->send(subscription_msg.dump(), uWS::OpCode::TEXT);
587void CoinbasePublisher::publish_level_snapshot(MarketDataUpdate *update) {
588 auto *snapshot =
reinterpret_cast<BookSnapshot*
>(update->
data);
589 auto it_range = symbol_channel_client_.find(update->
symbol);
590 if (it_range != symbol_channel_client_.end()) {
591 auto range = it_range->second.equal_range(
static_cast<uint8_t
>(coinbase::WebSocketChannel::LEVEL2));
592 if (range.first == range.second) {
595 json::array_t updates;
597 auto total_levels = snapshot->num_bid + snapshot->num_ask;
600 for (; i < snapshot->num_bid; ++i) {
608 for (; i < total_levels; ++i) {
617 json snapshot_msg = {
618 {
"channel",
"l2_data"},
622 {
"type",
"snapshot"},
623 {
"product_id", update->
symbol},
628 SequencedMessage snapshot_payload(snapshot_msg);
629 for (
auto it = range.first; it != range.second; ++it) {
630 auto *ws = it->second;
631 auto *user_data = ws->getUserData();
632 ws->send(snapshot_payload.render(user_data->seq_num++), uWS::OpCode::TEXT);
637void CoinbasePublisher::publish_level_update(MarketDataUpdate *update) {
638 auto *level_update =
reinterpret_cast<MDLevelUpdate*
>(update->
data);
639 auto it_range = symbol_channel_client_.find(update->
symbol);
640 if (it_range != symbol_channel_client_.end()) {
641 auto range = it_range->second.equal_range(
static_cast<uint8_t
>(coinbase::WebSocketChannel::LEVEL2));
642 if (range.first == range.second) {
646 json::array_t updates;
647 for (
auto i = 0u; i < level_update->num_level_update; ++i) {
648 auto &level = level_update->levels[i];
658 {
"side", level.side ?
"offer" :
"bid"},
666 {
"channel",
"l2_data"},
671 {
"product_id", update->
symbol},
676 SequencedMessage update_payload(update_msg);
677 for (
auto it = range.first; it != range.second; ++it) {
678 auto *ws = it->second;
679 auto *user_data = ws->getUserData();
680 ws->send(update_payload.render(user_data->seq_num++), uWS::OpCode::TEXT);
685void CoinbasePublisher::publish_trade_summary(MarketDataUpdate *update) {
686 auto it_range = symbol_channel_client_.find(update->
symbol);
687 if (it_range == symbol_channel_client_.end()) {
690 auto range = it_range->second.equal_range(
static_cast<uint8_t
>(coinbase::WebSocketChannel::MARKET_TRADES));
691 if (range.first == range.second) {
695 auto *summary =
reinterpret_cast<TradeSummary*
>(update->
data);
698 SequencedMessage trade_payload(trade_msg);
699 for (
auto it = range.first; it != range.second; ++it) {
700 auto *ws = it->second;
701 auto *user_data = ws->getUserData();
702 ws->send(trade_payload.render(user_data->seq_num++), uWS::OpCode::TEXT);
706void CoinbasePublisher::publish_order_update(MarketDataUpdate *update) {
707 auto it_range = symbol_channel_client_.find(update->
symbol);
708 if (it_range != symbol_channel_client_.end()) {
709 auto range = it_range->second.equal_range(
static_cast<uint8_t
>(coinbase::WebSocketChannel::USER));
710 if (range.first == range.second) {
713 SLICK_ASSERT(
false &&
"User data shouldn't subscribed in market data publisher");
static SymbolManager & instance()
CoinbasePublisher(const json &config, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue)
slick::queue< Request > & request_queue_
virtual void check_heartbeats()=0
std::chrono::seconds pong_timeout_
WebsocketMarketDataPublisher(Venue venue, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue, uint32_t port)
json encode_market_trade(const char *product_id, const TradeSummary &summary)
One executed trade, as a "type":"update" event.
json encode_market_trades(const char *product_id, const char *event_type, const MDTrade *trades, uint32_t num_trades, bool newest_first)
A run of trades as a single event of the given type.
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
bool copy_wire_field(char(&dst)[N], std::string_view src) noexcept
Copies a name into a fixed-width wire field.
std::string format_heatbeat_timestamp()
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
constexpr const char * to_string(FeedState state) noexcept
@ TRADE_SUMMARY
One executed trade.
std::string to_price_string(price_t price)
std::string to_qty_string(qty_t qty)
static uint_fast64_t heartbeat_count