1#include <slick/logger.hpp>
3#include <coinbase/auth.hpp>
11using Http = slick::net::Http;
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;
22struct PostRequestData {
23 std::string body_buffer;
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));
44bool matches_order_status(std::string_view filter,
OrderStatus status)
noexcept {
65 , response_cursor_(response_queue.initial_reading_index())
66 , response_poll_ms_(config.value(
"response_poll_ms", 1))
68 if (config.contains(
"initial_products")) {
69 products_ = config[
"initial_products"].get<std::string>();
71 auto base_url = config.value(
"base_url",
"https://api.coinbase.com");
72 auto rsp = Http::get(base_url +
"/api/v3/brokerage/market/products");
74 products_ = rsp.result_text;
76 LOG_WARN(
"Failed to get products. error: {}", rsp.result_text);
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>();
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"),
93 product_by_id_[product_id] = prod.dump();
98void CoinbaseRestOrderGateway::on_listen_socket(us_listen_socket_t *) {
104 LOG_INFO(
"Coinbase REST response poll ready ({} ms)", response_poll_ms_);
107void CoinbaseRestOrderGateway::armResponseTimer() {
108 if (response_timer_ ==
nullptr || response_timer_armed_) {
111 response_timer_armed_ =
true;
114 [](us_timer_t *timer) {
116 self->response_timer_armed_ =
false;
117 self->drainResponses();
118 self->expireWaiters();
122 if (self->pending_.size() != 0 || !self->timed_waiters_.empty() ||
123 !self->expected_reports_.empty()) {
124 self->armResponseTimer();
127 std::max(1, response_poll_ms_), 0);
131 if (
loop_ !=
nullptr && response_timer_ !=
nullptr) {
132 us_timer_t *timer = response_timer_;
133 response_timer_ =
nullptr;
134 response_timer_armed_ =
false;
136 loop_->defer([timer]() { us_timer_close(timer); });
141void CoinbaseRestOrderGateway::track(
PendingResponses::Id id, std::chrono::milliseconds timeout) {
142 timed_waiters_.push_back({id, std::chrono::steady_clock::now() + timeout});
146 std::erase_if(timed_waiters_, [
id](
const TimedWaiter &waiter) {
return waiter.id == id; });
149void CoinbaseRestOrderGateway::abandonPending(
const std::shared_ptr<PendingHttp> &http) {
150 for (
const auto id : http->ids) {
151 pending_.abandon(
id);
159void CoinbaseRestOrderGateway::expectReport(uint64_t tag) {
162 expected_reports_.push_back({tag, std::chrono::steady_clock::now() + std::chrono::seconds(5)});
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);
173 for (
const auto id : due) {
177 std::erase_if(expected_reports_,
178 [now](
const ExpectedReport &expected) {
return expected.deadline <= now; });
181void CoinbaseRestOrderGateway::drainResponses() {
184 if (data ==
nullptr) {
187 const auto &response = *data;
188 orders_.apply(response);
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;
201 const std::string_view order_id(response.order_id,
202 strnlen(response.order_id,
sizeof(response.order_id)));
203 if (!order_id.empty()) {
206 order_id_to_symbol_.erase(std::string(order_id));
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);
221 pending_.dispatch(response);
226 std::chrono::milliseconds timeout,
227 const std::shared_ptr<PendingHttp> &http,
228 std::function<
void(
const OrderResponse *)> on_report) {
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) {
234 if (!http->aborted) {
239 http->ids.push_back(
id);
247 std::string_view auth_header = req->getHeader(
"authorization");
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"})");
259 if (auth_header.starts_with(
"Bearer ")) {
260 token = std::string(auth_header.substr(7));
262 return std::make_tuple(
false,
"", R
"({"error":"UNAUTHORIZED","message":"Invalid auth token"})");
266 auto decoded = jwt::decode<jwt::traits::nlohmann_json>(token);
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,
"");
273 }
catch (
const std::exception& ) {
274 return std::make_tuple(
false,
"", R
"({"error":"UNAUTHORIZED","message":"Invalid token"})");
278CoinbaseRestOrderGateway::OrderValidationResult
279CoinbaseRestOrderGateway::validate_order(
280 const std::string& product_id,
double price_d,
double qty_d,
OrderType order_type)
const
282 auto it = product_specs_.find(product_id);
283 if (it == product_specs_.end()) {
284 return {
false,
"INVALID_PRODUCT_ID",
"Unknown product: " + product_id};
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;
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)};
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)};
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)};
312 return {
true, {}, {}};
330void CoinbaseRestOrderGateway::setup_routes(uWS::App &app) {
331 app.get(
"/api/v3/brokerage/market/products", [
this](
auto *res,
auto *) {
332 res->writeHeader(
"Content-Type",
"application/json")->end(products_);
333 }).get(
"/api/v3/brokerage/products", [
this](
auto *res,
auto *) {
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);
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);
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"})");
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);
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"));
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"})");
392 limit =
static_cast<size_t>(parsed);
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()) {
409 if (!order_status.empty() && !matches_order_status(order_status, order->status)) {
412 if (orders.size() >= limit) {
422 {
"orders", std::move(orders)},
428 res->writeHeader(
"Content-Type",
"application/json")
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);
441 auto request_data = std::make_shared<PostRequestData>();
442 request_data->user_id = std::move(user_id);
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");
456 res->onData([
this, res, request_data, http](std::string_view chunk,
bool is_last)
mutable {
459 request_data->body_buffer.append(chunk);
467 json request_body = json::parse(request_data->body_buffer);
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;
476 auto& order_config = request_body[
"order_configuration"];
484 if (order_config.contains(
"limit_limit_gtc")) {
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>()));
492 else if (order_config.contains(
"market_market_ioc")) {
495 auto& cfg = order_config[
"market_market_ioc"];
496 qty =
to_qty_t(std::stod(cfg[
"base_size"].get<std::string>()));
498 else if (order_config.contains(
"sor_limit_ioc")) {
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>()));
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>()));
511 if (cfg.contains(
"limit_price")) {
513 price =
to_price_t(std::stod(cfg[
"limit_price"].get<std::string>()));
518 else if (order_config.contains(
"limit_limit_fok")) {
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>()));
529 json response_json = {
532 {
"message",
"Unsupported order_configuration type"},
533 {
"error_details",
"Unsupported order_configuration type"},
534 {
"new_order_failure_reason",
"Unsupported order_configuration type"}
538 res->writeStatus(
"400 Bad Request")
539 ->writeHeader(
"Content-Type",
"application/json")
540 ->end(response_json.dump());
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());
553 auto vr = validate_order(product_id, price_d, qty_d, order_type);
555 json response_json = {
558 {
"message", vr.error_type},
559 {
"error_details", vr.error_details},
560 {
"new_order_failure_reason", vr.error_type}
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);
574 const uint64_t tag = ++next_request_tag_;
582 request->request_tag = tag;
589 LOG_WARN(
"client_order_id truncated to fit into fixed size buffer: original='{}', truncated='{}'", client_order_id, request->add_order.client_order_id);
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;
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,
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);
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 = {
633 {
"message", to_string(matched_response->reject_reason)},
634 {
"error_details", error_msg},
635 {
"new_order_failure_reason", to_string(matched_response->reject_reason)}
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={}",
646 json response_json = {
648 {
"success_response", {
649 {
"order_id", matched_response->
order_id},
650 {
"product_id", product_id},
652 {
"client_order_id", client_order_id}
654 {
"order_configuration", order_config}
656 res->writeStatus(
"200 OK")
657 ->writeHeader(
"Content-Type",
"application/json")
658 ->end(response_json.dump());
660 LOG_INFO(
"Order processed successfully: user={}, client_order_id={}, order_id={}, status={}",
666 }
catch (
const json::parse_error& e) {
667 abandonPending(http);
668 res->writeStatus(
"400 Bad Request")
669 ->writeHeader(
"Content-Type",
"application/json")
671 {
"error",
"INVALID_REQUEST"},
672 {
"message", std::string(
"Invalid JSON: ") + e.what()}
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")
680 {
"error",
"INVALID_ARGUMENT"},
681 {
"message", std::string(
"Missing or invalid field: ") + e.what()}
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")
689 {
"error",
"INTERNAL_ERROR"},
690 {
"message", std::string(
"Unexpected error: ") + e.what()}
692 LOG_ERROR(
"Unexpected error in POST /orders: {}", e.what());
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);
706 auto request_data = std::make_shared<PostRequestData>();
707 request_data->user_id = std::move(user_id);
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");
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;
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;
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"})");
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);
747 std::string order_id;
752 uWS::HttpResponse<false>* res;
753 std::vector<CancelEntry> entries;
758 bool finished =
false;
760 auto batch = std::make_shared<Batch>(Batch{res, {}, 0, user_id,
false});
761 batch->entries.reserve(order_ids_json.size());
763 auto finish = [
this, batch]() {
764 if (batch->finished) {
767 batch->finished =
true;
768 json results = json::array();
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}});
777 results.push_back({{
"success",
false},
778 {
"failure_reason",
to_string(entry.reject_reason)},
779 {
"order_id", entry.order_id}});
781 results.push_back({{
"success",
true}, {
"failure_reason",
""}, {
"order_id", entry.order_id}});
782 order_id_to_symbol_.erase(entry.order_id);
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);
801 for (
auto& oid_json : order_ids_json) {
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});
811 const std::string symbol = sym_it->second;
812 const uint64_t tag = ++next_request_tag_;
817 request->request_tag = tag;
821 std::memset(&request->cancel_order, 0,
sizeof(request->cancel_order));
829 LOG_INFO(
"Submitted cancel request: user={}, order_id={}, symbol={}, tag={}", user_id, order_id, symbol, tag);
833 const size_t index = batch->entries.size() - 1;
834 awaitReport(tag, std::chrono::milliseconds(500), http,
835 [batch, index, finish](
const OrderResponse *response) {
837 batch->entries[index].reject_reason = response->
reject_reason;
839 if (--batch->remaining == 0) {
845 if (batch->remaining == 0) {
848 }
catch (
const json::parse_error& e) {
849 abandonPending(http);
850 res->writeStatus(
"400 Bad Request")
851 ->writeHeader(
"Content-Type",
"application/json")
853 {
"error",
"INVALID_REQUEST"},
854 {
"message", std::string(
"Invalid JSON: ") + e.what()}
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")
862 {
"error",
"INVALID_ARGUMENT"},
863 {
"message", std::string(
"Missing or invalid field: ") + e.what()}
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")
871 {
"error",
"INTERNAL_ERROR"},
872 {
"message", std::string(
"Unexpected error: ") + e.what()}
874 LOG_ERROR(
"Unexpected error in POST /orders/batch_cancel: {}", e.what());
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);
888 auto request_data = std::make_shared<PostRequestData>();
889 request_data->user_id = std::move(user_id);
891 res->onAborted([request_data]() {
892 LOG_WARN(
"HTTP connection aborted during POST /api/v3/brokerage/orders/edit");
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;
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;
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")
913 {
"errors", json::array({{{
"edit_failure_reason",
"UNKNOWN_ORDER"}}})}
915 LOG_WARN(
"edit_order: unknown order_id={}", order_id);
918 const std::string& symbol = sym_it->second;
922 if (request_body.contains(
"price")) {
923 new_price =
to_price_t(std::stod(request_body[
"price"].get<std::string>()));
925 if (request_body.contains(
"size")) {
926 new_qty =
to_qty_t(std::stod(request_body[
"size"].get<std::string>()));
930 if (new_price !=
NULL_PRICE || new_qty != 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);
936 res->writeStatus(
"400 Bad Request")
937 ->writeHeader(
"Content-Type",
"application/json")
940 {
"errors", json::array({{{
"edit_failure_reason", vr.error_type}}})}
942 LOG_ERROR(
"Edit order rejected (validation): user={}, order_id={}, reason={}",
943 user_id, order_id, vr.error_details);
948 uint64_t response_read_index =
response_queue_.initial_reading_index();
956 std::memset(&request->modify_order, 0,
sizeof(request->modify_order));
959 request->modify_order.new_price = new_price;
960 request->modify_order.new_qty = new_qty;
963 LOG_INFO(
"Published edit request: user={}, order_id={}, symbol={}", user_id, order_id, symbol);
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);
971 std::string client_order_id;
972 while (std::chrono::steady_clock::now() < deadline) {
974 if (data !=
nullptr) {
975 if (std::string(data->user_id) == user_id && data->request_time == request->time_stamp) {
977 reject_reason = data->reject_reason;
982 client_order_id = data->client_order_id;
986 std::this_thread::sleep_for(std::chrono::microseconds(poll_interval_us));
990 res->writeStatus(
"400 Bad Request")
991 ->writeHeader(
"Content-Type",
"application/json")
994 {
"errors", json::array({{{
"edit_failure_reason",
to_string(reject_reason)}}})}
996 LOG_ERROR(
"Edit order rejected: user={}, order_id={}, reason={}", user_id, order_id,
to_string(reject_reason));
998 res->writeStatus(
"200 OK")
999 ->writeHeader(
"Content-Type",
"application/json")
1002 {
"errors", json::array()}
1004 LOG_INFO(
"Edit order succeeded: user={}, order_id={}, client_order_id={}", user_id, order_id, client_order_id);
1007 }
catch (
const json::parse_error& e) {
1008 res->writeStatus(
"400 Bad Request")
1009 ->writeHeader(
"Content-Type",
"application/json")
1011 {
"error",
"INVALID_REQUEST"},
1012 {
"message", std::string(
"Invalid JSON: ") + e.what()}
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")
1019 {
"error",
"INVALID_ARGUMENT"},
1020 {
"message", std::string(
"Missing or invalid field: ") + e.what()}
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")
1027 {
"error",
"INTERNAL_ERROR"},
1028 {
"message", std::string(
"Unexpected error: ") + e.what()}
1030 LOG_ERROR(
"Unexpected error in POST /orders/edit: {}", e.what());
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);
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")}
1047 res->writeStatus(std::to_string(rsp.result_code) +
" " + rsp.reason)
1048 ->writeHeader(
"Content-Type",
"application/json")
1049 ->end(rsp.result_text);
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_
static constexpr Id kNoId
RestWsOrderGateway(Venue venue, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue, uint32_t port)
bool iequals(std::string_view a, std::string_view b) noexcept
ASCII case-insensitive compare, used for every venue-name lookup.
@ Learn
The order exists: remember which symbol its id belongs to.
@ Forget
The order is gone: drop its routing.
@ Ignore
Says nothing about 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.
json to_json(const Order &order)
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()
constexpr price_t NULL_PRICE
constexpr double to_price_double(price_t price)
constexpr price_t to_price_t(double price)
Scales a decimal into the fixed-point representation, rounding to the nearest tick rather than trunca...
constexpr const char * to_string(FeedState state) noexcept
constexpr qty_t to_qty_t(double qty)
constexpr double to_qty_double(qty_t qty)
OrdRejectReason reject_reason
uint64_t request_tag
request_tag of the request this response answers, or for a response no request triggered (a passive f...