Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
coinbase_rest_order_gateway.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
3#include <coinbase/auth.hpp>
5#include <algorithm>
6#include <cmath>
7#include "coinbase_common.hpp"
8
9using namespace slick::sim;
10using namespace slick::sim::order_gateway;
11using Http = slick::net::Http;
12
13namespace {
14
15bool is_multiple_of(double value, double increment) {
16 if (increment < 1e-12) return true;
17 double ratio = value / increment;
18 return std::abs(ratio - std::round(ratio)) < 1e-6;
19}
20
21// Per-request data for HTTP POST handling
22struct PostRequestData {
23 std::string body_buffer;
24 std::string user_id;
25};
26
27} // namespace
28
29namespace {
30
31bool iequals(std::string_view lhs, std::string_view rhs) noexcept {
32 return lhs.size() == rhs.size()
33 && std::equal(lhs.begin(), lhs.end(), rhs.begin(), [](char a, char b) {
34 return std::tolower(static_cast<unsigned char>(a))
35 == std::tolower(static_cast<unsigned char>(b));
36 });
37}
38
44bool matches_order_status(std::string_view filter, OrderStatus status) noexcept {
45 if (iequals(filter, "OPEN")) {
46 switch (status) {
53 return true;
54 default:
55 return false;
56 }
57 }
58 return iequals(filter, to_string(status));
59}
60
61} // namespace
62
63CoinbaseRestOrderGateway::CoinbaseRestOrderGateway(const json& config, slick::queue<Request> &request_queue, slick::queue<OrderResponse> &response_queue)
64 : RestWsOrderGateway(Venue::COINBASE, request_queue, response_queue, config.value("port", 3000))
65 , response_cursor_(response_queue.initial_reading_index())
66 , response_poll_ms_(config.value("response_poll_ms", 1))
67{
68 if (config.contains("initial_products")) {
69 products_ = config["initial_products"].get<std::string>();
70 } else {
71 auto base_url = config.value("base_url", "https://api.coinbase.com");
72 auto rsp = Http::get(base_url + "/api/v3/brokerage/market/products");
73 if (rsp.is_ok()) {
74 products_ = rsp.result_text;
75 } else {
76 LOG_WARN("Failed to get products. error: {}", rsp.result_text);
77 }
78 }
79 if (!products_.empty()) {
80 auto products = json::parse(products_);
81 for (auto &prod : products["products"]) {
82 const auto product_id = prod["product_id"].get<std::string>();
83 auto as_double = [&prod](const char *key) -> double {
84 if (!prod.contains(key)) return 0.0;
85 const auto &value = prod[key];
86 return value.is_string() ? std::stod(value.get<std::string>()) : value.get<double>();
87 };
88 product_specs_[product_id] = ProductSpec{
89 .price_increment = as_double("price_increment"),
90 .base_increment = as_double("base_increment"),
91 .base_min_size = as_double("base_min_size"),
92 };
93 product_by_id_[product_id] = prod.dump();
94 }
95 }
96}
97
98void CoinbaseRestOrderGateway::on_listen_socket(us_listen_socket_t *) {
99 // Create the timer once and arm it for requests. A repeating millisecond timer kept an active
100 // handle on the uWS loop, preventing app.run() from returning and causing stop() to hang at
101 // join. An idle gateway now has no active timer.
102 response_timer_ = us_create_timer(reinterpret_cast<us_loop_t *>(loop_), 0, sizeof(CoinbaseRestOrderGateway *));
103 *reinterpret_cast<CoinbaseRestOrderGateway **>(us_timer_ext(response_timer_)) = this;
104 LOG_INFO("Coinbase REST response poll ready ({} ms)", response_poll_ms_);
105}
106
107void CoinbaseRestOrderGateway::armResponseTimer() {
108 if (response_timer_ == nullptr || response_timer_armed_) {
109 return;
110 }
111 response_timer_armed_ = true;
112 us_timer_set(
113 response_timer_,
114 [](us_timer_t *timer) {
115 auto *self = *reinterpret_cast<CoinbaseRestOrderGateway **>(us_timer_ext(timer));
116 self->response_timer_armed_ = false;
117 self->drainResponses();
118 self->expireWaiters();
119 // Keep polling while HTTP waiters or expected reports remain. A disconnected client can
120 // still have a report in flight that supplies order routing. Once both are drained,
121 // leave the timer inactive so the loop can exit on shutdown.
122 if (self->pending_.size() != 0 || !self->timed_waiters_.empty() ||
123 !self->expected_reports_.empty()) {
124 self->armResponseTimer();
125 }
126 },
127 std::max(1, response_poll_ms_), 0); // one-shot
128}
129
131 if (loop_ != nullptr && response_timer_ != nullptr) {
132 us_timer_t *timer = response_timer_;
133 response_timer_ = nullptr; // armResponseTimer must not touch it again
134 response_timer_armed_ = false;
135 // Timers are owned by the loop and may only be touched on its thread.
136 loop_->defer([timer]() { us_timer_close(timer); });
137 }
139}
140
141void CoinbaseRestOrderGateway::track(PendingResponses::Id id, std::chrono::milliseconds timeout) {
142 timed_waiters_.push_back({id, std::chrono::steady_clock::now() + timeout});
143}
144
145void CoinbaseRestOrderGateway::untrack(PendingResponses::Id id) {
146 std::erase_if(timed_waiters_, [id](const TimedWaiter &waiter) { return waiter.id == id; });
147}
148
149void CoinbaseRestOrderGateway::abandonPending(const std::shared_ptr<PendingHttp> &http) {
150 for (const auto id : http->ids) {
151 pending_.abandon(id);
152 // abandon() skips the completion that would untrack this id. Remove its timeout record here
153 // to avoid keeping the poll timer active for the life of the process.
154 untrack(id);
155 }
156 http->ids.clear();
157}
158
159void CoinbaseRestOrderGateway::expectReport(uint64_t tag) {
160 // The deadline stops polling if the engine drops a request and never reports. Reports normally
161 // arrive in microseconds; reading one removes its entry immediately.
162 expected_reports_.push_back({tag, std::chrono::steady_clock::now() + std::chrono::seconds(5)});
163}
164
165void CoinbaseRestOrderGateway::expireWaiters() {
166 const auto now = std::chrono::steady_clock::now();
167 std::vector<PendingResponses::Id> due;
168 for (const auto &waiter : timed_waiters_) {
169 if (waiter.deadline <= now) {
170 due.push_back(waiter.id);
171 }
172 }
173 for (const auto id : due) {
174 pending_.expire(id); // its completion untracks it
175 }
176 // A report that never arrives must not keep the poll running forever.
177 std::erase_if(expected_reports_,
178 [now](const ExpectedReport &expected) { return expected.deadline <= now; });
179}
180
181void CoinbaseRestOrderGateway::drainResponses() {
182 for (;;) {
183 auto [data, size] = response_queue_.read(response_cursor_);
184 if (data == nullptr) {
185 return;
186 }
187 const auto &response = *data;
188 orders_.apply(response);
189
190 // The request this report answers is no longer owed one, whether or not its
191 // HTTP client is still connected.
192 if (response.request_tag != 0 && !expected_reports_.empty()) {
193 std::erase_if(expected_reports_, [&response](const ExpectedReport &expected) {
194 return expected.tag == response.request_tag;
195 });
196 }
197
198 // Learn routing from the report stream. A disconnect abandons the create handler's
199 // completion even when the engine accepts the order. Recording routing in that completion
200 // left such orders visible in history but uncancellable.
201 const std::string_view order_id(response.order_id,
202 strnlen(response.order_id, sizeof(response.order_id)));
203 if (!order_id.empty()) {
204 switch (coinbase::routing_effect(response.order_status)) {
206 order_id_to_symbol_.erase(std::string(order_id));
207 break;
209 const std::string_view symbol(response.symbol,
210 strnlen(response.symbol, sizeof(response.symbol)));
211 if (!symbol.empty()) {
212 order_id_to_symbol_[std::string(order_id)] = std::string(symbol);
213 }
214 break;
215 }
217 break;
218 }
219 }
220
221 pending_.dispatch(response);
222 }
223}
224
225PendingResponses::Id CoinbaseRestOrderGateway::awaitReport(uint64_t tag,
226 std::chrono::milliseconds timeout,
227 const std::shared_ptr<PendingHttp> &http,
228 std::function<void(const OrderResponse *)> on_report) {
229 auto id_slot = std::make_shared<PendingResponses::Id>(PendingResponses::kNoId);
230 const auto id = pending_.add(
231 [tag](const OrderResponse &response) { return response.request_tag == tag; },
232 [this, id_slot, http, on_report = std::move(on_report)](const OrderResponse *response) {
233 untrack(*id_slot);
234 if (!http->aborted) {
235 on_report(response);
236 }
237 });
238 *id_slot = id;
239 http->ids.push_back(id);
240 track(id, timeout);
241 armResponseTimer();
242 return id;
243}
244
245std::tuple<bool, std::string, std::string> CoinbaseRestOrderGateway::authenticate(uWS::HttpRequest *req) {
246 // Get the Authorization header
247 std::string_view auth_header = req->getHeader("authorization");
248
249 // For Coinbase, it's typically: "Bearer <JWT_TOKEN>"
250 if (auth_header.empty()) {
251 auth_header = req->getHeader("Authorization");
252 if (auth_header.empty()) {
253 return std::make_tuple(false, "", R"({"error":"UNAUTHORIZED","message":"Authorization header required"})");
254 }
255 }
256
257 // Extract the token (remove "Bearer " prefix)
258 std::string token;
259 if (auth_header.starts_with("Bearer ")) {
260 token = std::string(auth_header.substr(7));
261 } else {
262 return std::make_tuple(false, "", R"({"error":"UNAUTHORIZED","message":"Invalid auth token"})");
263 }
264
265 try {
266 auto decoded = jwt::decode<jwt::traits::nlohmann_json>(token);
267
268 // Extract 'sub' claim
269 std::string sub = decoded.get_subject();
270 std::string user_id = sub.substr(sub.rfind('/') + 1);
271 return std::make_tuple(true, user_id, "");
272
273 } catch (const std::exception& /* e */) {
274 return std::make_tuple(false, "", R"({"error":"UNAUTHORIZED","message":"Invalid token"})");
275 }
276}
277
278CoinbaseRestOrderGateway::OrderValidationResult
279CoinbaseRestOrderGateway::validate_order(
280 const std::string& product_id, double price_d, double qty_d, OrderType order_type) const
281{
282 auto it = product_specs_.find(product_id);
283 if (it == product_specs_.end()) {
284 return {false, "INVALID_PRODUCT_ID", "Unknown product: " + product_id};
285 }
286
287 const auto &spec = it->second;
288 const double price_inc = spec.price_increment;
289 const double base_inc = spec.base_increment;
290 const double base_min = spec.base_min_size;
291
292 if (order_type != OrderType::MARKET && price_inc > 1e-12) {
293 if (!is_multiple_of(price_d, price_inc)) {
294 return {false, "INVALID_LIMIT_PRICE_POST_ONLY",
295 "price " + std::to_string(price_d) +
296 " is not a multiple of tick size " + std::to_string(price_inc)};
297 }
298 }
299
300 if (base_min > 1e-12 && qty_d < base_min - 1e-9) {
301 return {false, "INVALID_ORDER_CONFIG",
302 "qty " + std::to_string(qty_d) +
303 " is below minimum order size " + std::to_string(base_min)};
304 }
305
306 if (base_inc > 1e-12 && !is_multiple_of(qty_d, base_inc)) {
307 return {false, "INVALID_ORDER_CONFIG",
308 "qty " + std::to_string(qty_d) +
309 " is not a multiple of base increment " + std::to_string(base_inc)};
310 }
311
312 return {true, {}, {}};
313}
314
315// void CoinbaseRestOrderGateway::start() {
316// thread_ = std::move(std::thread([this]() {
317// auto app = uWS::App();
318// setup_routes(app);
319// app.listen(port_, [this](auto *listen_socket) {
320// listen_socket_ = listen_socket;
321// if (listen_socket) {
322// LOG_INFO("Coinbase REST OrderGateway started on port {}", port_);
323// } else {
324// LOG_ERROR("Failed to listen to port");
325// }
326// }).run();
327// }));
328// }
329
330void CoinbaseRestOrderGateway::setup_routes(uWS::App &app) {
331 app.get("/api/v3/brokerage/market/products", [this](auto *res, auto */* req */) {
332 res->writeHeader("Content-Type", "application/json")->end(products_);
333 }).get("/api/v3/brokerage/products", [this](auto *res, auto */* req */) {
334 res->writeHeader("Content-Type", "application/json")->end(products_);
335 }).get("/api/v3/brokerage/products/:product_id", [this](auto *res, auto *req) {
336 handle_get_product(res, req);
337 }).get("/api/v3/brokerage/market/products/:product_id", [this](auto *res, auto *req) {
338 handle_get_product(res, req);
339 }).get("/api/v3/brokerage/orders/historical/batch", [this](auto *res, auto *req) {
340 handle_get_orders(res, req);
341 }).post("/api/v3/brokerage/orders", [this](auto *res, auto *req) {
342 handle_create_order(res, req);
343 }).post("/api/v3/brokerage/orders/batch_cancel", [this](auto *res, auto *req) {
344 handle_batch_cancel(res, req);
345 }).post("/api/v3/brokerage/orders/edit", [this](auto *res, auto *req) {
346 handle_edit_order(res, req);
347 }).get("/api/v3/brokerage/transaction_summary", [this](auto *res, auto *req) {
348 handle_get_transaction_summary(res, req);
349 });
350}
351
352void CoinbaseRestOrderGateway::handle_get_product(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
353 std::string_view product_id = req->getParameter("product_id");
354 LOG_INFO("Fetching product: {}", product_id);
355 auto iter = product_by_id_.find(std::string(product_id));
356 if (iter != product_by_id_.end()) {
357 res->end(iter->second);
358 }
359 else {
360 res->writeStatus("400 Bad Request")
361 ->writeHeader("Content-Type", "application/json")
362 ->end(R"({"error":"INVALID_ARGUMENT","error_details":"valid product_id is required","message":"valid product_id is required"})");
363 }
364}
365
366void CoinbaseRestOrderGateway::handle_get_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
367 auto [authenticated, user_id, error_response] = authenticate(req);
368 if (!authenticated) {
369 res->writeStatus("401 Unauthorized")
370 ->writeHeader("Content-Type", "application/json")
371 ->end(error_response);
372 return;
373 }
374
375 // Query parameters are read before anything else: `req` is only valid for the
376 // duration of this call, and uWebSockets recycles it as soon as we return.
377 const std::string product_id(req->getQuery("product_id"));
378 const std::string order_side(req->getQuery("order_side"));
379 const std::string order_status(req->getQuery("order_status"));
380 const std::string limit_param(req->getQuery("limit"));
381
382 size_t limit = std::numeric_limits<size_t>::max();
383 if (!limit_param.empty()) {
384 char *parse_end = nullptr;
385 const auto parsed = std::strtoull(limit_param.c_str(), &parse_end, 10);
386 if (parse_end == limit_param.c_str() || *parse_end != '\0') {
387 res->writeStatus("400 Bad Request")
388 ->writeHeader("Content-Type", "application/json")
389 ->end(R"({"error":"INVALID_ARGUMENT","error_details":"limit must be a number","message":"limit must be a number"})");
390 return;
391 }
392 limit = static_cast<size_t>(parsed);
393 }
394
395 // Catch up on everything the exchange has reported since the last listing. Done
396 // here rather than on a timer because the create-order handler blocks this same
397 // loop thread while it waits for its response, so scheduled work is not reliably
398 // able to run between requests.
399 drainResponses();
400
401 json orders = json::array();
402 for (const Order *order : orders_.orders_of(user_id)) {
403 if (!product_id.empty() && product_id != order->symbol.view()) {
404 continue;
405 }
406 if (!order_side.empty() && !iequals(order_side, to_string(order->side))) {
407 continue;
408 }
409 if (!order_status.empty() && !matches_order_status(order_status, order->status)) {
410 continue;
411 }
412 if (orders.size() >= limit) {
413 break;
414 }
415 orders.push_back(coinbase::to_json(*order));
416 }
417
418 // `has_next`/`cursor` are part of the documented envelope. The whole (filtered)
419 // result is returned in one page, so the cursor is always empty - a client that
420 // pages correctly still terminates.
421 json response = {
422 {"orders", std::move(orders)},
423 {"sequence", "0"},
424 {"has_next", false},
425 {"cursor", ""}
426 };
427
428 res->writeHeader("Content-Type", "application/json")
429 ->end(coinbase::dump_json(response));
430}
431
432void CoinbaseRestOrderGateway::handle_create_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
433 auto [authenticated, user_id, error_response] = authenticate(req);
434 if (!authenticated) {
435 res->writeStatus("401 Unauthorized")
436 ->writeHeader("Content-Type", "application/json")
437 ->end(error_response);
438 return;
439 }
440
441 auto request_data = std::make_shared<PostRequestData>();
442 request_data->user_id = std::move(user_id);
443
444 // Track the PendingResponses ids and connection state for each in-flight HTTP request. Check
445 // `aborted` before using the response: uWS keeps it alive after the handler returns, but
446 // destroys it when the connection drops.
447 auto http = std::make_shared<PendingHttp>();
448 http->response = res;
449 res->onAborted([this, http]() {
450 http->aborted = true;
451 abandonPending(http);
452 LOG_WARN("HTTP connection aborted during POST /api/v3/brokerage/orders");
453 });
454
455 // Accumulate request body chunks
456 res->onData([this, res, request_data, http](std::string_view chunk, bool is_last) mutable {
457
458 // Accumulate body chunks
459 request_data->body_buffer.append(chunk);
460
461 if (!is_last) {
462 return; // Wait for more data
463 }
464
465 // Process complete request body
466 try {
467 json request_body = json::parse(request_data->body_buffer);
468
469 // Extract required fields
470 std::string product_id = request_body["product_id"];
471 std::string side_str = request_body["side"];
472 std::string client_order_id = request_body["client_order_id"];
473 std::string user_id = request_data->user_id;
474
475 // Parse order_configuration to determine order type and TIF
476 auto& order_config = request_body["order_configuration"];
477
478 OrderType order_type;
479 TimeInForce tif;
480 price_t price = NULL_PRICE;
481 qty_t qty = 0;
482
483 // Pattern match on nested configuration keys
484 if (order_config.contains("limit_limit_gtc")) {
485 order_type = OrderType::LIMIT;
487 auto& cfg = order_config["limit_limit_gtc"];
488 qty = to_qty_t(std::stod(cfg["base_size"].get<std::string>()));
489 price = to_price_t(std::stod(cfg["limit_price"].get<std::string>()));
490 // post_only is ignored: AddOrderMessage has no field to carry it.
491 }
492 else if (order_config.contains("market_market_ioc")) {
493 order_type = OrderType::MARKET;
495 auto& cfg = order_config["market_market_ioc"];
496 qty = to_qty_t(std::stod(cfg["base_size"].get<std::string>()));
497 }
498 else if (order_config.contains("sor_limit_ioc")) {
499 order_type = OrderType::LIMIT;
501 auto& cfg = order_config["sor_limit_ioc"];
502 qty = to_qty_t(std::stod(cfg["base_size"].get<std::string>()));
503 price = to_price_t(std::stod(cfg["limit_price"].get<std::string>()));
504 }
505 else if (order_config.contains("market_market_fok")) {
506 auto& cfg = order_config["market_market_fok"];
508 qty = to_qty_t(std::stod(cfg["base_size"].get<std::string>()));
509
510 // Check if this is LIMIT FOK (has limit_price) or MARKET FOK
511 if (cfg.contains("limit_price")) {
512 order_type = OrderType::LIMIT;
513 price = to_price_t(std::stod(cfg["limit_price"].get<std::string>()));
514 } else {
515 order_type = OrderType::MARKET;
516 }
517 }
518 else if (order_config.contains("limit_limit_fok")) {
519 // coinbase-advanced-cpp sends this configuration for LIMIT orders with
520 // FILL_OR_KILL. The gateway previously accepted only market_market_fok and rejected
521 // this form before it reached the engine.
522 order_type = OrderType::LIMIT;
524 auto& cfg = order_config["limit_limit_fok"];
525 qty = to_qty_t(std::stod(cfg["base_size"].get<std::string>()));
526 price = to_price_t(std::stod(cfg["limit_price"].get<std::string>()));
527 }
528 else {
529 json response_json = {
530 {"success", false},
531 {"error_response", {
532 {"message", "Unsupported order_configuration type"},
533 {"error_details", "Unsupported order_configuration type"},
534 {"new_order_failure_reason", "Unsupported order_configuration type"}
535 }}
536 };
537
538 res->writeStatus("400 Bad Request")
539 ->writeHeader("Content-Type", "application/json")
540 ->end(response_json.dump());
541
542 LOG_ERROR("Order rejected: user={}, client_order_id={}, reason=Unsupported order_configuration type, order_configuration={}",
543 user_id, client_order_id, order_config.dump());
544 return;
545 }
546
547 Side side = (side_str == "BUY") ? Side::BUY : Side::SELL;
548
549 // Validate price and qty against product specs before queuing
550 {
551 const double price_d = (price != NULL_PRICE) ? to_price_double(price) : 0.0;
552 const double qty_d = to_qty_double(qty);
553 auto vr = validate_order(product_id, price_d, qty_d, order_type);
554 if (!vr.valid) {
555 json response_json = {
556 {"success", false},
557 {"error_response", {
558 {"message", vr.error_type},
559 {"error_details", vr.error_details},
560 {"new_order_failure_reason", vr.error_type}
561 }}
562 };
563 res->writeStatus("400 Bad Request")
564 ->writeHeader("Content-Type", "application/json")
565 ->end(response_json.dump());
566 LOG_ERROR("Order rejected (validation): user={}, client_order_id={}, reason={}",
567 user_id, client_order_id, vr.error_details);
568 return;
569 }
570 }
571
572 // Use a request tag to correlate reports independently of user and client order ids.
573 // The order stores the tag and copies it to every response.
574 const uint64_t tag = ++next_request_tag_;
575
576 // Reserve space in request queue
577 auto request_index = request_queue_.reserve();
578 auto* request = request_queue_[request_index];
579
580 // Populate Request struct
581 request->time_stamp = utils::get_current_time_ns();
582 request->request_tag = tag;
583 utils::copy_wire_field(request->symbol, product_id);
584 request->msg_type = MessageType::NEW_ORDER_SINGLE;
585
586 // Populate AddOrderMessage
587 utils::copy_wire_field(request->add_order.user_id, user_id);
588 if (utils::copy_wire_field(request->add_order.client_order_id, client_order_id)) {
589 LOG_WARN("client_order_id truncated to fit into fixed size buffer: original='{}', truncated='{}'", client_order_id, request->add_order.client_order_id);
590 }
591 request->add_order.side = side;
592 request->add_order.type = order_type;
593 request->add_order.time_in_force = tif;
594 request->add_order.price = price;
595 request->add_order.qty = qty;
596 request->add_order.take_profit_price = NULL_PRICE;
597 request->add_order.stop_loss_price = NULL_PRICE;
598 request->add_order.expire_time = 0;
599
600 // Record the expectation before publishing the request. The exchange thread can reply
601 // as soon as the request is queued. Registering afterwards could leave an uncleared
602 // expectation, an armed poll timer and a loop that cannot drain on shutdown.
603 expectReport(tag);
604 request_queue_.publish(request_index);
605
606 LOG_INFO("Published order request: user={}, client_order_id={}, symbol={}, side={}, type={}, qty={}, tag={}",
607 user_id, client_order_id, product_id, side_str,
608 to_string(order_type), to_qty_double(qty), tag);
609
610 // The loop timer sends the HTTP response when the report arrives. Waiting here used to
611 // block the gateway's only event-loop thread for the full timeout, preventing it from
612 // serving other clients.
613 awaitReport(
614 tag, std::chrono::milliseconds(5000), http,
615 [this, res, user_id, client_order_id, product_id, side_str,
616 order_config = order_config.get<json>()](const OrderResponse *matched_response) {
617 if (matched_response == nullptr) {
618 res->writeStatus("504 Gateway Timeout")
619 ->writeHeader("Content-Type", "application/json")
620 ->end(R"({"error":"TIMEOUT","message":"Order processing timeout"})");
621 LOG_ERROR("Order submission timeout: user={}, client_order_id={}", user_id, client_order_id);
622 return;
623 }
624 if (matched_response->order_status == OrderStatus::REJECTED) {
625 // Bounded: this field is a fixed char array in a recycled
626 // queue slot, not a guaranteed NUL-terminated string.
627 const std::string error_msg(
628 matched_response->error_message,
629 strnlen(matched_response->error_message, sizeof(matched_response->error_message)));
630 json response_json = {
631 {"success", false},
632 {"error_response", {
633 {"message", to_string(matched_response->reject_reason)},
634 {"error_details", error_msg},
635 {"new_order_failure_reason", to_string(matched_response->reject_reason)}
636 }}
637 };
638 res->writeStatus("400 Bad Request")
639 ->writeHeader("Content-Type", "application/json")
640 ->end(response_json.dump());
641 LOG_ERROR("Order rejected: user={}, client_order_id={}, reason={}",
642 user_id, client_order_id, to_string(matched_response->reject_reason));
643 return;
644 }
645
646 json response_json = {
647 {"success", true},
648 {"success_response", {
649 {"order_id", matched_response->order_id},
650 {"product_id", product_id},
651 {"side", side_str},
652 {"client_order_id", client_order_id}
653 }},
654 {"order_configuration", order_config}
655 };
656 res->writeStatus("200 OK")
657 ->writeHeader("Content-Type", "application/json")
658 ->end(response_json.dump());
659
660 LOG_INFO("Order processed successfully: user={}, client_order_id={}, order_id={}, status={}",
661 user_id, client_order_id, std::string_view(matched_response->order_id, sizeof(matched_response->order_id)), to_string(matched_response->order_status));
662 });
663 return;
664
665
666 } catch (const json::parse_error& e) {
667 abandonPending(http);
668 res->writeStatus("400 Bad Request")
669 ->writeHeader("Content-Type", "application/json")
670 ->end(json({
671 {"error", "INVALID_REQUEST"},
672 {"message", std::string("Invalid JSON: ") + e.what()}
673 }).dump());
674 LOG_ERROR("JSON parse error in POST /orders: {}", e.what());
675 } catch (const json::exception& e) {
676 abandonPending(http);
677 res->writeStatus("400 Bad Request")
678 ->writeHeader("Content-Type", "application/json")
679 ->end(json({
680 {"error", "INVALID_ARGUMENT"},
681 {"message", std::string("Missing or invalid field: ") + e.what()}
682 }).dump());
683 LOG_ERROR("JSON field error in POST /orders: {}", e.what());
684 } catch (const std::exception& e) {
685 abandonPending(http);
686 res->writeStatus("500 Internal Server Error")
687 ->writeHeader("Content-Type", "application/json")
688 ->end(json({
689 {"error", "INTERNAL_ERROR"},
690 {"message", std::string("Unexpected error: ") + e.what()}
691 }).dump());
692 LOG_ERROR("Unexpected error in POST /orders: {}", e.what());
693 }
694 });
695}
696
697void CoinbaseRestOrderGateway::handle_batch_cancel(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
698 auto [authenticated, user_id, error_response] = authenticate(req);
699 if (!authenticated) {
700 res->writeStatus("401 Unauthorized")
701 ->writeHeader("Content-Type", "application/json")
702 ->end(error_response);
703 return;
704 }
705
706 auto request_data = std::make_shared<PostRequestData>();
707 request_data->user_id = std::move(user_id);
708
709 auto http = std::make_shared<PendingHttp>();
710 http->response = res;
711 res->onAborted([this, http]() {
712 http->aborted = true;
713 abandonPending(http);
714 LOG_WARN("HTTP connection aborted during POST /api/v3/brokerage/orders/batch_cancel");
715 });
716
717 res->onData([this, res, request_data, http](std::string_view chunk, bool is_last) mutable {
718 request_data->body_buffer.append(chunk);
719 if (!is_last) return;
720
721 try {
722 json request_body = json::parse(request_data->body_buffer);
723 auto& order_ids_json = request_body["order_ids"];
724 std::string user_id = request_data->user_id;
725
726 if (!order_ids_json.is_array() || order_ids_json.empty()) {
727 res->writeStatus("400 Bad Request")
728 ->writeHeader("Content-Type", "application/json")
729 ->end(R"({"error":"INVALID_ARGUMENT","message":"order_ids must be a non-empty array"})");
730 return;
731 }
732
733 // Validate every entry before publishing any cancel. A malformed entry
734 // ({"order_ids":["id",123]}) previously threw after earlier entries registered waiters:
735 // the catch returned 400, then the batch wrote another response on the same connection.
736 for (const auto &entry : order_ids_json) {
737 if (!entry.is_string()) {
738 res->writeStatus("400 Bad Request")
739 ->writeHeader("Content-Type", "application/json")
740 ->end(R"({"error":"INVALID_ARGUMENT","message":"order_ids must contain only strings"})");
741 LOG_ERROR("batch_cancel: non-string order_id in request from user={}", user_id);
742 return;
743 }
744 }
745
746 struct CancelEntry {
747 std::string order_id;
748 bool submitted;
749 OrdRejectReason reject_reason = OrdRejectReason::NONE;
750 };
751 struct Batch {
752 uWS::HttpResponse<false>* res;
753 std::vector<CancelEntry> entries;
754 size_t remaining;
755 std::string user_id;
758 bool finished = false;
759 };
760 auto batch = std::make_shared<Batch>(Batch{res, {}, 0, user_id, false});
761 batch->entries.reserve(order_ids_json.size());
762
763 auto finish = [this, batch]() {
764 if (batch->finished) {
765 return;
766 }
767 batch->finished = true;
768 json results = json::array();
769 int rejected = 0;
770 for (auto& entry : batch->entries) {
771 if (!entry.submitted) {
772 results.push_back({{"success", false}, {"failure_reason", "UNKNOWN_ORDER"}, {"order_id", entry.order_id}});
773 continue;
774 }
775 if (entry.reject_reason != OrdRejectReason::NONE) {
776 ++rejected;
777 results.push_back({{"success", false},
778 {"failure_reason", to_string(entry.reject_reason)},
779 {"order_id", entry.order_id}});
780 } else {
781 results.push_back({{"success", true}, {"failure_reason", ""}, {"order_id", entry.order_id}});
782 order_id_to_symbol_.erase(entry.order_id);
783 }
784 }
785 batch->res->writeStatus("200 OK")
786 ->writeHeader("Content-Type", "application/json")
787 ->end(json({{"results", results}}).dump());
788 LOG_INFO("batch_cancel completed: user={}, total={}, rejected={}",
789 batch->user_id, batch->entries.size(), rejected);
790 };
791
792 // Drain reports before looking up routing. A report from an abandoned request may have
793 // arrived since the last poll; until it is read, a cancel for that live order would
794 // return UNKNOWN_ORDER.
795 drainResponses();
796
797 // Publish the whole batch before awaiting replies. The old loop waited 200 ms per order
798 // and blocked the gateway's only event-loop thread for a second on a five-order batch.
799 // Tags correlate each entry with its accepted or rejected response. A timeout retains
800 // the previous "no news is success" behavior.
801 for (auto& oid_json : order_ids_json) {
802 // Already validated as a string above; get_ref avoids another throw
803 // in the middle of a half-submitted batch.
804 std::string order_id = oid_json.get_ref<const std::string&>();
805 auto sym_it = order_id_to_symbol_.find(order_id);
806 if (sym_it == order_id_to_symbol_.end()) {
807 LOG_WARN("batch_cancel: unknown order_id={}", order_id);
808 batch->entries.push_back({order_id, false});
809 continue;
810 }
811 const std::string symbol = sym_it->second;
812 const uint64_t tag = ++next_request_tag_;
813
814 auto request_index = request_queue_.reserve();
815 auto* request = request_queue_[request_index];
816 request->time_stamp = utils::get_current_time_ns();
817 request->request_tag = tag;
818 utils::copy_wire_field(request->symbol, symbol);
819 request->msg_type = MessageType::ORDER_CANCEL_REQUEST;
820
821 std::memset(&request->cancel_order, 0, sizeof(request->cancel_order));
822 utils::copy_wire_field(request->cancel_order.user_id, user_id);
823 // Leave client_order_id empty - engine falls through to findOrderByOrderId
824 utils::copy_wire_field(request->cancel_order.order_id, order_id);
825
826 // Before publishing, for the same reason as the create path.
827 expectReport(tag);
828 request_queue_.publish(request_index);
829 LOG_INFO("Submitted cancel request: user={}, order_id={}, symbol={}, tag={}", user_id, order_id, symbol, tag);
830
831 batch->entries.push_back({order_id, true, OrdRejectReason::NONE});
832 ++batch->remaining;
833 const size_t index = batch->entries.size() - 1;
834 awaitReport(tag, std::chrono::milliseconds(500), http,
835 [batch, index, finish](const OrderResponse *response) {
836 if (response != nullptr && response->order_status == OrderStatus::REJECTED) {
837 batch->entries[index].reject_reason = response->reject_reason;
838 }
839 if (--batch->remaining == 0) {
840 finish();
841 }
842 });
843 }
844
845 if (batch->remaining == 0) {
846 finish();
847 }
848 } catch (const json::parse_error& e) {
849 abandonPending(http);
850 res->writeStatus("400 Bad Request")
851 ->writeHeader("Content-Type", "application/json")
852 ->end(json({
853 {"error", "INVALID_REQUEST"},
854 {"message", std::string("Invalid JSON: ") + e.what()}
855 }).dump());
856 LOG_ERROR("JSON parse error in POST /orders/batch_cancel: {}", e.what());
857 } catch (const json::exception& e) {
858 abandonPending(http);
859 res->writeStatus("400 Bad Request")
860 ->writeHeader("Content-Type", "application/json")
861 ->end(json({
862 {"error", "INVALID_ARGUMENT"},
863 {"message", std::string("Missing or invalid field: ") + e.what()}
864 }).dump());
865 LOG_ERROR("JSON field error in POST /orders/batch_cancel: {}", e.what());
866 } catch (const std::exception& e) {
867 abandonPending(http);
868 res->writeStatus("500 Internal Server Error")
869 ->writeHeader("Content-Type", "application/json")
870 ->end(json({
871 {"error", "INTERNAL_ERROR"},
872 {"message", std::string("Unexpected error: ") + e.what()}
873 }).dump());
874 LOG_ERROR("Unexpected error in POST /orders/batch_cancel: {}", e.what());
875 }
876 });
877}
878
879void CoinbaseRestOrderGateway::handle_edit_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
880 auto [authenticated, user_id, error_response] = authenticate(req);
881 if (!authenticated) {
882 res->writeStatus("401 Unauthorized")
883 ->writeHeader("Content-Type", "application/json")
884 ->end(error_response);
885 return;
886 }
887
888 auto request_data = std::make_shared<PostRequestData>();
889 request_data->user_id = std::move(user_id);
890
891 res->onAborted([request_data]() {
892 LOG_WARN("HTTP connection aborted during POST /api/v3/brokerage/orders/edit");
893 });
894
895 res->onData([this, res, request_data](std::string_view chunk, bool is_last) mutable {
896 request_data->body_buffer.append(chunk);
897 if (!is_last) return;
898
899 try {
900 json request_body = json::parse(request_data->body_buffer);
901 std::string order_id = request_body["order_id"];
902 std::string user_id = request_data->user_id;
903
904 // Drain unread reports before looking up routing, as in the cancel path.
905 drainResponses();
906
907 auto sym_it = order_id_to_symbol_.find(order_id);
908 if (sym_it == order_id_to_symbol_.end()) {
909 res->writeStatus("400 Bad Request")
910 ->writeHeader("Content-Type", "application/json")
911 ->end(json({
912 {"success", false},
913 {"errors", json::array({{{"edit_failure_reason", "UNKNOWN_ORDER"}}})}
914 }).dump());
915 LOG_WARN("edit_order: unknown order_id={}", order_id);
916 return;
917 }
918 const std::string& symbol = sym_it->second;
919
920 price_t new_price = NULL_PRICE;
921 qty_t new_qty = 0;
922 if (request_body.contains("price")) {
923 new_price = to_price_t(std::stod(request_body["price"].get<std::string>()));
924 }
925 if (request_body.contains("size")) {
926 new_qty = to_qty_t(std::stod(request_body["size"].get<std::string>()));
927 }
928
929 // Validate modified price/qty against product specs before queuing
930 if (new_price != NULL_PRICE || new_qty != 0) {
931 const OrderType ot = (new_price != NULL_PRICE) ? OrderType::LIMIT : OrderType::MARKET;
932 const double price_d = (new_price != NULL_PRICE) ? to_price_double(new_price) : 0.0;
933 const double qty_d = (new_qty != 0) ? to_qty_double(new_qty) : 0.0;
934 auto vr = validate_order(symbol, price_d, qty_d, ot);
935 if (!vr.valid) {
936 res->writeStatus("400 Bad Request")
937 ->writeHeader("Content-Type", "application/json")
938 ->end(json({
939 {"success", false},
940 {"errors", json::array({{{"edit_failure_reason", vr.error_type}}})}
941 }).dump());
942 LOG_ERROR("Edit order rejected (validation): user={}, order_id={}, reason={}",
943 user_id, order_id, vr.error_details);
944 return;
945 }
946 }
947
948 uint64_t response_read_index = response_queue_.initial_reading_index();
949
950 auto request_index = request_queue_.reserve();
951 auto* request = request_queue_[request_index];
952 request->time_stamp = utils::get_current_time_ns();
953 utils::copy_wire_field(request->symbol, symbol);
954 request->msg_type = MessageType::ORDER_REPLACE_REQUEST;
955
956 std::memset(&request->modify_order, 0, sizeof(request->modify_order));
957 utils::copy_wire_field(request->modify_order.user_id, user_id);
958 utils::copy_wire_field(request->modify_order.order_id, order_id);
959 request->modify_order.new_price = new_price;
960 request->modify_order.new_qty = new_qty;
961
962 request_queue_.publish(request_index);
963 LOG_INFO("Published edit request: user={}, order_id={}, symbol={}", user_id, order_id, symbol);
964
965 // Wait briefly for a reject. No response within timeout means success.
966 constexpr int timeout_ms = 200;
967 constexpr int poll_interval_us = 100;
969 auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
970
971 std::string client_order_id;
972 while (std::chrono::steady_clock::now() < deadline) {
973 auto [data, size] = response_queue_.read(response_read_index);
974 if (data != nullptr) {
975 if (std::string(data->user_id) == user_id && data->request_time == request->time_stamp) {
976 if (data->order_status == OrderStatus::REJECTED) {
977 reject_reason = data->reject_reason;
978 }
979 else {
980 reject_reason = OrdRejectReason::NONE;
981 }
982 client_order_id = data->client_order_id;
983 break;
984 }
985 }
986 std::this_thread::sleep_for(std::chrono::microseconds(poll_interval_us));
987 }
988
989 if (reject_reason != OrdRejectReason::NONE) {
990 res->writeStatus("400 Bad Request")
991 ->writeHeader("Content-Type", "application/json")
992 ->end(json({
993 {"success", false},
994 {"errors", json::array({{{"edit_failure_reason", to_string(reject_reason)}}})}
995 }).dump());
996 LOG_ERROR("Edit order rejected: user={}, order_id={}, reason={}", user_id, order_id, to_string(reject_reason));
997 } else {
998 res->writeStatus("200 OK")
999 ->writeHeader("Content-Type", "application/json")
1000 ->end(json({
1001 {"success", true},
1002 {"errors", json::array()}
1003 }).dump());
1004 LOG_INFO("Edit order succeeded: user={}, order_id={}, client_order_id={}", user_id, order_id, client_order_id);
1005 }
1006
1007 } catch (const json::parse_error& e) {
1008 res->writeStatus("400 Bad Request")
1009 ->writeHeader("Content-Type", "application/json")
1010 ->end(json({
1011 {"error", "INVALID_REQUEST"},
1012 {"message", std::string("Invalid JSON: ") + e.what()}
1013 }).dump());
1014 LOG_ERROR("JSON parse error in POST /orders/edit: {}", e.what());
1015 } catch (const json::exception& e) {
1016 res->writeStatus("400 Bad Request")
1017 ->writeHeader("Content-Type", "application/json")
1018 ->end(json({
1019 {"error", "INVALID_ARGUMENT"},
1020 {"message", std::string("Missing or invalid field: ") + e.what()}
1021 }).dump());
1022 LOG_ERROR("JSON field error in POST /orders/edit: {}", e.what());
1023 } catch (const std::exception& e) {
1024 res->writeStatus("500 Internal Server Error")
1025 ->writeHeader("Content-Type", "application/json")
1026 ->end(json({
1027 {"error", "INTERNAL_ERROR"},
1028 {"message", std::string("Unexpected error: ") + e.what()}
1029 }).dump());
1030 LOG_ERROR("Unexpected error in POST /orders/edit: {}", e.what());
1031 }
1032 });
1033}
1034
1035void CoinbaseRestOrderGateway::handle_get_transaction_summary(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1036 auto [authenticated, user_id, error_response] = authenticate(req);
1037 if (!authenticated) {
1038 res->writeStatus("401 Unauthorized")
1039 ->writeHeader("Content-Type", "application/json")
1040 ->end(error_response);
1041 return;
1042 }
1043
1044 auto rsp = Http::get("https://api.coinbase.com/api/v3/brokerage/transaction_summary", {
1045 {"Authorization", "Bearer " + ::coinbase::generate_coinbase_jwt("GET api.coinbase.com/api/v3/brokerage/transaction_summary")}
1046 });
1047 res->writeStatus(std::to_string(rsp.result_code) + " " + rsp.reason)
1048 ->writeHeader("Content-Type", "application/json")
1049 ->end(rsp.result_text);
1050}
std::tuple< bool, std::string, std::string > authenticate(uWS::HttpRequest *req)
void stop() override
Closes the response timer before the base closes the listen socket.
CoinbaseRestOrderGateway(const json &config, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue)
slick::queue< Request > & request_queue_
slick::queue< OrderResponse > & response_queue_
RestWsOrderGateway(Venue venue, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue, uint32_t port)
slick::net::Http Http
nlohmann::json json
Definition order.hpp:16
bool iequals(std::string_view a, std::string_view b) noexcept
ASCII case-insensitive compare, used for every venue-name lookup.
Definition types.hpp:117
@ Learn
The order exists: remember which symbol its id belongs to.
@ Forget
The order is gone: drop its routing.
std::string dump_json(const json &value)
nlohmann's dump() throws on invalid UTF-8.
constexpr RoutingEffect routing_effect(OrderStatus status)
Terminal reports retire routing.
bool copy_wire_field(char(&dst)[N], std::string_view src) noexcept
Copies a name into a fixed-width wire field.
uint64_t get_current_time_ns()
Definition timestamp.hpp:93
constexpr price_t NULL_PRICE
Definition types.hpp:28
constexpr double to_price_double(price_t price)
Definition types.hpp:46
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
constexpr const char * to_string(FeedState state) noexcept
int_fast64_t qty_t
Definition types.hpp:22
constexpr qty_t to_qty_t(double qty)
Definition types.hpp:50
constexpr double to_qty_double(qty_t qty)
Definition types.hpp:54
int_fast64_t price_t
Definition types.hpp:21
OrdRejectReason reject_reason
Definition messages.hpp:312
uint64_t request_tag
request_tag of the request this response answers, or for a response no request triggered (a passive f...
Definition messages.hpp:324