Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_ws_order_gateway.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
3#include <utils/timestamp.hpp>
4#include <coinbase/rest.hpp>
5#include <coinbase/order.hpp>
6#include "coinbase_common.hpp"
7#include <cstdlib>
8
9using CoinbaseRestClient = coinbase::CoinbaseRestClient;
10using namespace slick::sim::order_gateway;
12using namespace slick::sim::utils;
13
14namespace {
15 ::coinbase::OrderStatus to_coinbase_order_status(slick::sim::OrderStatus status) {
16 switch (status) {
17 case slick::sim::OrderStatus::NEW: return ::coinbase::OrderStatus::OPEN;
18 case slick::sim::OrderStatus::PENDING_NEW: return ::coinbase::OrderStatus::PENDING;
19 case slick::sim::OrderStatus::PENDING_REPLACE: return ::coinbase::OrderStatus::EDIT_QUEUED;
20 case slick::sim::OrderStatus::PENDING_CANCEL: return ::coinbase::OrderStatus::CANCEL_QUEUED;
21 case slick::sim::OrderStatus::REPLACED: return ::coinbase::OrderStatus::OPEN;
22 case slick::sim::OrderStatus::CANCELED: return ::coinbase::OrderStatus::CANCELLED;
23 case slick::sim::OrderStatus::FILLED: return ::coinbase::OrderStatus::FILLED;
24 // Coinbase has no partially-filled status. Keep the order OPEN while quantity remains
25 // live; `completion_percentage` reports its progress. The old FILLED mapping told
26 // clients the order had finished.
27 case slick::sim::OrderStatus::PARTIALLY_FILLED: return ::coinbase::OrderStatus::OPEN;
28 case slick::sim::OrderStatus::EXPIRED: return ::coinbase::OrderStatus::EXPIRED;
29 case slick::sim::OrderStatus::REJECTED: return ::coinbase::OrderStatus::FAILED;
30 default: return ::coinbase::OrderStatus::UNKNOWN_ORDER_STATUS;
31 }
32 }
33
36 bool hasCoinbaseCredentials() {
37#if defined(_WIN32)
38 char *value = nullptr;
39 size_t size = 0;
40 const bool present = _dupenv_s(&value, &size, "COINBASE_API_SECRET") == 0 && value != nullptr && value[0] != '\0';
41 std::free(value);
42 return present;
43#else
44 const char *value = std::getenv("COINBASE_API_SECRET");
45 return value != nullptr && value[0] != '\0';
46#endif
47 }
48
51 std::string_view to_coinbase_time_in_force(slick::sim::TimeInForce tif) {
53 switch (tif) {
54 case TimeInForce::GOOD_TILL_CANCEL: return "GOOD_UNTIL_CANCELLED";
55 case TimeInForce::GOOD_TILL_DATE: return "GOOD_UNTIL_DATE_TIME";
56 case TimeInForce::IMMEDIATE_OR_CANCEL: return "IMMEDIATE_OR_CANCEL";
57 case TimeInForce::FILL_OR_KILL: return "FILL_OR_KILL";
58 default: return "UNKNOWN_TIME_IN_FORCE";
59 }
60 }
61}
62
63
64uint_fast64_t PerSocketData::heartbeat_count = 0;
65
66CoinbaseWebsocketOrderGateway::CoinbaseWebsocketOrderGateway(const json& config, slick::queue<Request> &request_queue, slick::queue<OrderResponse> &response_queue)
67 : RestWsOrderGateway(Venue::COINBASE, request_queue, response_queue, config.value("port", 3001))
68 , response_read_index_(response_queue_.initial_reading_index())
69 , ping_interval_ms_(config.value("ping_interval", 30) * 1000)
70 , pong_timeout_(config.value("pong_timeout", 60))
71{
72 // fee_rate_ is used only to display total_fees on the user channel. Fetching it requires an
73 // authenticated startup round trip, also fetches products, and needs COINBASE_API_KEY/SECRET.
74 // For offline startup without a live feed, skip the call when `fee_rate` is configured or the
75 // secret is absent.
76 if (config.contains("fee_rate")) {
77 fee_rate_ = config["fee_rate"].get<double>();
78 } else if (!hasCoinbaseCredentials()) {
79 LOG_WARN("order_gateway.ws has no fee_rate and COINBASE_API_SECRET is unset; "
80 "using the default taker fee rate {} without calling Coinbase", fee_rate_);
81 } else {
82 try {
83 auto rest_api = CoinbaseRestClient(config.value("base_url", "https://api.coinbase.com"));
84 fee_rate_ = rest_api.get_taker_fee_rate();
85 } catch (const std::exception &ex) {
86 LOG_WARN("Could not fetch the Coinbase taker fee rate ({}); using {}", ex.what(), fee_rate_);
87 }
88 }
89}
90
91void CoinbaseWebsocketOrderGateway::setup_routes(uWS::App &app) {
92 app.ws<PerSocketData>("/*", {
93 /* WebSocket settings */
94 .compression = uWS::SHARED_COMPRESSOR,
95 .maxPayloadLength = 16 * 1024,
96 .idleTimeout = 120,
97 .maxBackpressure = 1 * 1024 * 1024,
98
99 /* WebSocket handlers */
100 .upgrade = nullptr,
101
102 .open = [this](auto *ws) {
103 // Initialize connection timestamp
104 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
105 ws->getUserData()->authenticated = false;
106 // The sequence is per socket and starts at zero: a client resets its
107 // continuity check on connect and expects the first message to be 0.
108 ws->getUserData()->seq_num = 0;
109 LOG_INFO("WebSocket client connected");
110 },
111
112 .message = [this](auto *ws, std::string_view message, uWS::OpCode /* opCode */) {
113 handle_message(ws, message);
114 },
115
116 .drain = [](auto */* ws */) {
117 // Check backpressure
118 },
119
120 .ping = [](auto *ws, std::string_view /* message */) {
121 // Automatically respond to client ping with pong
122 // uWebSockets handles this automatically, but we log it
123 LOG_TRACE("Received ping from client {:p}", (void*)ws);
124 },
125
126 .pong = [this](auto *ws, std::string_view /* message */) {
127 // Client responded to our ping
128 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
129 LOG_TRACE("Received pong from client {:p}", (void*)ws);
130 },
131
132 .close = [this](auto *ws, int code, std::string_view message) {
133 handle_close(ws, code, message);
134 }
135 });
136}
137
138void CoinbaseWebsocketOrderGateway::on_listen_socket([[maybe_unused]] us_listen_socket_t *listen_socket) {
139 loop_->defer([this]() {
140 // The third argument is ext_size, not a flag: it is the number of bytes
141 // us_timer_ext() hands back. Passing 0 and then writing a pointer there
142 // overruns the timer allocation.
143 heartbeat_timer_ = us_create_timer((struct us_loop_t*)loop_, 0,
145
146 // Store 'this' pointer in timer extension data
147 *((CoinbaseWebsocketOrderGateway**)us_timer_ext(heartbeat_timer_)) = this;
148
149 // Set timer callback that retrieves 'this' from extension data
150 us_timer_set(heartbeat_timer_, [](struct us_timer_t *timer) {
151 // Dereference the pointer stored in extension data
152 auto* self = *((CoinbaseWebsocketOrderGateway**)us_timer_ext(timer));
153 self->check_heartbeats();
154 }, ping_interval_ms_, ping_interval_ms_);
155 });
156
157 LOG_INFO("COINBASE Websocket OrderGateway Event loop configured (heartbeat: {}ms)", ping_interval_ms_);
158
159 // Start continuous response processing
160 schedule_response_processing();
161}
162
163void CoinbaseWebsocketOrderGateway::handle_message(wsT *ws, std::string_view message) {
164 try {
165 json msg = json::parse(message);
166
167 // Check if this is a subscription message
168 if (msg.contains("type") && msg["type"] == "subscribe") {
169 // Extract JWT token from message
170 if (!msg.contains("jwt")) {
171 send_error(ws, "Missing JWT token");
172 return;
173 }
174
175 auto &token = msg["jwt"].get_ref<std::string&>();
176
177 // Verify and decode JWT
178 try {
179 auto decoded = jwt::decode<jwt::traits::nlohmann_json>(token);
180 // auto verifier = jwt::verify<jwt::traits::nlohmann_json>()
181 // .allow_algorithm(jwt::algorithm::hs256{jwt_secret_})
182 // .with_issuer("coinbase");
183 // verifier.verify(decoded);
184
185 // Extract 'sub' claim
186 std::string sub = decoded.get_subject();
187
188 // Store user_id in per-socket data
189 auto *user_data = ws->getUserData();
190 user_data->sub = sub;
191 user_data->user_id = sub.substr(sub.rfind('/') + 1);
192 user_data->authenticated = true;
193
194 if (!clients_.contains(user_data->user_id)) {
195 user_data->seq_num = 0;
196 clients_[user_data->user_id] = ws;
197 }
198
199 auto &channel = msg["channel"].get_ref<std::string&>();
200
201 LOG_INFO("Client {} subscribe channel {}", sub, channel);
202
203 if (channel == "user") {
204 // Send subscription confirmation
205 {
206 json orders = json::array();
207 for (const Order *order : orders_.orders_of(user_data->user_id)) {
208 orders.push_back(to_json(*order));
209 }
210 json response = {
211 {"channel", "user"},
212 {"client_id", ""},
213 {"timestamp", utils::format_timestamp_iso8601(9)},
214 {"sequence_num", user_data->seq_num++},
215 {"events", {{
216 {"type", "snapshot"},
217 {"orders", orders},
218 {"positions", {
219 {"perpetual_futures_positions", json::array()},
220 {"expiring_futures_positions", json::array()}
221 }}
222 }}}
223 };
224 ws->send(coinbase::dump_json(response), uWS::OpCode::TEXT);
225 }
226 {
227 json response = {
228 {"channel", "subscriptions"},
229 {"client_id", ""},
230 {"timestamp", utils::format_timestamp_iso8601(9)},
231 {"sequence_num", user_data->seq_num++},
232 {"events", {{
233 {"subscriptions", {
234 {"user", {user_data->user_id}}
235 }}
236 }}}
237 };
238
239 ws->send(response.dump(), uWS::OpCode::TEXT);
240 }
241 }
242 else if (channel == "heartbeats") {
243 user_data->subscribed_heartbeat = true;
244 json response = {
245 {"channel", "subscriptions"},
246 {"client_id", ""},
247 {"timestamp", utils::format_timestamp_iso8601(9)},
248 {"sequence_num", user_data->seq_num++},
249 {"events", {{
250 {"subscriptions", {
251 {"heartbeats", {"heartbeats"}}
252 }}
253 }}}
254 };
255 ws->send(response.dump(), uWS::OpCode::TEXT);
256 }
257 else if (channel == "futures_balance_summary") {
258 json response = {
259 {"channel", "futures_balance_summary"},
260 {"client_id", ""},
261 {"timestamp", utils::format_timestamp_iso8601(9)},
262 {"sequence_num", user_data->seq_num++},
263 {"events", {{
264 {"type", "snapshot"},
265 {"fcm_balance_summary", {
266 {"futures_buying_power", "10000.00"},
267 {"total_usd_balance", "3611.86"},
268 {"cbi_usd_balance", "2051.75"},
269 {"cfm_usd_balance", "1560.11"},
270 {"total_open_orders_hold_amount", "0"},
271 {"unrealized_pnl", "0"},
272 {"daily_realized_pnl", "0"},
273 {"initial_margin","460.14"},
274 {"available_margin", "5060.76"},
275 {"liquidation_threshold", "345.11"},
276 {"liquidation_buffer_amount", "4715.66"},
277 {"liquidation_buffer_percentage", "1000"},
278 {"intraday_margin_window_measure", {
279 {"margin_window_type", "FCM_MARGIN_WINDOW_TYPE_INTRADAY"},
280 {"margin_level","MARGIN_LEVEL_TYPE_BASE"},
281 {"initial_margin","460.14"},
282 {"maintenance_margin","345.11"},
283 {"liquidation_buffer_percentage", "1000"},
284 {"total_hold","0"},
285 {"futures_buying_power","10000.00"}
286 }},
287 {"overnight_margin_window_measure", {
288 {"margin_window_type","FCM_MARGIN_WINDOW_TYPE_OVERNIGHT"},
289 {"margin_level","MARGIN_LEVEL_TYPE_BASE"},
290 {"initial_margin","1497.85"},
291 {"maintenance_margin","1318.11"},
292 {"liquidation_buffer_percentage","1000"},
293 {"total_hold","0"},
294 {"futures_buying_power","2293.45"}
295 }}
296 }}
297 }}}
298 };
299 ws->send(response.dump(), uWS::OpCode::TEXT);
300 }
301 else {
302 json response = {
303 {"type", "error"},
304 {"message", std::format("channel `{}` is not supported", channel)},
305 };
306 ws->send(response.dump(), uWS::OpCode::TEXT);
307 }
308 } catch (const jwt::error::token_verification_exception& e) {
309 send_error(ws, std::string("JWT verification failed: ") + e.what());
310 ws->close();
311 } catch (const std::exception& e) {
312 send_error(ws, std::string("JWT decode error: ") + e.what());
313 ws->close();
314 }
315 }
316 else {
317 json response = {
318 {"type", "error"},
319 {"message", std::format("type `{}` is not supported", msg.value<std::string>("type", ""))},
320 };
321 ws->send(response.dump(), uWS::OpCode::TEXT);
322 }
323 } catch (const json::parse_error& e) {
324 send_error(ws, std::string("Invalid JSON: ") + e.what());
325 }
326}
327
328void CoinbaseWebsocketOrderGateway::handle_close(wsT *ws, int code, std::string_view message) {
329 auto &user_id = ws->getUserData()->user_id;
330
331 if (!user_id.empty()) {
332 // Remove client from map (no lock needed - single threaded)
333 clients_.erase(user_id);
334 LOG_INFO("Client disconnected: user_id={}, code={}, msg={}", user_id, code, message);
335 } else {
336 LOG_INFO("Client disconnected before authentication, code={}, msg={}", code, message);
337 }
338}
339
340void CoinbaseWebsocketOrderGateway::send_error(wsT *ws, const std::string& error_msg) {
341 json error = {
342 {"type", "error"},
343 {"message", error_msg}
344 };
345 ws->send(error.dump(), uWS::OpCode::TEXT);
346 LOG_ERROR("WebSocket error: {}", error_msg);
347}
348
349void CoinbaseWebsocketOrderGateway::process_all_responses() {
350 // Process up to 100 responses per call to avoid blocking event loop too long
351 constexpr int max_batch = 100;
352 int processed = 0;
353
354 while (processed < max_batch) {
355 // Try to read from the queue (non-blocking)
356 auto [data, size] = response_queue_.read(response_read_index_);
357
358 if (data == nullptr) {
359 // No more data available
360 break;
361 }
362
363 // Process the order response
364 auto& response = *data;
365
366 // Record it before anything else. This has to happen whether or not the
367 // owner is connected: a client that subscribes later still expects its
368 // earlier orders in the snapshot, and this is the only pass over the stream.
369 orders_.apply(response);
370
371 // Extract user_id from the order response
372 std::string user_id = response.user_id;
373
374 if (user_id.empty()) {
375 LOG_WARN("Order response has empty user_id, skipping");
376 processed++;
377 continue;
378 }
379
380 // Find the WebSocket connection for this user (no lock needed - single threaded)
381 auto it = clients_.find(user_id);
382 if (it != clients_.end()) {
383 auto* client_ws = it->second;
384 // Serialize order response to JSON
385 handle_order_response(response, client_ws);
386
387 LOG_INFO("Sent order response {} to user_id={}, client_order_id={}, order_status={}",
388 to_string(response.exec_type), user_id, response.client_order_id, to_string(response.order_status));
389 } else {
390 LOG_WARN("No WebSocket connection found for user_id={}", user_id);
391 }
392
393 processed++;
394 }
395
396 // Reschedule ourselves to run again on next event loop iteration
397 // schedule_response_processing() checks running_ flag
398 schedule_response_processing();
399}
400
401void CoinbaseWebsocketOrderGateway::handle_order_response(const OrderResponse &response, wsT *ws) {
402 // Serialize order response to JSON
403 if (response.order_status == OrderStatus::PENDING_NEW) {
404 // Don't send pending new updates to client - wait for final status update
405 return;
406 }
407 auto filled_value = to_price_double(response.avg_fill_price) * to_qty_double(response.cum_qty);
408 auto fees = filled_value * fee_rate_;
409 auto *user_data = ws->getUserData();
410 // process_all_responses applies this report to the order store before calling here. The store
411 // tracks the fill count because OrderResponse has no count field. The ratio cum_qty/last_qty
412 // gives the count only when all fills have the same size.
413 const auto order_id_view =
414 std::string_view(response.order_id, strnlen(response.order_id, sizeof(response.order_id)));
415 const auto *tracked = orders_.find(order_id_view);
416 const auto fill_count = tracked != nullptr ? tracked->num_fills : 0u;
417 const auto completion =
418 response.qty > 0 ? (to_qty_double(response.cum_qty) / to_qty_double(response.qty)) * 100.0 : 0.0;
419 json response_json = {
420 {"channel", "user"},
421 {"client_id", ""},
422 {"timestamp", format_timestamp_iso8601(9)},
423 {"sequence_num", user_data->seq_num++},
424 {"events", json::array({
425 json::object({
426 {"type", "update"},
427 {"orders", json::array({
428 json::object({
429 {"avg_price", to_price_string(response.avg_fill_price)},
430 {"client_order_id", std::string(response.client_order_id)},
431 {"completion_percentage", std::to_string(completion)},
432 {"contract_expiry_type", "UNKNOWN_CONTRACT_EXPIRY_TYPE"},
433 {"cumulative_quantity", to_qty_string(response.cum_qty)},
434 {"filled_value", std::to_string(filled_value)},
435 {"leaves_quantity", to_qty_string(response.leaves_qty)},
436 {"limit_price", to_price_string(response.price)},
437 {"number_of_fills", std::to_string(fill_count)},
438 {"order_id", std::string(response.order_id)},
439 {"order_side", response.side == Side::BUY ? "BUY" : "SELL"},
440 {"order_type", to_string(response.order_type)},
441 {"post_only", response.post_only ? "true" : "false"},
442 {"product_id", std::string(response.symbol)},
443 {"reject_reason", to_string(response.reject_reason)},
444 {"status", to_string(to_coinbase_order_status(response.order_status))},
445 {"time_in_force", std::string(to_coinbase_time_in_force(response.time_in_force))},
446 {"total_fees", std::to_string(fees)},
447 {"total_value_after_fees", std::to_string(filled_value - fees)},
448 {"trigger_status", "INVALID_ORDER_TYPE"},
449 {"creation_time", format_timestamp_iso8601(response.creation_time, 9)},
450 {"end_time", "0001-01-01T00:00:00Z"},
451 {"start_time", "0001-01-01T00:00:00Z"}
452 })
453 })}
454 })
455 })}
456 };
457
458 // Send to client via WebSocket
459 ws->send(response_json.dump(), uWS::OpCode::TEXT);
460}
461
462void CoinbaseWebsocketOrderGateway::check_heartbeats() {
463 auto now = std::chrono::steady_clock::now();
464 std::vector<std::string> disconnected_clients;
465
466 // No lock needed - single threaded event loop
467 for (auto it = clients_.begin(); it != clients_.end();) {
468 auto* ws = it->second;
469 auto* user_data = ws->getUserData();
470
471 // Check if client has responded to pings
472 auto time_since_pong = std::chrono::duration_cast<std::chrono::seconds>(
473 now - user_data->last_pong);
474
475 if (time_since_pong > pong_timeout_) {
476 // Client hasn't responded to pings, close connection
477 LOG_WARN("Client {} failed heartbeat check (last_pong: {}s ago), disconnecting",
478 user_data->user_id, time_since_pong.count());
479
480 disconnected_clients.push_back(it->first);
481 it = clients_.erase(it);
482 ws->close(); // Close the connection
483 } else {
484 // Send ping to client (only if authenticated)
485 if (user_data->subscribed_heartbeat) {
486 // Send a text-based ping message (Coinbase style)
487 json event = {
488 {"current_time", utils::format_heatbeat_timestamp()},
489 {"heartbeat_counter", user_data->heartbeat_count++}
490 };
491 json ping_msg = {
492 {"channel", "heartbeats"},
493 {"client_id", ""},
494 {"timestamp", utils::format_timestamp_iso8601(9)},
495 {"sequence_num", user_data->seq_num++},
496 {"events", {event}}
497 };
498 ws->send(ping_msg.dump(), uWS::OpCode::TEXT);
499 }
500 // Also send protocol-level ping
501 ws->send("", uWS::OpCode::PING);
502 LOG_TRACE("Sent heartbeat to client {}", user_data->user_id);
503 ++it;
504 }
505 }
506
507 if (!disconnected_clients.empty()) {
508 LOG_INFO("Disconnected {} stale clients", disconnected_clients.size());
509 }
510}
CoinbaseWebsocketOrderGateway(const json &config, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue)
slick::queue< OrderResponse > & response_queue_
RestWsOrderGateway(Venue venue, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue, uint32_t port)
coinbase::CoinbaseRestClient CoinbaseRestClient
nlohmann::json json
Definition order.hpp:16
std::string dump_json(const json &value)
nlohmann's dump() throws on invalid UTF-8.
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
Definition decimal.hpp:9
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 double to_price_double(price_t price)
Definition types.hpp:46
constexpr const char * to_string(FeedState state) noexcept
std::string to_price_string(price_t price)
Definition types.hpp:107
std::string to_qty_string(qty_t qty)
Definition types.hpp:108
constexpr double to_qty_double(qty_t qty)
Definition types.hpp:54
OrdRejectReason reject_reason
Definition messages.hpp:312