diff --git a/src/lib/orderman/ccapi/CCAPIDeribitOrderMux.cpp b/src/lib/orderman/ccapi/CCAPIDeribitOrderMux.cpp index 6adb4e1a2..1adc7efac 100644 --- a/src/lib/orderman/ccapi/CCAPIDeribitOrderMux.cpp +++ b/src/lib/orderman/ccapi/CCAPIDeribitOrderMux.cpp @@ -61,7 +61,7 @@ class OrderEventHandler : public ccapi::EventHandler { bool interested = event_types.find(event.getType()) != event_types.end(); LOG(OrderMan, Info, "CCAPIDeribitOrderMux::OrderEventHandler::processEvent tid: {} " - "processing: {} " + "interested: {} " "event: {}", os::get_thread_id(), interested, event.toStringPretty(2, 2)); if (interested) @@ -70,6 +70,37 @@ class OrderEventHandler : public ccapi::EventHandler { } }; +// Helper with corrid generation and parsing +struct CorrIDHelper { + const std::string create_order_prefix = "NewOrder"; + const char delim = ':'; + std::string get_create_order_corrid( + OrderKey ok, const std::string &deribit_sec_name) { + return create_order_prefix + delim + std::to_string(ok.value()) + delim + + deribit_sec_name; + } + std::vector split_string(const std::string &str, char delim) { + // vector of string to save tokens + std::vector tokens = {}; + // stringstream class check1 + std::stringstream check1(str); + std::string intermediate; + while (getline(check1, intermediate, delim)) { + tokens.push_back(intermediate); + } + return tokens; + } + std::optional parse_create_order_corrid( + const std::string &corrid) { + auto tokens = split_string(corrid, delim); + if (tokens.size() == 3 && tokens.at(0) == create_order_prefix) { + std::string ok_str = tokens.at(1); + return OrderKey(std::stoi(ok_str)); + } + return std::nullopt; + } +}; + // Struct to organize the periodic requesting or positons and orders struct PositionOrderRequestHelper { struct PosData { @@ -149,6 +180,7 @@ struct CCAPIDeribitOrderMux::PImpl { CCAPIConnectionConfig::DeribitConnectionConfig d_conn_config; const std::string missing_corrid_placeholder = "MISSING_CORRID"; PositionOrderRequestHelper pos_ord_req_helper = {}; + CorrIDHelper corrid_helper = {}; md::SecurityOracle sec_oracle; ccapi::Session *session = nullptr; OnCCAPIOrderUpdate order_update_cb; @@ -203,6 +235,56 @@ CCAPIDeribitOrderMux::CCAPIDeribitOrderMux( CCAPIDeribitOrderMux::~CCAPIDeribitOrderMux() {} +// The CCAPI interaction wrt public requests, private requests and subscription +// is as follows +// Requests: +// --------- +// 1. +// New Order (_send_order function): Builtin Request::Operation::CREATE_ORDER +// 2. +// Modify Order (update_order): Private Request::Operation::GENERIC_PRIVATE_REQUEST +// since could not find a ccapi built in modify operator +// 3. +// Cancel Order (cancel_order): Builtin Request::Operation::CANCEL_ORDER +// 4. +// Query Position (query_postion): Private Request::Operation::GENERIC_PRIVATE_REQUEST. +// There is a builtin Request::Operation::GET_ACCOUNT_POSITIONS but it didnt work +// 5. +// Query Open Orders (query_open_orders): Private Request::Operation::GENERIC_PRIVATE_REQUEST +// similiar to above, there is a builtin GET_OPEN_ORDERS which did not work +// 6. +// RFQ: Private Request::Operation::GENERIC_PRIVATE_REQUEST, +// Subscriptions: +// ------------- +// 1. +// Orders per instrument: +// CCAPI_EM_ORDER_UPDATE +// 2. +// Trades per instrument +// CCAPI_EM_PRIVATE_TRADE + +// The event types we get are: +// ✖ UNKNOWN, +// Every subscription has a session, the message type associated is +// SESSION_CONNECTION_UP or SESSION_CONNECTION_DOWN. It recconects +// automatically so we dont take any action +// ✖ SESSION_STATUS, +// Every subscription has a status, the message type associated is +// SUBSCRIPTION_STARTED or SUBSCRIPTION_FAILURE. We only send orders +// once we get a SUBSCRIPTION_STATUS event with message type SUBSCRIPTION_STARTED. +// We do NOT detect SUBSCRIPTION_FAILURE and retry +// ✔ SUBSCRIPTION_STATUS, +// REQUEST_STATUS, +// This a 'response' to a request. The type of Message tells which request, ex +// CREATE_ORDER, CANCEL_ORDER etc +// ✔ RESPONSE, +// As the name says. We have 2 kinds of subscription data (since we have 2 subscriptions) +// EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE and EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE +// ✔ SUBSCRIPTION_DATA, +// ✖ AUTHORIZATION_STATUS, +// ✖ FIX, +// ✖ FIX_STATUS, + CCAPIOpResult CCAPIDeribitOrderMux::launch_new_order( const CreateOrderMsg &cr_msg) { // order update subscription @@ -559,10 +641,11 @@ void CCAPIDeribitOrderMux::_subscribe_to_order_callbacks() { me->session->subscribe(sub); } +// There are only 3 types of events we handle void CCAPIDeribitOrderMux::_handle_event(const ccapi::Event &event) { ccapi::Event::Type event_type = event.getType(); bts_assert( - event_type == ccapi::Event::Type::RESPONSE || //response to a request + event_type == ccapi::Event::Type::RESPONSE || event_type == ccapi::Event::Type::SUBSCRIPTION_DATA || event_type == ccapi::Event::Type::SUBSCRIPTION_STATUS); auto get_corr_id = [&](const ccapi::Message &msg, size_t idx) { @@ -642,6 +725,33 @@ void CCAPIDeribitOrderMux::_handle_element( // orders break; } + case ccapi::Message::Type::RESPONSE_ERROR: { + auto key = me->corrid_helper.parse_create_order_corrid(corr_id); + if (key == std::nullopt) { + return; + } + LOG(OrderMan, Error, + "CCAPIDeribitOrderMux::_handle_element order entry error key: {}", + key->value()); + auto it = me->order_map.find(OrderKey(key->value())); + if (it == me->order_map.end()) { + LOG(OrderMan, Error, + "CCAPIDeribitOrderMux::_handle_element order entry error, " + "Could not find key: " + "{}", + key->value()); + return; + } + auto err = CCAPICreateOrderErrorMsg::parse(element, corr_id); + if (err == std::nullopt) { + LOG(OrderMan, Error, + "CCAPIDeribitOrderMux::_handle_element order entry error, " + "Could not parse message: {}", + key->value()); + } + it->second.handle_create_error(err.value()); + break; + } case ccapi::Message::Type::REQUEST_FAILURE: { } default: @@ -686,16 +796,16 @@ void CCAPIDeribitOrderMux::_send_order(const CreateOrderMsg &cr_msg) { ccapi::Request request( ccapi::Request::Operation::CREATE_ORDER, CCAPI_EXCHANGE_NAME_DERIBIT, sec_desc); - std::string corr_id = "NewOrder:" + std::to_string(cr_msg.key.value()) + - ":" + - (cr_msg.security == nullptr - ? "NOSEC" - : cr_msg.security->deribit().security_desc()); + std::string corrid = me->corrid_helper.get_create_order_corrid( + cr_msg.key, (cr_msg.security == nullptr + ? "NOSEC" + : cr_msg.security->deribit().security_desc())); me->order_map.insert( {cr_msg.key, CCAPISingleOrderManager( - *cr_msg.security, cr_msg.key, corr_id, cr_msg.side, + *cr_msg.security, cr_msg.key, corrid, cr_msg.side, cr_msg.price.value(), cr_msg.quantity.full_value())}); - request.setCorrelationId(corr_id); + request.setCorrelationId(corrid); + // TODO, TimeInForce request.appendParam( {{CCAPI_EM_ORDER_SIDE, cr_msg.side == api::SIDE_BUY ? CCAPI_EM_ORDER_SIDE_BUY diff --git a/src/lib/orderman/ccapi/CCAPIOrderCallbackMsgs.h b/src/lib/orderman/ccapi/CCAPIOrderCallbackMsgs.h index a56a05637..62f9b64d8 100644 --- a/src/lib/orderman/ccapi/CCAPIOrderCallbackMsgs.h +++ b/src/lib/orderman/ccapi/CCAPIOrderCallbackMsgs.h @@ -1,5 +1,6 @@ #pragma once +#include "ccapi_cpp/ccapi_message.h" #include "ccapi_cpp/ccapi_session.h" #include "lib/api/services/OrderService.pb.h" #include "lib/domain_model/Security.pb.h" @@ -8,12 +9,15 @@ #include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/utils/PBUtils.h" #include "lib/utils/bts_assert.h" +#include #include #include #include #include #include +#include #include +#include using namespace std; namespace bts::orderman { @@ -42,7 +46,7 @@ bts::api::orderman::OrderStatus convert_ccapi_status(const std::string &status); // ORDER_ID = 16257763986, // QUANTITY = 10.0, // SIDE = BUY, -// STATUS = open +// STATUS = openis_position_cb // } // ] // ], @@ -79,6 +83,46 @@ struct CCAPICreateOrderMsg { status(convert_ccapi_status(getm(map, CCAPI_EM_ORDER_STATUS))), corr_id(corr_id) {} }; + +// Event [ +// type = RESPONSE, +// messageList = [ +// Message [ +// type = RESPONSE_ERROR, +// recapType = UNKNOWN, +// time = 1970-01-01T00:00:00.000000000Z, +// timeReceived = 2023-05-19T14:16:37.229712920Z, +// elementList = [ +// Element [ +// nameValueMap = { +// ERROR_MESSAGE = {"jsonrpc":"2.0","id":1684505797121182092,"error":{"message":"Invalid params","data":{"reason": +// "positive float required","param":"price"},"code":-32602},"usIn":1684505797179014,"usOut":1684505797179346,"usDiff":332,"test +// net":true}, +// HTTP_STATUS_CODE = 400 +// } +// ] +// ], +// correlationIdList = [ NewOrder:655008:BTC-20MAY23-24500-P ] +// ] +// ] +// ] + +struct CCAPICreateOrderErrorMsg { + std::string corrid; + std::string error; + static std::optional parse( + const ccapi::Element &element, const std::string &corrid) { + const auto &nv_map = element.getNameValueMap(); + auto it = nv_map.find(CCAPI_ERROR_MESSAGE); + if (it == nv_map.end()) + return std::nullopt; + nlohmann::json main_pl = nlohmann::json::parse(it->second); + const auto &error_msg = main_pl.at("error"); + CCAPICreateOrderErrorMsg rv = {corrid, error_msg.dump()}; + return rv; + } +}; + // 2. // Event [ // type = SUBSCRIPTION_DATA, diff --git a/src/lib/orderman/ccapi/CCAPIOrderState.h b/src/lib/orderman/ccapi/CCAPIOrderState.h index 392c8e275..c421f8f49 100644 --- a/src/lib/orderman/ccapi/CCAPIOrderState.h +++ b/src/lib/orderman/ccapi/CCAPIOrderState.h @@ -39,6 +39,7 @@ struct CCAPIOrderState { // these are statistics of incoming an outgoing messages respectively size_t n_cbs = 0; size_t n_outgoing_mods = 0; + std::string msg; void add_trade(const CCAPITradeMsg &t, bool update_fill_state = true) { cb_trades.push_back(t); diff --git a/src/lib/orderman/ccapi/CCAPISingleOrderManager.cpp b/src/lib/orderman/ccapi/CCAPISingleOrderManager.cpp index fbf406e24..7ef49fedd 100644 --- a/src/lib/orderman/ccapi/CCAPISingleOrderManager.cpp +++ b/src/lib/orderman/ccapi/CCAPISingleOrderManager.cpp @@ -53,6 +53,7 @@ struct TerminalMessage { api::orderman::OrderStatus::ORDER_STATUS_INACTIVE; double final_accumulated_qty = os::nan(); double final_avg_filled_price = os::nan(); + std::string msg; void update(const CCAPICreateOrderMsg &cr_msg) { bts_assert(!terminated()); status = cr_msg.status; @@ -67,6 +68,14 @@ struct TerminalMessage { final_avg_filled_price = ou_msg.cumm_filled_price; bts_assert(terminated()); } + void update(const CCAPICreateOrderErrorMsg &err_msg) { + bts_assert(!terminated()); + final_accumulated_qty = 0.0; + final_avg_filled_price = os::nan(); + msg = err_msg.error; + status = api::orderman::ORDER_STATUS_ERROR; + bts_assert(terminated()); + } bool terminated() const { return orderman::in_terminal_state(status); } }; @@ -156,26 +165,41 @@ void CCAPISingleOrderManager::handle_create_reponse( } break; case State::WORKING: - if (me->order.cc_order_key == create_order_msg.order_id) - LOG(OrderMan, Error, - "CCAPISingleOrderManager::handle_create ok: {} state: {}", - me->order.order_key, _state_msg(me->state)); - break; case State::END_WAITING_FOR_FILLS: - if (me->order.cc_order_key == create_order_msg.order_id) - LOG(OrderMan, Error, - "CCAPISingleOrderManager::handle_create ok: {} state: {}", - me->order.order_key, _state_msg(me->state)); - break; case State::END: if (me->order.cc_order_key == create_order_msg.order_id) LOG(OrderMan, Error, - "CCAPISingleOrderManager::handle_create ok: {} state: {}", + "CCAPISingleOrderManager::handle_create ok: {} state: {} Invalid " + "Statemachine", me->order.order_key, _state_msg(me->state)); break; } } +void CCAPISingleOrderManager::handle_create_error( + const CCAPICreateOrderErrorMsg &create_order_error_msg) { + LOG(OrderMan, Error, + "CCAPISingleOrderManager ok: {} ::handle_create_error corr_id: {} " + "cc_order_key: {} state: {} error_msg: {}", + me->order.order_key, me->order.cc_create_corr_id, me->order.cc_order_key, + _state_msg(me->state), create_order_error_msg.error); + switch (me->state) { + case State::WAITING_FOR_ID: + me->ter_msg.update(create_order_error_msg); + _go_to_end_state(); + break; + case State::WORKING: + case State::END_WAITING_FOR_FILLS: + case State::END: + LOG(OrderMan, Error, + "CCAPISingleOrderManager ok: {} ::handle_create_error corr_id: " + "{} cc_order_key: {} state: {} Invalid Statemachine", + me->order.order_key, me->order.cc_create_corr_id, + me->order.cc_order_key, _state_msg(me->state)); + break; + } +} + void CCAPISingleOrderManager::handle_order_sub_update( const CCAPIOrderUpdateMsg &order_update_msg) { if (!_relevent_update(order_update_msg.order_id)) @@ -267,6 +291,7 @@ void CCAPISingleOrderManager::_switch_state(State new_state) { void CCAPISingleOrderManager::_go_to_end_state() { bts_assert(me->ter_msg.terminated()); + me->order.msg = me->ter_msg.msg; me->order.status = me->ter_msg.status; _switch_state(State::END); } diff --git a/src/lib/orderman/ccapi/CCAPISingleOrderManager.h b/src/lib/orderman/ccapi/CCAPISingleOrderManager.h index 45145dd84..68059e9af 100644 --- a/src/lib/orderman/ccapi/CCAPISingleOrderManager.h +++ b/src/lib/orderman/ccapi/CCAPISingleOrderManager.h @@ -10,6 +10,7 @@ struct CCAPICreateOrderMsg; struct CCAPIOrderUpdateMsg; struct CCAPITradeMsg; struct CCAPIOrderState; +struct CCAPICreateOrderErrorMsg; // Handles the state management for a single order. The complexity here // is that the @@ -28,6 +29,9 @@ class CCAPISingleOrderManager { // This is a CCAPI standard message in response to a create request. // This should be the first message void handle_create_reponse(const CCAPICreateOrderMsg &create_order_msg); + // Error in creating an order (ex incorrect price) + void handle_create_error( + const CCAPICreateOrderErrorMsg &create_order_error_msg); // This is a CCAPI standard subcription message that we receive when we // subscribe to the instrument orders (CCAPI_EM_ORDER_UPDATE) void handle_order_sub_update(const CCAPIOrderUpdateMsg &order_update_msg); diff --git a/src/lib/orderman/gateways/CCAPIExecutionGateway.cpp b/src/lib/orderman/gateways/CCAPIExecutionGateway.cpp index b64359d48..2cb9486b7 100644 --- a/src/lib/orderman/gateways/CCAPIExecutionGateway.cpp +++ b/src/lib/orderman/gateways/CCAPIExecutionGateway.cpp @@ -64,7 +64,7 @@ api::orderman::NativeOrderStatus native_order_status(const CCAPIOrderState &s) { case api::orderman::OrderStatus::ORDER_STATUS_CANCELED: return api::orderman::NativeOrderStatus::NATIVE_ORDER_STATUS_CANCELED; case api::orderman::OrderStatus::ORDER_STATUS_ERROR: - return api::orderman::NativeOrderStatus::NATIVE_ORDER_STATUS_STOPPED; + return api::orderman::NativeOrderStatus::NATIVE_ORDER_STATUS_REJECTED; case api::orderman::OrderStatus::ORDER_STATUS_DISCONNECTED: return api::orderman::NativeOrderStatus::NATIVE_ORDER_STATUS_UNDEFINED; case api::orderman::OrderStatus::ORDER_STATUS_PENDING_WORKING: @@ -357,6 +357,7 @@ void CCAPIExecutionGateway::_on_order_cb(const CCAPIOrderState &s) { to_array(s.cc_order_key, &er_exch_oid); er.price.value() = s.order_px; er.quantity = s.order_qty; + er.msg = s.msg; // fractional qty // fills er.avg_price.value() = s.avg_filled_price;