Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_publisher.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
4#include <optional>
8#include <utils/timestamp.hpp>
9
10using namespace slick::sim::md_publisher;
11using namespace slick::sim;
12using namespace slick::sim::utils;
13
14namespace {
15 auto &symbol_mgr = SymbolManager::instance();
16}
17
18uint_fast64_t PerSocketData::heartbeat_count = 0;
19
20CoinbasePublisher::CoinbasePublisher(const nlohmann::json &config, slick::queue<Request> &request_queue, slick::queue<uint8_t> &market_data_queue)
21 : WebsocketMarketDataPublisher(Venue::COINBASE, request_queue, market_data_queue, config.value("port", 5000))
22{
23}
24
25// void CoinbasePublisher::start() {
26// running_.store(true, std::memory_order_release);
27// // Start WebSocket server thread (handles everything in event loop)
28// ws_thread_ = std::thread([this]() {
29// auto app = uWS::App();
30
31// app.ws<PerSocketData>("/*", {
32// /* WebSocket settings */
33// .compression = uWS::SHARED_COMPRESSOR,
34// .maxPayloadLength = 2 << 24,
35// .idleTimeout = 120,
36// .maxBackpressure = 2 << 25,
37
38// /* WebSocket handlers */
39// .upgrade = nullptr,
40
41// .open = [this](auto *ws) {
42// // Initialize connection timestamp
43// ws->getUserData()->last_pong = std::chrono::steady_clock::now();
44// clients_.emplace(ws);
45// LOG_INFO("CoinbasePublisher WebSocket client connected");
46// },
47
48// .message = [this](auto *ws, std::string_view message, uWS::OpCode /* opCode */) {
49// handleMessage(ws, message);
50// },
51
52// .drain = [](auto */* ws */) {
53// // Check backpressure
54// },
55
56// .ping = [](auto *ws, std::string_view /* message */) {
57// // Automatically respond to client ping with pong
58// // uWebSockets handles this automatically, but we log it
59// LOG_TRACE("CoinbasePublisher Received ping from client {:p}", (void*)ws);
60// },
61
62// .pong = [this](auto *ws, std::string_view /* message */) {
63// // Client responded to our ping
64// ws->getUserData()->last_pong = std::chrono::steady_clock::now();
65// LOG_TRACE("CoinbasePublisher Received pong from client {:p}", (void*)ws);
66// },
67
68// .close = [this](auto *ws, int code, std::string_view message) {
69// handleClose(ws, code, message);
70// }
71// })
72// .listen(port_, [this, &app](auto *listen_socket) {
73// listen_socket_ = listen_socket;
74// if (listen_socket) {
75// LOG_INFO("CoinbasePublisher started on port {}", port_);
76
77// // Get the event loop
78// loop_ = uWS::Loop::get();
79
80// // Create heartbeat timer in the event loop
81// // Use defer() to create timer with proper lambda capture
82// loop_->defer([this]() {
83// heartbeat_timer_ = us_create_timer((struct us_loop_t*)loop_, 0, 0);
84
85// // Store 'this' pointer in timer extension data
86// *((CoinbasePublisher**)us_timer_ext(heartbeat_timer_)) = this;
87
88// // Set timer callback that retrieves 'this' from extension data
89// us_timer_set(heartbeat_timer_, [](struct us_timer_t *timer) {
90// // Dereference the pointer stored in extension data
91// auto* self = *((CoinbasePublisher**)us_timer_ext(timer));
92// self->checkHeartbeats();
93// }, ping_interval_ms_, ping_interval_ms_);
94// });
95
96// LOG_INFO("CoinbasePublisher Event loop configured (heartbeat: {}ms)", ping_interval_ms_);
97
98// // Start continuous response processing
99// schedulePublishProcessing();
100
101// } else {
102// LOG_ERROR("CoinbasePublisher Failed to listen on port {}", port_);
103// }
104// })
105// .run();
106// });
107// }
108
109void CoinbasePublisher::setup_routes(uWS::App &app) {
110 app.ws<PerSocketData>("/*", {
111 /* WebSocket settings */
112 .compression = uWS::SHARED_COMPRESSOR,
113 .maxPayloadLength = 1 << 24,
114 .idleTimeout = 120,
115 .maxBackpressure = 1 << 25,
116
117 /* WebSocket handlers */
118 .upgrade = nullptr,
119
120 .open = [this](auto *ws) {
121 // Initialize connection timestamp
122 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
123 // Start each socket at sequence_num zero. An uninitialized counter gave the first
124 // market-data message an arbitrary number, causing continuity checks to report a gap.
125 ws->getUserData()->seq_num = 0;
126 clients_.emplace(ws);
127 LOG_INFO("CoinbasePublisher WebSocket client connected");
128 },
129
130 .message = [this](auto *ws, std::string_view message, uWS::OpCode /* opCode */) {
131 handle_message(ws, message);
132 },
133
134 .drain = [](auto */* ws */) {
135 // Check backpressure
136 },
137
138 .ping = [](auto *ws, std::string_view /* message */) {
139 // Automatically respond to client ping with pong
140 // uWebSockets handles this automatically, but we log it
141 LOG_TRACE("CoinbasePublisher Received ping from client {:p}", (void*)ws);
142 },
143
144 .pong = [this](auto *ws, std::string_view /* message */) {
145 // Client responded to our ping
146 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
147 LOG_TRACE("CoinbasePublisher Received pong from client {:p}", (void*)ws);
148 },
149
150 .close = [this](auto *ws, int code, std::string_view message) {
151 handle_close(ws, code, message);
152 }
153 });
154}
155
156// void CoinbasePublisher::stop() {
157// running_.store(false, std::memory_order_release);
158
159// // Close heartbeat timer
160// if (heartbeat_timer_) {
161// us_timer_close(heartbeat_timer_);
162// heartbeat_timer_ = nullptr;
163// }
164
165// if (listen_socket_ && loop_) {
166// // Closing the listen socket must happen on the loop's own thread;
167// // doing it cross-thread races with the loop's poll handles.
168// loop_->defer([this]() {
169// if (listen_socket_) {
170// us_listen_socket_close(0, listen_socket_);
171// listen_socket_ = nullptr;
172// }
173// });
174// }
175
176// if (ws_thread_.joinable()) {
177// ws_thread_.join();
178// }
179// }
180
181// void CoinbasePublisher::schedulePublishProcessing() {
182// if (!running_.load(std::memory_order_acquire) || !loop_) {
183// return;
184// }
185
186// loop_->defer([this]() {
187// publishMarketDataUpdate();
188// });
189// }
190
191void CoinbasePublisher::publish_market_data_update(MarketDataUpdate *update) {
192 switch(update->type) {
194 break;
196 publish_level_update(update);
197 break;
199 publish_order_update(update);
200 break;
202 publish_subscription_response(update);
203 break;
205 publish_level_snapshot(update);
206 break;
208 publish_trade_summary(update);
209 break;
210 default:
211 LOG_WARN("Received unknown or invalid market data update type: {}", static_cast<int>(update->type));
212 break;
213 }
214}
215
216void CoinbasePublisher::handle_message(wsT *ws, std::string_view message) {
217 try {
218 json msg = json::parse(message);
219
220 // Check if this is a subscription message
221 if (msg.contains("type") && msg["type"] == "subscribe") {
222
223 auto *user_data = ws->getUserData();
224
225 if (!clients_.contains(ws)) {
226 user_data->seq_num = 0;
227 clients_.emplace(ws);
228 }
229
230 auto &channel = msg["channel"].get_ref<std::string&>();
231
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())) {
234 // Check product_ids before indexing msg["product_ids"]. An omitted field otherwise
235 // throws out of the uWS subscribe callback.
236 send_error(ws, std::format("channel `{}` requires product_ids", channel));
237 return;
238 }
239
240 if (channel == "level2") {
241 for (auto &prod : msg["product_ids"]) {
242 LOG_INFO("Client {:p} subscribe level2: {}", ws, prod.get<std::string_view>());
243 auto index = request_queue_.reserve();
244 auto *request = request_queue_[index];
245 std::string symbol = prod.get<std::string>();
246 utils::copy_wire_field(request->symbol, symbol);
247 request->msg_type = MessageType::MD_SUBSCRIPTION;
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;
251 request_queue_.publish(index);
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);
258 }
259 }
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>());
263 auto index = request_queue_.reserve();
264 auto *request = request_queue_[index];
265 std::string symbol = prod.get<std::string>();
266 utils::copy_wire_field(request->symbol, symbol);
267 request->msg_type = MessageType::MD_SUBSCRIPTION;
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;
271 request_queue_.publish(index);
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);
278 }
279 }
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>());
283 auto index = request_queue_.reserve();
284 auto *request = request_queue_[index];
285 std::string symbol = prod.get<std::string>();
286 utils::copy_wire_field(request->symbol, symbol);
287 request->msg_type = MessageType::MD_SUBSCRIPTION;
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;
291 request_queue_.publish(index);
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);
298 }
299 }
300 else if (channel == "heartbeats") {
301 user_data->subscribed_heartbeat = true;
302 json response = {
303 {"channel", "subscriptions"},
304 {"client_id", ""},
305 {"timestamp", format_timestamp_iso8601(9)},
306 {"sequence_num", user_data->seq_num++},
307 {"events", {{
308 {"subscriptions", {
309 {"heartbeats", {"heartbeats"}}
310 }}
311 }}}
312 };
313 ws->send(response.dump(), uWS::OpCode::TEXT);
314 }
315 else {
316 json response = {
317 {"type", "error"},
318 {"message", std::format("channel `{}` is not supported", channel)},
319 };
320 ws->send(response.dump(), uWS::OpCode::TEXT);
321 }
322 }
323 else {
324 json response = {
325 {"type", "error"},
326 {"message", std::format("type `{}` is not supported", msg.value<std::string>("type", ""))},
327 };
328 ws->send(response.dump(), uWS::OpCode::TEXT);
329 }
330 } catch (const json::parse_error& e) {
331 send_error(ws, std::string("Invalid JSON: ") + e.what());
332 }
333}
334
336 auto now = std::chrono::steady_clock::now();
337 std::vector<wsT*> disconnected_clients;
338
339 // No lock needed - single threaded event loop
340 for (auto it = clients_.begin(); it != clients_.end();) {
341 auto* ws = *it;
342 auto* user_data = ws->getUserData();
343
344 // Check if client has responded to pings
345 auto time_since_pong = std::chrono::duration_cast<std::chrono::seconds>(
346 now - user_data->last_pong);
347
348 if (time_since_pong > pong_timeout_) {
349 // Client hasn't responded to pings, close connection
350 LOG_WARN("Client {:p} failed heartbeat check (last_pong: {}s ago), disconnecting",
351 ws, time_since_pong.count());
352
353 disconnected_clients.push_back(ws);
354 it = clients_.erase(it);
355 ws->close(); // Close the connection
356 } else {
357 // Send ping to client (only if authenticated)
358 if (user_data->subscribed_heartbeat) {
359 // Send a text-based ping message (Coinbase style)
360 json event = {
361 {"current_time", utils::format_heatbeat_timestamp()},
362 {"heartbeat_counter", user_data->heartbeat_count++}
363 };
364 json ping_msg = {
365 {"channel", "heartbeats"},
366 {"client_id", ""},
367 {"timestamp", utils::format_timestamp_iso8601(9)},
368 {"sequence_num", user_data->seq_num++},
369 {"events", {event}}
370 };
371 ws->send(ping_msg.dump(), uWS::OpCode::TEXT);
372
373 }
374 // Also send protocol-level ping
375 ws->send("", uWS::OpCode::PING);
376 LOG_TRACE("Sent heartbeat to client {:p}", ws);
377 ++it;
378 }
379 }
380
381 if (!disconnected_clients.empty()) {
382 LOG_INFO("Disconnected {} stale clients", disconnected_clients.size());
383 }
384}
385
386void CoinbasePublisher::handle_close(wsT *ws, int code, std::string_view message) {
387 LOG_INFO("Client {:p} disconnected: code={}, msg={}", ws, code, message);
388 unsubscribe_md(ws);
389 clients_.erase(ws);
390}
391
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);
397 auto index = request_queue_.reserve();
398 auto *request = request_queue_[index];
399 utils::copy_wire_field(request->symbol, symbol);
400 request->msg_type = MessageType::MD_UNSUBSCRIPTION;
401 request->md_subscription.channel = static_cast<uint8_t>(channel);
402 request->md_subscription.client = (void*)ws;
403 request_queue_.publish(index);
404
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);
411 break;
412 } else {
413 ++itr;
414 }
415 }
416 if (it->second.empty()) {
417 symbol_channel_client_.erase(it);
418 }
419 }
420 subscription_info_[channel][symbol].erase(ws);
421 }
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();
425 }
426}
427
428void CoinbasePublisher::send_error(wsT *ws, const std::string& error_msg) {
429 json error = {
430 {"type", "error"},
431 {"message", error_msg}
432 };
433 ws->send(error.dump(), uWS::OpCode::TEXT);
434 LOG_ERROR("WebSocket error: {}", error_msg);
435}
436
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()) {
443 return;
444 }
445
446 // A reject reserves room for the response header and nothing else, so the
447 // BookSnapshot read below would run off the end of the frame and then
448 // iterate however many levels the leftover bytes happened to describe.
449 // Tell the subscribers why instead.
450 if (response->reject_reason != MDSubscriptionRejectReason::NONE) {
451 auto message = std::format("Subscription to {} rejected: {}",
452 update->symbol, to_string(response->reject_reason));
453 LOG_WARN(message);
454 for (auto *ws : it->second) {
455 send_error(ws, message);
456 }
457 return;
458 }
459 json snapshot_msg;
460 json update_msg; // trades newer than the book snapshot, if any
461 auto channel = static_cast<coinbase::WebSocketChannel>(response->channel);
462 // Send coinbase snapshot based on channel type
463 if (channel == coinbase::WebSocketChannel::LEVEL2) {
464 // Extract book snapshot data
465 auto *snapshot = reinterpret_cast<BookSnapshot*>(response->data);
466 auto *levels = reinterpret_cast<MDLevel*>(snapshot->levels);
467
468 // Build bids and asks arrays
469 json::array_t updates;
470
471 auto total_levels = snapshot->num_bid + snapshot->num_ask;
472 uint32_t i = 0;
473
474 for (; i < snapshot->num_bid; ++i) {
475 updates.push_back({
476 {"side", "bid"},
477 {"price_level", to_price_string(levels[i].price)},
478 {"new_quantity", to_qty_string(levels[i].qty)}
479 });
480 }
481
482 for (; i < total_levels; ++i) {
483 updates.push_back({
484 {"side", "offer"},
485 {"price_level", to_price_string(levels[i].price)},
486 {"new_quantity", to_qty_string(levels[i].qty)}
487 });
488 }
489
490 // Create level2 snapshot message
491 snapshot_msg = {
492 {"channel", "l2_data"},
493 {"client_id", ""},
494 {"timestamp", format_timestamp_iso8601(9)},
495 {"events", {{
496 {"type", "snapshot"},
497 {"product_id", update->symbol},
498 {"updates", updates}
499 }}}
500 };
501 }
502 else if (channel == coinbase::WebSocketChannel::MARKET_TRADES) {
503 auto *trade_response = reinterpret_cast<MDTradeSnapshotResponse*>(response->data);
504 // Coinbase orders snapshot trades newest first.
505 snapshot_msg = encode_market_trades(update->symbol, "snapshot", trade_response->trades,
506 trade_response->num_snapshot, true);
507 if (trade_response->num_update) {
508 // These are newer than the book snapshot this subscriber gets, so
509 // they are not settled history — deliver them as a normal update,
510 // chronologically, right after the snapshot.
511 update_msg = encode_market_trades(update->symbol, "update",
512 trade_response->trades + trade_response->num_snapshot,
513 trade_response->num_update, false);
514 }
515 }
516 else if (channel == coinbase::WebSocketChannel::TICKER) {
517 // Send ticker snapshot (would need actual ticker data)
518 snapshot_msg = {
519 {"channel", "ticker"},
520 {"client_id", ""},
521 {"timestamp", format_timestamp_iso8601(9)},
522 {"events", {{
523 {"type", "snapshot"},
524 {"tickers", json::array()}
525 }}}
526 };
527 }
528 else {
529 LOG_WARN("Subscription response for unsupported channel: {}", coinbase::to_string(channel));
530 return;
531 }
532
533 // Serialised before the loop: the book snapshot is the largest message this
534 // publisher sends, and several sockets can be waiting on the same one.
535 SequencedMessage snapshot_payload(snapshot_msg);
536 std::optional<SequencedMessage> update_payload;
537 if (!update_msg.is_null()) {
538 update_payload.emplace(update_msg);
539 }
540
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);
548
549 ws->send(snapshot_payload.render(user_data->seq_num++), uWS::OpCode::TEXT);
550
551 LOG_DEBUG("CoinbasePublisher send {} snapshot", update->symbol);
552
553 if (update_payload) {
554 ws->send(update_payload->render(user_data->seq_num++), uWS::OpCode::TEXT);
555 }
556
557 if (subscription_info.pending_subscriptions.empty()) {
558 // Send subscription confirmation
559 json subscription_msg = {
560 {"channel", "subscriptions"},
561 {"client_id", ""},
562 {"timestamp", format_timestamp_iso8601(9)},
563 {"sequence_num", user_data->seq_num++},
564 {"events", {{
565 {"subscriptions", {
566 {coinbase::to_string(channel), subscription_info.received_subscriptions}
567 }}
568 }}}
569 };
570
571 for (auto i = 0u; i < coinbase::WebSocketChannel::_CHANNEL_COUNT_; ++i) {
572 if (i == response->channel) {
573 continue;
574 }
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;
578 }
579 }
580 ws->send(subscription_msg.dump(), uWS::OpCode::TEXT);
581 }
582 }
583 }
584 }
585}
586
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) {
593 return;
594 }
595 json::array_t updates;
596
597 auto total_levels = snapshot->num_bid + snapshot->num_ask;
598 uint32_t i = 0;
599
600 for (; i < snapshot->num_bid; ++i) {
601 updates.push_back({
602 {"side", "bid"},
603 {"price_level", to_price_string(snapshot->levels[i].price)},
604 {"new_quantity", to_qty_string(snapshot->levels[i].qty)}
605 });
606 }
607
608 for (; i < total_levels; ++i) {
609 updates.push_back({
610 {"side", "offer"},
611 {"price_level", to_price_string(snapshot->levels[i].price)},
612 {"new_quantity", to_qty_string(snapshot->levels[i].qty)}
613 });
614 }
615
616 // Create level2 snapshot message
617 json snapshot_msg = {
618 {"channel", "l2_data"},
619 {"client_id", ""},
620 {"timestamp", format_timestamp_iso8601(9)},
621 {"events", {{
622 {"type", "snapshot"},
623 {"product_id", update->symbol},
624 {"updates", updates}
625 }}}
626 };
627
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);
633 }
634 }
635}
636
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) {
643 return;
644 }
645 // Build level update message
646 json::array_t updates;
647 for (auto i = 0u; i < level_update->num_level_update; ++i) {
648 auto &level = level_update->levels[i];
649 // LOG_DEBUG("Level Update: {} {} @ {} size={} seq_num={} time={}({})",
650 // update->symbol,
651 // level.side ? "SELL" : "BUY",
652 // to_price_double(level.price),
653 // to_qty_double(level.qty),
654 // level.seq_num,
655 // format_timestamp_iso8601(level.event_time, 9),
656 // level.event_time);
657 updates.push_back({
658 {"side", level.side ? "offer" : "bid"},
659 {"price_level", to_price_string(level.price)},
660 {"new_quantity", to_qty_string(level.qty)},
661 {"event_time", format_timestamp_iso8601(level.event_time, 9)}
662 });
663 }
664
665 json update_msg = {
666 {"channel", "l2_data"},
667 {"client_id", ""},
668 {"timestamp", format_timestamp_iso8601(9)},
669 {"events", {{
670 {"type", "update"},
671 {"product_id", update->symbol},
672 {"updates", updates}
673 }}}
674 };
675
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);
681 }
682 }
683}
684
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()) {
688 return;
689 }
690 auto range = it_range->second.equal_range(static_cast<uint8_t>(coinbase::WebSocketChannel::MARKET_TRADES));
691 if (range.first == range.second) {
692 return;
693 }
694
695 auto *summary = reinterpret_cast<TradeSummary*>(update->data);
696 auto trade_msg = encode_market_trade(update->symbol, *summary);
697
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);
703 }
704}
705
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) {
711 return;
712 }
713 SLICK_ASSERT(false && "User data shouldn't subscribed in market data publisher");
714 }
715}
static SymbolManager & instance()
CoinbasePublisher(const json &config, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue)
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...
Definition decimal.hpp:9
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()
Definition timestamp.hpp:62
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
Definition timestamp.hpp:9
constexpr const char * to_string(FeedState state) noexcept
@ TRADE_SUMMARY
One executed trade.
std::string to_price_string(price_t price)
Definition types.hpp:107
std::string to_qty_string(qty_t qty)
Definition types.hpp:108