From f0464331cb6cee42361852f6570eebabbfebd49f Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Wed, 8 Jul 2020 09:52:18 -0400 Subject: [PATCH] Added better handling of cancel rejects. --- .../orderman/actors/GLBXExecutionGateway.cpp | 8 +- .../actors/GLBXiLink3ExecutionGateway.cpp | 4 +- .../orderman/actors/ICEExecutionGateway.cpp | 2 +- src/lib/orderman/actors/IExecutionGateway.h | 4 +- src/lib/orderman/actors/ilink3/IL3Parser.cpp | 78 +-- src/lib/orderman/actors/ilink3/IL3Parser.h | 3 +- src/lib/orderman/actors/ilink3/ILinkGW.cpp | 453 ++++++++++-------- src/lib/orderman/actors/ilink3/ILinkGW.h | 176 ++++--- .../actors/order_manager/OrderManager.cpp | 5 +- src/lib/orderman/events/CancelRejectEvent.h | 31 +- .../orderman/orderman_utils/CancelReject.h | 22 + src/lib/orderman/orders/GLBXNativeOrder.cpp | 12 +- src/lib/orderman/orders/ICENativeOrder.cpp | 2 +- testing/manual/orders/order_entry.txt | 2 - 14 files changed, 435 insertions(+), 367 deletions(-) create mode 100644 src/lib/orderman/orderman_utils/CancelReject.h diff --git a/src/lib/orderman/actors/GLBXExecutionGateway.cpp b/src/lib/orderman/actors/GLBXExecutionGateway.cpp index 9e9f17908..bd0086939 100644 --- a/src/lib/orderman/actors/GLBXExecutionGateway.cpp +++ b/src/lib/orderman/actors/GLBXExecutionGateway.cpp @@ -284,12 +284,16 @@ void GLBXExecutionGateway::on_cancel_reject( decode_clorid(msg.get(), &ok, &sk); std::string reject_msg; + CancelRejectReason reason = CancelRejectReason::Other; if (msg.has()) reject_msg = msg.get(); - else if (msg.has()) + else if (msg.has()) { + if (msg.get() == 2045) + reason = CancelRejectReason::UnknownOrder; reject_msg = fmt::format("Order cancel was rejected with error code {}", msg.get()); - me->on_cancel_reject(ok, reject_msg); + } + me->on_cancel_reject({ok, reason,reject_msg}); } void GLBXExecutionGateway::on_connection_status_change(bool is_connected) { diff --git a/src/lib/orderman/actors/GLBXiLink3ExecutionGateway.cpp b/src/lib/orderman/actors/GLBXiLink3ExecutionGateway.cpp index 772f41222..daae8319f 100644 --- a/src/lib/orderman/actors/GLBXiLink3ExecutionGateway.cpp +++ b/src/lib/orderman/actors/GLBXiLink3ExecutionGateway.cpp @@ -139,9 +139,9 @@ void GLBXiLink3ExecutionGateway::connect(jetfix::SessionName const &sn) { me->gw.emplace(*me->connection, me->framer, &me->db, me->session_store->starting_session_descriptor(), c, me->cfg); - me->gw->subscribe_cancel_reject([this](auto k, auto const &msg) { + me->gw->subscribe_cancel_reject([this](auto &cr) { bts_assert(me->state == State::READY || me->state == State::CONNECTING); - me->on_cancel_reject(k, msg); + me->on_cancel_reject(cr); }); me->gw->subscribe_execution_reports([this](auto er) { diff --git a/src/lib/orderman/actors/ICEExecutionGateway.cpp b/src/lib/orderman/actors/ICEExecutionGateway.cpp index 37d578c77..7b036c108 100644 --- a/src/lib/orderman/actors/ICEExecutionGateway.cpp +++ b/src/lib/orderman/actors/ICEExecutionGateway.cpp @@ -462,7 +462,7 @@ void ICEExecutionGateway::on_cancel_reject(const jetfix::fix::ICECancelRejectMsg else if (msg.has()) reject_msg = fmt::format("Order cancel was rejected with error code {}", msg.get()); - me->on_cancel_reject(ok, reject_msg); + me->on_cancel_reject(CancelReject {ok, CancelRejectReason::Other,reject_msg}); } diff --git a/src/lib/orderman/actors/IExecutionGateway.h b/src/lib/orderman/actors/IExecutionGateway.h index e728b4e6d..a6f99fee8 100644 --- a/src/lib/orderman/actors/IExecutionGateway.h +++ b/src/lib/orderman/actors/IExecutionGateway.h @@ -17,7 +17,7 @@ namespace orderman { class NewSecuritiesEvent; class NewAdminDataEvent; class ExecutionReport; - +class CancelReject; struct CreateOrderMsg { OrderKey key; @@ -52,7 +52,7 @@ using OrderMsg = using OnGwStatusChange = std::function; using OnExeReport = std::function; -using OnCancelReject = std::function; +using OnCancelReject = std::function; // fix execution gateway for a single FIX session class IExecutionGateway { diff --git a/src/lib/orderman/actors/ilink3/IL3Parser.cpp b/src/lib/orderman/actors/ilink3/IL3Parser.cpp index c87fa409b..f1932a9d1 100644 --- a/src/lib/orderman/actors/ilink3/IL3Parser.cpp +++ b/src/lib/orderman/actors/ilink3/IL3Parser.cpp @@ -6,25 +6,26 @@ #include "ILink3Utils.h" #include "lib/domain_model/Security.h" #include "lib/md/IntPrice.h" +#include "lib/orderman/actors/ilink3/IL3SecDB.h" +#include "lib/orderman/orderman_utils/CancelReject.h" #include "lib/orderman/orderman_utils/fix_order_codec.h" #include "lib/orderman/orderman_utils/orderman_common.h" -#include "lib/orderman/actors/ilink3/IL3SecDB.h" namespace bts { namespace orderman { namespace ilink3 { IL3Parser::IL3Parser(config::JetFIX::Connection const &cfg, IL3SecDB *db) - : most_recent_account(), cfg(cfg) ,db(db) {} + : most_recent_account(), cfg(cfg), db(db) {} const api::Security *IL3Parser::get_security(SecurityKey id) { - if (db) + if (db) return db->get_security(id); else return nullptr; } -const api::Security * IL3Parser::get_security(ExchangeSecurityKey id) { +const api::Security *IL3Parser::get_security(ExchangeSecurityKey id) { if (db) return db->get_security(id); else @@ -32,8 +33,7 @@ const api::Security * IL3Parser::get_security(ExchangeSecurityKey id) { } template -void IL3Parser::parse_common(const T &msg, - ExecutionReport *data) { +void IL3Parser::parse_common(const T &msg, ExecutionReport *data) { data->account_name = most_recent_account; static_assert(sizeof(OperatorID) == T::senderIDLength()); memcpy(&data->operator_id.value(), msg.senderID(), msg.senderIDLength()); @@ -54,9 +54,9 @@ void IL3Parser::parse_common(const T &msg, *sec, Price{price.mantissa() * md::pow10(price.exponent())}); data->quantity = Quantity{msg.orderQty()}; data->side = map_side(msg.side()); - auto &stop_price = const_cast(msg).stopPx(); + auto &stop_price = const_cast(msg).stopPx(); data->stop_price = securities::decode_exchange_price( - *sec, Price{stop_price.mantissa() * md::pow10(stop_price.exponent())}); + *sec, Price{stop_price.mantissa() * md::pow10(stop_price.exponent())}); data->time_in_force = map_time_in_force(msg.timeInForce()); data->transact_time = ExchangeTimeStamp64{msg.transactTime()}; data->ice_cl_ord_id = 0; @@ -65,8 +65,7 @@ void IL3Parser::parse_common(const T &msg, } template -void IL3Parser::parse_trade(const T &msg, - ExecutionReport *data) { +void IL3Parser::parse_trade(const T &msg, ExecutionReport *data) { orderman::to_array(msg.getExecIDAsStringView(), &data->exchange_fill_id.value()); switch (msg.ordStatus()) { @@ -98,8 +97,8 @@ void IL3Parser::parse_trade(const T &msg, data->filled_quantity = Quantity{msg.cumQty()}; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportNew522 &msg, ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportNew522 &msg, + ExecutionReport *data) { parse_common(msg, data); data->avg_price = Price{0.0}; data->cust_order_handling_inst = ""; @@ -114,39 +113,35 @@ bool IL3Parser::parse( data->order_status = api::orderman::NativeOrderStatus(*msg.ordStatus()); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportReject523 &msg, ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportReject523 &msg, + ExecutionReport *data) { parse_common(msg, data); data->order_status = api::orderman::NativeOrderStatus(*msg.ordStatus()); data->msg = msg.getTextAsStringView(); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportElimination524 &msg, - ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportElimination524 &msg, + ExecutionReport *data) { parse_common(msg, data); data->order_status = api::orderman::NativeOrderStatus(*msg.ordStatus()); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportTradeOutright525 &msg, - ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportTradeOutright525 &msg, + ExecutionReport *data) { parse_common(msg, data); parse_trade(msg, data); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportTradeSpread526 &msg, - ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportTradeSpread526 &msg, + ExecutionReport *data) { parse_common(msg, data); parse_trade(msg, data); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportTradeSpreadLeg527 &msg, - ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportTradeSpreadLeg527 &msg, + ExecutionReport *data) { data->account_name = most_recent_account; - data->avg_price = Price {0.0}; + data->avg_price = Price{0.0}; static_assert(sizeof(OperatorID) == iLinkBinary::ExecutionReportTradeSpread526::senderIDLength()); memcpy(&data->operator_id.value(), msg.senderID(), msg.senderIDLength()); @@ -192,24 +187,39 @@ bool IL3Parser::parse( parse_trade(msg, data); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportModify531 &msg, ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportModify531 &msg, + ExecutionReport *data) { parse_common(msg, data); data->order_status = api::orderman::NativeOrderStatus(*msg.ordStatus()); return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportStatus532 &msg, ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportStatus532 &msg, + ExecutionReport *data) { parse_common(msg, data); - // data->order_status = msg. return true; } -bool IL3Parser::parse( - const iLinkBinary::ExecutionReportCancel534 &msg, ExecutionReport *data) { +bool IL3Parser::parse(const iLinkBinary::ExecutionReportCancel534 &msg, + ExecutionReport *data) { parse_common(msg, data); data->order_status = api::orderman::NativeOrderStatus(*msg.ordStatus()); return true; } + +bool IL3Parser::parse(const iLinkBinary::OrderCancelReject535 &msg, + CancelReject *cr) { + SecurityKey sk; + OrderKey ok; + decode_clorid(msg.clOrdID(), &ok, &sk); + cr->order_key = ok; + cr->reject_msg = msg.getTextAsStringView(); + // https://www.cmegroup.com/confluence/display/EPICSANDBOX/iLink+Reject+Codes + if (msg.cxlRejReason() == 2045) + cr->reason = CancelRejectReason::UnknownOrder; + else + cr->reason = CancelRejectReason::Other; + return true; +} + void IL3Parser::set_account( const iLinkBinary::PartyDetailsDefinitionRequestAck519 &msg) { // When using on-demand format the PartyDetailsDefinitionRequestAck519 diff --git a/src/lib/orderman/actors/ilink3/IL3Parser.h b/src/lib/orderman/actors/ilink3/IL3Parser.h index 57fb9087d..b72edf344 100644 --- a/src/lib/orderman/actors/ilink3/IL3Parser.h +++ b/src/lib/orderman/actors/ilink3/IL3Parser.h @@ -9,6 +9,7 @@ namespace bts { namespace orderman { +class CancelReject; namespace ilink3 { class IL3SecDB; @@ -31,8 +32,8 @@ public: bool parse(const iLinkBinary::ExecutionReportModify531&, ExecutionReport*); bool parse(const iLinkBinary::ExecutionReportStatus532&, ExecutionReport*); bool parse(const iLinkBinary::ExecutionReportCancel534&, ExecutionReport*); + bool parse(const iLinkBinary::OrderCancelReject535&, CancelReject*); void set_account(const iLinkBinary::PartyDetailsDefinitionRequestAck519&); - private: template void parse_common(const T&, ExecutionReport*); template void parse_trade(const T&, ExecutionReport*); diff --git a/src/lib/orderman/actors/ilink3/ILinkGW.cpp b/src/lib/orderman/actors/ilink3/ILinkGW.cpp index af95db824..fbcac47ef 100644 --- a/src/lib/orderman/actors/ilink3/ILinkGW.cpp +++ b/src/lib/orderman/actors/ilink3/ILinkGW.cpp @@ -1,12 +1,12 @@ #include "ILinkGW.h" -#include "lib/utils/bts_assert.h" -#include "lib/utils/SecureLogon.h" -#include "ILink3Utils.h" -#include "IL3GeneratedFull.h" #include "IL3Dispatcher.h" +#include "IL3GeneratedFull.h" #include "IL3MessageFramer.h" -#include "lib/utils/datetime.h" +#include "ILink3Utils.h" #include "lib/orderman/orderman_utils/fix_order_codec.h" +#include "lib/utils/SecureLogon.h" +#include "lib/utils/bts_assert.h" +#include "lib/utils/datetime.h" /* # Some notes about session binding and initialization: # @@ -33,29 +33,15 @@ namespace bts { namespace orderman { namespace ilink3 { -log::CharPtrWrapper wrap(const char* str) { return log::CharPtrWrapper{ str }; } +log::CharPtrWrapper wrap(const char *str) { return log::CharPtrWrapper{str}; } -ILinkGW::ILinkGW( - IL3Connection& con, - IL3MessageFramer& buffer, - IL3SecDB *db, - const Session& session, - const Config& conf, - config::JetFIX::Connection const & cfg) : - _config(conf), - _x_state(State::INIT), - _buffer(buffer), - _on_state_change([](auto){}), - _on_exe_report([](auto*){}), - _on_session_change([](auto){}), - _connection(con), - _session(session), - _msg_count(0), - _time(), - _pool(), - _exe_parser(cfg,db), - _retransmit() -{ +ILinkGW::ILinkGW(IL3Connection &con, IL3MessageFramer &buffer, IL3SecDB *db, + const Session &session, const Config &conf, + config::JetFIX::Connection const &cfg) + : _config(conf), _x_state(State::INIT), _buffer(buffer), + _on_state_change([](auto) {}), _on_exe_report([](auto *) {}), + _on_session_change([](auto) {}), _connection(con), _session(session), + _msg_count(0), _time(), _pool(), _exe_parser(cfg, db), _retransmit() { _clorid_buffer.resize(clordid_sz()); } @@ -67,9 +53,10 @@ void ILinkGW::connect() { // This determines the session uuid void ILinkGW::send_negotiate() { - // add 2 bytes for the empty 'credentials' (39008) length which must be present + // add 2 bytes for the empty 'credentials' (39008) length which must be + // present auto msg = _buffer.frame( - iLinkBinary::Negotiate500::credentialsHeaderLength()); + iLinkBinary::Negotiate500::credentialsHeaderLength()); msg.uUID(_session.uuid); msg.requestTimestamp(_time.now()); msg.putSession(_config.cme_session); @@ -79,27 +66,27 @@ void ILinkGW::send_negotiate() { msg.putFirm(_config.firm); const auto ld = glbx::calculate_hmac( - _config.cme_session, - std::to_string(msg.requestTimestamp()), - std::to_string(msg.uUID()), - _config.cme_session, - _config.firm - ); + _config.cme_session, std::to_string(msg.requestTimestamp()), + std::to_string(msg.uUID()), _config.cme_session, _config.firm); msg.putAccessKeyID(ld.access_key); msg.putHMACSignature(ld.hmac); std::string temp = ld.canonical; - for (size_t x = 0; x < temp.size(); ++x) { if (temp[x] == '\n') temp[x] = '$'; } + for (size_t x = 0; x < temp.size(); ++x) { + if (temp[x] == '\n') + temp[x] = '$'; + } flush(false); // clear HMAC for json logging - msg.putHMACSignature(std::string_view { nullptr, 0 }); - log_out(msg,0); + msg.putHMACSignature(std::string_view{nullptr, 0}); + log_out(msg, 0); // expect -> NegotiationResponse501 or NegotiationReject502 } void ILinkGW::send_establish() { - // add 2 bytes for the empty 'credentials' (39008) length which must be present + // add 2 bytes for the empty 'credentials' (39008) length which must be + // present auto msg = _buffer.frame(2); msg.uUID(_session.uuid); msg.requestTimestamp(_time.now()); @@ -110,37 +97,36 @@ void ILinkGW::send_establish() { msg.putTradingSystemName(std::string_view("SPARK")); msg.putTradingSystemVersion(std::string_view("1")); msg.putTradingSystemVendor(std::string_view("BTS")); - // On primary connection, the expected message sequence number of the next business message from customer to CME + // On primary connection, the expected message sequence number of the next + // business message from customer to CME msg.nextSeqNo(_session.to_cme); msg.keepAliveInterval(30000); - const auto ld = glbx::calculate_hmac( - _config.cme_session, - // RequestTimestamp - std::to_string(msg.requestTimestamp()), - std::to_string(msg.uUID()), - _config.cme_session, - // Firm ID - _config.firm, - // TradingSystemName - msg.getTradingSystemNameAsString(), - // TradingSystemVersion - msg.getTradingSystemVersionAsString(), - // TradingSystemVendor - msg.getTradingSystemVendorAsString(), - // NextSeqNo - std::to_string(msg.nextSeqNo()), - // KeepAliveInterval - std::to_string(msg.keepAliveInterval()) - ); + const auto ld = + glbx::calculate_hmac(_config.cme_session, + // RequestTimestamp + std::to_string(msg.requestTimestamp()), + std::to_string(msg.uUID()), _config.cme_session, + // Firm ID + _config.firm, + // TradingSystemName + msg.getTradingSystemNameAsString(), + // TradingSystemVersion + msg.getTradingSystemVersionAsString(), + // TradingSystemVendor + msg.getTradingSystemVendorAsString(), + // NextSeqNo + std::to_string(msg.nextSeqNo()), + // KeepAliveInterval + std::to_string(msg.keepAliveInterval())); msg.putAccessKeyID(ld.access_key); msg.putHMACSignature(ld.hmac); flush(false); // clear HMAC for json logging - msg.putHMACSignature(std::string_view { nullptr, 0 }); - log_out(msg,0); + msg.putHMACSignature(std::string_view{nullptr, 0}); + log_out(msg, 0); // expect -> EstablishmentAck504 or EstablishmentReject505 } @@ -149,14 +135,14 @@ void ILinkGW::send_sequence(bool lapsed) { msg.uUID(_session.uuid); msg.nextSeqNo(_session.to_cme); msg.faultToleranceIndicator(iLinkBinary::FTI::NULL_VALUE); - msg.keepAliveIntervalLapsed( - lapsed ? - iLinkBinary::KeepAliveLapsed::Lapsed : - iLinkBinary::KeepAliveLapsed::NotLapsed); - log_out(msg,0); + msg.keepAliveIntervalLapsed(lapsed + ? iLinkBinary::KeepAliveLapsed::Lapsed + : iLinkBinary::KeepAliveLapsed::NotLapsed); + log_out(msg, 0); } -void ILinkGW::send_retransmit_request(uint64_t uuid, uint32_t from, size_t count) { +void ILinkGW::send_retransmit_request(uint64_t uuid, uint32_t from, + size_t count) { bts_assert(from > 0); using namespace iLinkBinary; auto msg = _buffer.frame(); @@ -165,21 +151,23 @@ void ILinkGW::send_retransmit_request(uint64_t uuid, uint32_t from, size_t count msg.requestTimestamp(_time.now()); msg.fromSeqNo(from); msg.msgCount(count); - log_out(msg,0); + log_out(msg, 0); } -uint64_t ILinkGW::send_party_details(const api::orderman::RoutingRecord& route) { +uint64_t +ILinkGW::send_party_details(const api::orderman::RoutingRecord &route) { using namespace iLinkBinary; auto msg = _buffer.frame( - // 2 repeating group header. - // 1 for party details and 1 for trade reg - // This seems unsafe but the api doesn't seem to want you to know how to size buffers ahead of time - 2 * PartyDetailsDefinitionRequest518::NoPartyDetails::sbeHeaderSize() + - // N * size of each block - 3 * PartyDetailsDefinitionRequest518::NoPartyDetails::sbeBlockLength() + - 0 * PartyDetailsDefinitionRequest518::NoTrdRegPublications::sbeBlockLength() - ); + // 2 repeating group header. + // 1 for party details and 1 for trade reg + // This seems unsafe but the api doesn't seem to want you to know how to + // size buffers ahead of time + 2 * PartyDetailsDefinitionRequest518::NoPartyDetails::sbeHeaderSize() + + // N * size of each block + 3 * PartyDetailsDefinitionRequest518::NoPartyDetails::sbeBlockLength() + + 0 * PartyDetailsDefinitionRequest518::NoTrdRegPublications:: + sbeBlockLength()); msg.partyDetailsListReqID(0); msg.sendingTimeEpoch(_time.now()); msg.listUpdateAction(ListUpdAct::Add); @@ -187,25 +175,25 @@ uint64_t ILinkGW::send_party_details(const api::orderman::RoutingRecord& route) // msg.putMemo("") -- not supported if (route.smp_id().empty()) { msg.selfMatchPreventionID( - PartyDetailsDefinitionRequest518::selfMatchPreventionIDNullValue()); - } - else { - // CME needs the SMP_ID to be 12 characters or less + PartyDetailsDefinitionRequest518::selfMatchPreventionIDNullValue()); + } else { + // CME needs the SMP_ID to be 12 characters or less // after they to_string() the uint64 bts_assert_d(route.smp_id().size() == 8); - const uint64_t* psmp_id = reinterpret_cast(&route.smp_id()); - uint64_t smp_id = (*psmp_id) % (2UL<<39); + const uint64_t *psmp_id = + reinterpret_cast(&route.smp_id()); + uint64_t smp_id = (*psmp_id) % (2UL << 39); msg.selfMatchPreventionID(smp_id); } msg.cmtaGiveupCD(CmtaGiveUpCD::NULL_VALUE); msg.custOrderCapacity(map_cust_cti(route.cti_code())); msg.clearingAccountType(map_customer_or_firm(route.customer_or_firm())); - msg.selfMatchPreventionInstruction(map_smp_instruction(route.smp_instruction())); + msg.selfMatchPreventionInstruction( + map_smp_instruction(route.smp_instruction())); msg.avgPxIndicator(AvgPxInd::NULL_VALUE); msg.clearingTradePriceType(SLEDS::NULL_VALUE); - msg.custOrderHandlingInst( - static_cast( - route.cust_order_handing_inst()[0])); + msg.custOrderHandlingInst(static_cast( + route.cust_order_handing_inst()[0])); msg.executor(PartyDetailsDefinitionRequest518::executorNullValue()); msg.iDMShortCode(PartyDetailsDefinitionRequest518::iDMShortCodeNullValue()); @@ -217,28 +205,32 @@ uint64_t ILinkGW::send_party_details(const api::orderman::RoutingRecord& route) details.partyDetailRole(PartyDetailRole::ExecutingFirm); // 004 in cert details.putPartyDetailID( - std::string_view(route.sender_compid().c_str()+3, 3)); + std::string_view(route.sender_compid().c_str() + 3, 3)); details.next(); details.partyDetailRole(PartyDetailRole::Operator); - details.putPartyDetailID( - std::string_view(route.sender_compid().c_str(), 3)); + details.putPartyDetailID(std::string_view(route.sender_compid().c_str(), 3)); msg.noTrdRegPublicationsCount(0); - // In the future we may check for existing party details definitions and return that id - log_out(msg,msg.seqNum()); + // In the future we may check for existing party details definitions and + // return that id + log_out(msg, msg.seqNum()); return 0; } bool needs_stop_px(api::orderman::NativeOrderType order_type) { - return order_type == api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP || - order_type == api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP_LIMIT; + return order_type == + api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP || + order_type == + api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP_LIMIT; } bool need_px(api::orderman::NativeOrderType order_type) { - return order_type != api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_MARKET && - order_type != api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_MARKET_LIMIT && + return order_type != + api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_MARKET && + order_type != + api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_MARKET_LIMIT && order_type != api::orderman::NativeOrderType::NATIVE_ORDER_TYPE_STOP; } -void ILinkGW::send_order(const CreateOrderMsg& create) { +void ILinkGW::send_order(const CreateOrderMsg &create) { bts_assert_d(create.routing_record); bts_assert_d(create.security); bts_assert_d(create.security->has_glbx()); @@ -246,46 +238,54 @@ void ILinkGW::send_order(const CreateOrderMsg& create) { auto party = send_party_details(*create.routing_record); auto msg = _buffer.frame(); - if (need_px(create.order_type)) { msg.price().mantissa(to_price9(create.price)); } - else { msg.price().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); } + if (need_px(create.order_type)) { + msg.price().mantissa(to_price9(create.price)); + } else { + msg.price().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); + } msg.orderQty(create.quantity.value()); msg.securityID(create.security->glbx().exchange_id()); msg.side(map_side(create.side)); msg.seqNum(next_seq()); msg.putSenderID(create.routing_record->operator_id()); - encode_clorid(create.key, SecurityKey(create.security->id()), &_clorid_buffer); + encode_clorid(create.key, SecurityKey(create.security->id()), + &_clorid_buffer); msg.putClOrdID(_clorid_buffer); msg.partyDetailsListReqID(party); msg.orderRequestID(++_msg_count); msg.sendingTimeEpoch(_time.now()); - if (needs_stop_px(create.order_type)) { msg.stopPx().mantissa(to_price9(create.stop_px)); } - else { msg.stopPx().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); } + if (needs_stop_px(create.order_type)) { + msg.stopPx().mantissa(to_price9(create.stop_px)); + } else { + msg.stopPx().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); + } msg.putLocation(create.routing_record->location()); msg.minQty(iLinkBinary::NewOrderSingle514::minQtyNullValue()); if (create.time_in_force != api::orderman::TimeInForce::TIME_IN_FORCE_IOC) { msg.displayQty(create.display_quantity.value()); + } else { + msg.displayQty(iLinkBinary::NewOrderSingle514::displayQtyNullValue()); } - else { msg.displayQty(iLinkBinary::NewOrderSingle514::displayQtyNullValue()); } if (create.time_in_force == api::orderman::TimeInForce::TIME_IN_FORCE_DATE) { - //TODO: # of days since jan 1 1970 + // TODO: # of days since jan 1 1970 msg.expireDate(18424); - } - else { + } else { msg.expireDate(iLinkBinary::NewOrderSingle514::expireDateNullValue()); } msg.ordType(map_order_type(create.order_type)); msg.timeInForce(map_time_in_force(create.time_in_force)); - msg.manualOrderIndicator(map_manual_order_indicator(create.manual_order_indicator)); + msg.manualOrderIndicator( + map_manual_order_indicator(create.manual_order_indicator)); msg.execInst().clear(); msg.executionMode(iLinkBinary::ExecMode::NULL_VALUE); msg.liquidityFlag(iLinkBinary::BooleanNULL::NULL_VALUE); msg.managedOrder(iLinkBinary::BooleanNULL::NULL_VALUE); msg.shortSaleType(iLinkBinary::ShortSaleType::NULL_VALUE); - log_out(msg,msg.seqNum()); + log_out(msg, msg.seqNum()); } -void ILinkGW::send_cancel_replace(const CancelReplaceOrderMsg& replace) { - const auto& create = replace.create_fields; +void ILinkGW::send_cancel_replace(const CancelReplaceOrderMsg &replace) { + const auto &create = replace.create_fields; bts_assert_d(create.routing_record); bts_assert_d(create.security); bts_assert_d(create.security->has_glbx()); @@ -295,37 +295,45 @@ void ILinkGW::send_cancel_replace(const CancelReplaceOrderMsg& replace) { msg.orderID(replace.exchange_order_id.value()); - if (need_px(create.order_type)) { msg.price().mantissa(to_price9(create.price)); } - else { msg.price().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); } + if (need_px(create.order_type)) { + msg.price().mantissa(to_price9(create.price)); + } else { + msg.price().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); + } msg.orderQty(create.quantity.value()); msg.securityID(create.security->glbx().exchange_id()); msg.side(map_side(create.side)); msg.seqNum(next_seq()); msg.putSenderID(create.routing_record->operator_id()); - encode_clorid(create.key, SecurityKey(create.security->id()), &_clorid_buffer); + encode_clorid(create.key, SecurityKey(create.security->id()), + &_clorid_buffer); msg.putClOrdID(_clorid_buffer); msg.partyDetailsListReqID(party); msg.orderRequestID(++_msg_count); msg.sendingTimeEpoch(_time.now()); - if (needs_stop_px(create.order_type)) { msg.stopPx().mantissa(to_price9(create.stop_px)); } - else { msg.stopPx().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); } + if (needs_stop_px(create.order_type)) { + msg.stopPx().mantissa(to_price9(create.stop_px)); + } else { + msg.stopPx().mantissa(iLinkBinary::PRICENULL9::mantissaNullValue()); + } msg.putLocation(create.routing_record->location()); msg.minQty(iLinkBinary::NewOrderSingle514::minQtyNullValue()); msg.displayQty(create.display_quantity.value()); msg.expireDate(iLinkBinary::NewOrderSingle514::expireDateNullValue()); msg.ordType(map_order_type(create.order_type)); msg.timeInForce(map_time_in_force(create.time_in_force)); - msg.manualOrderIndicator(map_manual_order_indicator(create.manual_order_indicator)); + msg.manualOrderIndicator( + map_manual_order_indicator(create.manual_order_indicator)); msg.oFMOverride(iLinkBinary::OFMOverrideReq::Enabled); msg.execInst().clear(); msg.executionMode(iLinkBinary::ExecMode::NULL_VALUE); msg.liquidityFlag(iLinkBinary::BooleanNULL::NULL_VALUE); msg.managedOrder(iLinkBinary::BooleanNULL::NULL_VALUE); msg.shortSaleType(iLinkBinary::ShortSaleType::NULL_VALUE); - log_out(msg,msg.seqNum()); + log_out(msg, msg.seqNum()); } -void ILinkGW::send_cancel(const CancelOrderMsg& cancel) { +void ILinkGW::send_cancel(const CancelOrderMsg &cancel) { bts_assert_d(cancel.routing_record); bts_assert_d(cancel.security); bts_assert_d(cancel.security->has_glbx()); @@ -335,10 +343,12 @@ void ILinkGW::send_cancel(const CancelOrderMsg& cancel) { msg.orderID(cancel.exchange_order_id.value()); msg.partyDetailsListReqID(party); - msg.manualOrderIndicator(map_manual_order_indicator(cancel.manual_order_indicator)); + msg.manualOrderIndicator( + map_manual_order_indicator(cancel.manual_order_indicator)); msg.seqNum(next_seq()); msg.putSenderID(cancel.routing_record->operator_id()); - encode_clorid(cancel.key, SecurityKey(cancel.security->id()), &_clorid_buffer); + encode_clorid(cancel.key, SecurityKey(cancel.security->id()), + &_clorid_buffer); msg.putClOrdID(_clorid_buffer); msg.orderRequestID(++_msg_count); msg.sendingTimeEpoch(_time.now()); @@ -346,7 +356,7 @@ void ILinkGW::send_cancel(const CancelOrderMsg& cancel) { msg.securityID(cancel.security->glbx().exchange_id()); msg.side(map_side(cancel.side)); msg.liquidityFlag(iLinkBinary::BooleanNULL::NULL_VALUE); - log_out(msg,msg.seqNum()); + log_out(msg, msg.seqNum()); } void ILinkGW::send_terminate(uint16_t code) { @@ -355,23 +365,31 @@ void ILinkGW::send_terminate(uint16_t code) { msg.uUID(_session.uuid); msg.requestTimestamp(_time.now()); msg.errorCodes(code); - log_out(msg,0); + log_out(msg, 0); } void ILinkGW::flush(bool publish) { _buffer.flush(_connection); - if (publish) publish_session_update(); + if (publish) + publish_session_update(); } -const char* state_string(State s) { - switch(s) { - case State::INIT: return "INIT"; - case State::CONNECTING: return "CONNECTING"; - case State::NEGOTATING: return "NEGOTATING"; - case State::ESTABLISHING: return "ESTABLISHING"; - case State::RETRANSMITTING: return "RETRANSMITTING"; - case State::READY: return "READY"; - case State::ERROR: return "ERROR"; +const char *state_string(State s) { + switch (s) { + case State::INIT: + return "INIT"; + case State::CONNECTING: + return "CONNECTING"; + case State::NEGOTATING: + return "NEGOTATING"; + case State::ESTABLISHING: + return "ESTABLISHING"; + case State::RETRANSMITTING: + return "RETRANSMITTING"; + case State::READY: + return "READY"; + case State::ERROR: + return "ERROR"; } return "UNKNOWN"; } @@ -379,10 +397,11 @@ log::CharPtrWrapper wstate_string(State s) { return wrap(state_string(s)); } void ILinkGW::set_state(State s) { if (s != _x_state) { - LOG(iLink3, Info, "ILinkGW {}: {}->{}", - _session.uuid, wstate_string(_x_state), wstate_string(s)); + LOG(iLink3, Info, "ILinkGW {}: {}->{}", _session.uuid, + wstate_string(_x_state), wstate_string(s)); _x_state = s; - if (_on_state_change) _on_state_change(s); + if (_on_state_change) + _on_state_change(s); } } @@ -391,14 +410,15 @@ void ILinkGW::set_state(State s) { void ILinkGW::on_connect_success() { if (!_session) { - // If we have a 0 cme_seq this is a new session and we need to negotiate it + // If we have a 0 cme_seq this is a new session and we need to negotiate + // it LOG(iLink3, Info, "Negotiating new iLink session. {}", _session.uuid); set_state(State::NEGOTATING); send_negotiate(); - } - else { + } else { // We only need to establish the current sequence number - LOG(iLink3, Info, "re-establishing existing iLink session. {}", _session.uuid); + LOG(iLink3, Info, "re-establishing existing iLink session. {}", + _session.uuid); _session.to_cme = std::max(_session.to_cme, 1u); set_state(State::ESTABLISHING); send_establish(); @@ -411,33 +431,31 @@ void ILinkGW::on_disconnect() { LOG(iLink3, Error, "Attempting failover"); _connection.failover(); connect(); - } - else { + } else { set_state(State::ERROR); } } void ILinkGW::enqueue_retransmit(uint32_t from, uint32_t to, uint64_t uuid) { - LOG(iLink3,Warn, "Prepare retransmit from: {} to: {}", from, to); + LOG(iLink3, Warn, "Prepare retransmit from: {} to: {}", from, to); bts_assert(to >= from); do { // +1 because to/from are using an inclusive range auto count = std::min(to - from + 1, Retransmit::MAX_RECOVERY); - _retransmit.push(Retransmit { - uuid, - from, - from + count - 1 - }); + _retransmit.push(Retransmit{uuid, from, from + count - 1}); from += count; - } while(from < to); + } while (from < to); } void ILinkGW::begin_retransmit() { - if (_retransmit.empty()) return; - auto& working = _retransmit.front(); + if (_retransmit.empty()) + return; + auto &working = _retransmit.front(); // Don't pop the queue because we need to know when we're done auto count = working.to - working.from + 1; - LOG(iLink3,Warn, "Sending retransmit for missing packets: from: {} to: {} count: {}", working.from, working.to, count); + LOG(iLink3, Warn, + "Sending retransmit for missing packets: from: {} to: {} count: {}", + working.from, working.to, count); bts_assert_d(count < Retransmit::MAX_RECOVERY); send_retransmit_request(working.uuid, working.from, count); } @@ -445,49 +463,49 @@ void ILinkGW::begin_retransmit() { void ILinkGW::on_retransmit_complete() { // Replay is complete. Advance to go. Collect $200 _retransmit.pop(); - LOG(iLink3,Warn,"Retransmit complete"); + LOG(iLink3, Warn, "Retransmit complete"); if (!_retransmit.empty()) { // More replay to do... begin_retransmit(); flush(); - } - else { + } else { // Replay is finished, transition to ready state. // Since we're already established we dont' need to send anything set_state(State::READY); } } -size_t ILinkGW::on_data(const std::string_view& data) { - return consume_messages(*this, data.data(), data.size(), dispatch_message); +size_t ILinkGW::on_data(const std::string_view &data) { + return consume_messages(*this, data.data(), data.size(), + dispatch_message); } -void ILinkGW::handle(const iLinkBinary::NegotiationResponse501& msg) { +void ILinkGW::handle(const iLinkBinary::NegotiationResponse501 &msg) { // If we're receiving a NegotiateResponse we just created a session - log_in(msg,0); + log_in(msg, 0); - // NegotiationResponse indicates the session was created. CME sequence will be 1 + // NegotiationResponse indicates the session was created. CME sequence will + // be 1 _session.from_cme = 1; publish_session_update(); // Even though the CME sends a previous uuid+sequence we can't act on - // that data right now since we aren't established. We don't have to remember it, - // though, because exactly the same data comes on the EstablishmentAck + // that data right now since we aren't established. We don't have to remember + // it, though, because exactly the same data comes on the EstablishmentAck // msg.previousUUID(), msg.previousSeqNo(); set_state(State::ESTABLISHING); send_establish(); } -void ILinkGW::handle(const iLinkBinary::NegotiationReject502& msg) { - LOG(iLink3, Error, "Negotiate Reject: {} '{}'.", - msg.errorCodes(), - std::string(translate_negotiation_reject(msg.errorCodes()))); - log_in(msg,0); +void ILinkGW::handle(const iLinkBinary::NegotiationReject502 &msg) { + LOG(iLink3, Error, "Negotiate Reject: {} '{}'.", msg.errorCodes(), + std::string(translate_negotiation_reject(msg.errorCodes()))); + log_in(msg, 0); _connection.disconnect(); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::EstablishmentAck504& msg) { +void ILinkGW::handle(const iLinkBinary::EstablishmentAck504 &msg) { // previous uuid+sequence auto cme_prev_uuid = msg.previousUUID(); auto cme_prev_seq = msg.previousSeqNo(); @@ -506,77 +524,78 @@ void ILinkGW::handle(const iLinkBinary::EstablishmentAck504& msg) { auto cme_current_seq = msg.nextSeqNo() - 1; if (_session.from_cme < cme_current_seq) { // If we're behind it indicates we missed messages while disconnected - enqueue_retransmit(_session.from_cme+1, cme_current_seq, msg.uUID()); + enqueue_retransmit(_session.from_cme + 1, cme_current_seq, msg.uUID()); } _session.from_cme = cme_current_seq; - log_in(msg,0); + log_in(msg, 0); if (!_retransmit.empty()) { send_sequence(); begin_retransmit(); flush(); set_state(State::RETRANSMITTING); - } - else { + } else { send_sequence(); flush(); set_state(State::READY); } } -void ILinkGW::handle(const iLinkBinary::EstablishmentReject505& msg) { - LOG(iLink3, Error, "Establishment Reject: {} '{}'. NextSeq: {}.", - msg.errorCodes(), - std::string(translate_establish_reject(msg.errorCodes())), - msg.nextSeqNo()); +void ILinkGW::handle(const iLinkBinary::EstablishmentReject505 &msg) { + LOG(iLink3, Error, "Establishment Reject: {} '{}'. NextSeq: {}.", + msg.errorCodes(), + std::string(translate_establish_reject(msg.errorCodes())), + msg.nextSeqNo()); _connection.disconnect(); - log_in(msg,0); + log_in(msg, 0); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::Sequence506& msg) { - log_in(msg,0); +void ILinkGW::handle(const iLinkBinary::Sequence506 &msg) { + log_in(msg, 0); _session.from_cme = msg.nextSeqNo() - 1; publish_session_update(); send_sequence(); flush(); } void ILinkGW::handle(const iLinkBinary::Terminate507 &msg) { -// https://www.cmegroup.com/confluence/display/EPICSANDBOX/Terminate + // https://www.cmegroup.com/confluence/display/EPICSANDBOX/Terminate LOG(iLink3, Error, "Terminated by exchange. Code: {} Reason: {} Text: {}", msg.errorCodes(), wrap(msg.reason()), wrap(translate_terminate(msg.errorCodes()))); - if (msg.errorCodes() == 11 || msg.errorCodes() == 10) { + if (msg.errorCodes() == 11 || msg.errorCodes() == 10) { // This indicates our sequence number is too low. We will jump // forward one at a time. That should eventually fix it. - LOG(iLink3, Error, "Will attempt to recover by advancing our sequence number"); - _session.to_cme ++; + LOG(iLink3, Error, + "Will attempt to recover by advancing our sequence number"); + _session.to_cme++; publish_session_update(); } - log_in(msg,0); + log_in(msg, 0); _connection.disconnect(); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::Retransmission509& msg) { +void ILinkGW::handle(const iLinkBinary::Retransmission509 &msg) { // Accepted Retransmit - log_in(msg,0); + log_in(msg, 0); } -void ILinkGW::handle(const iLinkBinary::RetransmitReject510& msg) { - LOG(iLink3, Error, "Retransmit requeste rejected. {}", msg.getReasonAsString()); - log_in(msg,0); +void ILinkGW::handle(const iLinkBinary::RetransmitReject510 &msg) { + LOG(iLink3, Error, "Retransmit requeste rejected. {}", + msg.getReasonAsString()); + log_in(msg, 0); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::NotApplied513& msg) { - log_in(msg,0); +void ILinkGW::handle(const iLinkBinary::NotApplied513 &msg) { + log_in(msg, 0); send_sequence(); } -void ILinkGW::handle(const iLinkBinary::PartyDetailsDefinitionRequestAck519& msg) { +void ILinkGW::handle( + const iLinkBinary::PartyDetailsDefinitionRequestAck519 &msg) { _exe_parser.set_account(msg); handle_common(msg); } -void ILinkGW::handle(const iLinkBinary::BusinessReject521& msg) { - LOG(iLink3, Error, "Business Reject: {} '{}'.", - msg.businessRejectReason(), - wrap(translate_business_reject_reason(msg.businessRejectReason()))); +void ILinkGW::handle(const iLinkBinary::BusinessReject521 &msg) { + LOG(iLink3, Error, "Business Reject: {} '{}'.", msg.businessRejectReason(), + wrap(translate_business_reject_reason(msg.businessRejectReason()))); handle_common(msg); // A business reject can de-sync the sequence number because it rejects // the sequence number of the rejected message. Send a sequence message @@ -584,54 +603,66 @@ void ILinkGW::handle(const iLinkBinary::BusinessReject521& msg) { send_sequence(); flush(); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportNew522& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportNew522 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportReject523& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportReject523 &msg) { LOG(iLink3, Error, "Execution report reject: {}", wrap(msg.text())); handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportElimination524& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportElimination524 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeOutright525& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeOutright525 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpread526& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpread526 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpreadLeg527& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpreadLeg527 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportModify531& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportModify531 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportStatus532& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportStatus532 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportCancel534& msg) { +void ILinkGW::handle(const iLinkBinary::ExecutionReportCancel534 &msg) { handle_exe_report(msg); } -void ILinkGW::handle(const iLinkBinary::OrderCancelReject535& msg) { +void ILinkGW::handle(const iLinkBinary::OrderCancelReject535 &msg) { + CancelReject cr; + bool result = _exe_parser.parse(msg, &cr); + if (result) { + _on_cancel_reject(cr); + } else { + LOG(iLink3, Error, "Failed to parse cancel reject."); + } handle_common(msg); } -void ILinkGW::handle(const iLinkBinary::OrderCancelReplaceReject536& msg) { +void ILinkGW::handle(const iLinkBinary::OrderCancelReplaceReject536 &msg) { handle_common(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumOutright548& msg) { +void ILinkGW::handle( + const iLinkBinary::ExecutionReportTradeAddendumOutright548 &msg) { // Ignore trade correction/addendum messages for now. // See GLBXExecutionGateway.cpp:139 for further details handle_common(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumSpread549& msg) { +void ILinkGW::handle( + const iLinkBinary::ExecutionReportTradeAddendumSpread549 &msg) { // Ignore trade correction/addendum messages for now. // See GLBXExecutionGateway.cpp:139 for further details handle_common(msg); } -void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550& msg) { +void ILinkGW::handle( + const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550 &msg) { // Ignore trade correction/addendum messages for now. // See GLBXExecutionGateway.cpp:139 for further details handle_common(msg); } -}}} //namespace +} // namespace ilink3 +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/actors/ilink3/ILinkGW.h b/src/lib/orderman/actors/ilink3/ILinkGW.h index 1cbc79e14..15bd58b3c 100644 --- a/src/lib/orderman/actors/ilink3/ILinkGW.h +++ b/src/lib/orderman/actors/ilink3/ILinkGW.h @@ -1,20 +1,21 @@ #pragma once -#include -#include #include -#include +#include #include +#include +#include #include "../IExecutionGateway.h" -#include "TimeKeeper.h" #include "IL3Connection.h" #include "IL3ConnectionHandler.h" +#include "TimeKeeper.h" -#include "generated/MessageHeader.h" #include "IL3GeneratedFwd.h" #include "IL3Parser.h" -#include "lib/orderman/actors/ilink3/RawMsg.h" +#include "generated/MessageHeader.h" #include "lib/config/protos/jetfix.pb.h" +#include "lib/orderman/actors/ilink3/RawMsg.h" +#include "lib/orderman/orderman_utils/CancelReject.h" #define MID_SESSION_REPLAY @@ -37,9 +38,10 @@ struct Session { struct Config { std::string cme_session; // NGG - std::string firm; // 004 + std::string firm; // 004 bool failover_on_disconnect; - std::function raw_message_logger; + std::function + raw_message_logger; }; enum class State { @@ -51,11 +53,11 @@ enum class State { READY, ERROR }; -const char* state_string(State s); +const char *state_string(State s); typedef std::function OnStateChange; -typedef std::function OnExecutionReport; -typedef std::function OnSessionChange; -typedef std::function OnCancelReject; +typedef std::function OnExecutionReport; +typedef std::function OnSessionChange; +typedef std::function OnCancelReject; struct Retransmit { static constexpr uint32_t MAX_RECOVERY = 2500; @@ -70,12 +72,12 @@ class IL3MessageFramer; class ILinkGW : IL3ConnectionHandler { const Config _config; State _x_state; - IL3MessageFramer& _buffer; + IL3MessageFramer &_buffer; OnStateChange _on_state_change; OnExecutionReport _on_exe_report; OnSessionChange _on_session_change; OnCancelReject _on_cancel_reject; - IL3Connection& _connection; + IL3Connection &_connection; Session _session; std::string _clorid_buffer; uint32_t _msg_count; @@ -83,50 +85,45 @@ class ILinkGW : IL3ConnectionHandler { boost::object_pool _pool; IL3Parser _exe_parser; std::queue _retransmit; - -public: - ILinkGW( - IL3Connection&, - IL3MessageFramer&, - IL3SecDB*, - const Session&, - const Config&, - config::JetFIX::Connection const &); + + public: + ILinkGW(IL3Connection &, IL3MessageFramer &, IL3SecDB *, const Session &, + const Config &, config::JetFIX::Connection const &); void connect(); - void send_order(const CreateOrderMsg&); - void send_cancel_replace(const CancelReplaceOrderMsg&); - void send_cancel(const CancelOrderMsg&); - void send_terminate(uint16_t code=0); - void flush(bool publish=true); - void on_time() { - // Currently we just reply to a heartbeat with another heartbeat - // Probably better to track time and send them on demand + void send_order(const CreateOrderMsg &); + void send_cancel_replace(const CancelReplaceOrderMsg &); + void send_cancel(const CancelOrderMsg &); + void send_terminate(uint16_t code = 0); + void flush(bool publish = true); + void on_time(){ + // Currently we just reply to a heartbeat with another heartbeat + // Probably better to track time and send them on demand }; // state change State state() { return _x_state; } void subscribe_state(OnStateChange o) { _on_state_change = o; } - void subscribe_execution_reports(OnExecutionReport sub) { + void subscribe_execution_reports(OnExecutionReport sub) { _on_exe_report = sub; } void subscribe_session(OnSessionChange cb) { _on_session_change = cb; } - void subscribe_cancel_reject(OnCancelReject cb) {_on_cancel_reject = cb;} + void subscribe_cancel_reject(OnCancelReject cb) { _on_cancel_reject = cb; } // Only used for certification - void send_sequence(bool lapsed=false); + void send_sequence(bool lapsed = false); -private: + private: void send_negotiate(); void send_establish(); void send_retransmit_request(uint64_t uuid, uint32_t from, size_t count); - uint64_t send_party_details(const api::orderman::RoutingRecord&); + uint64_t send_party_details(const api::orderman::RoutingRecord &); -private: + private: void set_state(State); - uint32_t next_seq() { - _session.to_cme += 1; - return _session.to_cme-1; + uint32_t next_seq() { + _session.to_cme += 1; + return _session.to_cme - 1; } void publish_session_update() { _on_session_change(_session); } void on_connect_success() override; @@ -135,37 +132,36 @@ private: void begin_retransmit(); void on_retransmit_complete(); - template - static auto serialize(const T& msg) -> auto { + template static auto serialize(const T &msg) -> auto { return [=]() -> auto { RawMessageData result; std::stringstream buffer; buffer << msg; result.json = buffer.str(); - result.binary = std::string(msg.buffer() + msg.offset(), msg.decodeLength()); + result.binary = + std::string(msg.buffer() + msg.offset(), msg.decodeLength()); return result; }; } - template - void log_in(const T& msg,size_t sn) { - _config.raw_message_logger(RawMessageDirection::INCOMING, sn,serialize(msg)); + template void log_in(const T &msg, size_t sn) { + _config.raw_message_logger(RawMessageDirection::INCOMING, sn, + serialize(msg)); } - template - void log_out(const T& msg,size_t sn) { - _config.raw_message_logger(RawMessageDirection::OUTGOING, sn,serialize(msg)); + template void log_out(const T &msg, size_t sn) { + _config.raw_message_logger(RawMessageDirection::OUTGOING, sn, + serialize(msg)); } // // Message handlers - size_t on_data(const std::string_view&) override; + size_t on_data(const std::string_view &) override; - template - void handle_common(const T& msg) { + template void handle_common(const T &msg) { auto uuid = msg.uUID(); auto seq = msg.seqNum(); - log_in(msg,seq); + log_in(msg, seq); // Test if replay is copmlete if (!_retransmit.empty() && _retransmit.front().to == seq) { on_retransmit_complete(); @@ -174,16 +170,17 @@ private: // Handle non-replay packet if (uuid == _session.uuid) { - #ifdef MID_SESSION_REPLAY +#ifdef MID_SESSION_REPLAY // Gap detected during normal operation auto expected = _session.from_cme + 1; if (seq > expected) { bool busy = !_retransmit.empty(); - enqueue_retransmit(expected, seq-1, _session.uuid); - if (!busy) begin_retransmit(); + enqueue_retransmit(expected, seq - 1, _session.uuid); + if (!busy) + begin_retransmit(); flush(); } - #endif +#endif // msg may be a replay message with a lower sequence number if (msg.seqNum() > _session.from_cme) { _session.from_cme = msg.seqNum(); @@ -192,44 +189,45 @@ private: } } - template - void handle_exe_report(const T& msg) { - auto* report = _pool.construct(); + template void handle_exe_report(const T &msg) { + auto *report = _pool.construct(); bool result = _exe_parser.parse(msg, report); if (result) { _on_exe_report(report); + } else { + LOG(iLink3, Error, "Failed to parse error report."); } - else { LOG(iLink3, Error, "Failed to parse error report."); } handle_common(msg); } -public: - void handle(const iLinkBinary::NegotiationResponse501&); - void handle(const iLinkBinary::NegotiationReject502&); - void handle(const iLinkBinary::EstablishmentAck504&); - void handle(const iLinkBinary::EstablishmentReject505&); - void handle(const iLinkBinary::Sequence506&); - void handle(const iLinkBinary::Terminate507&); - void handle(const iLinkBinary::Retransmission509&); - void handle(const iLinkBinary::RetransmitReject510&); - void handle(const iLinkBinary::NotApplied513&); - void handle(const iLinkBinary::PartyDetailsDefinitionRequestAck519&); - void handle(const iLinkBinary::BusinessReject521&); - void handle(const iLinkBinary::ExecutionReportNew522&); - void handle(const iLinkBinary::ExecutionReportReject523&); - void handle(const iLinkBinary::ExecutionReportElimination524&); - void handle(const iLinkBinary::ExecutionReportTradeOutright525&); - void handle(const iLinkBinary::ExecutionReportTradeSpread526&); - void handle(const iLinkBinary::ExecutionReportTradeSpreadLeg527&); - void handle(const iLinkBinary::ExecutionReportModify531&); - void handle(const iLinkBinary::ExecutionReportStatus532&); - void handle(const iLinkBinary::ExecutionReportCancel534&); - void handle(const iLinkBinary::OrderCancelReject535&); - void handle(const iLinkBinary::OrderCancelReplaceReject536&); - void handle(const iLinkBinary::ExecutionReportTradeAddendumOutright548&); - void handle(const iLinkBinary::ExecutionReportTradeAddendumSpread549&); - void handle(const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550&); - + public: + void handle(const iLinkBinary::NegotiationResponse501 &); + void handle(const iLinkBinary::NegotiationReject502 &); + void handle(const iLinkBinary::EstablishmentAck504 &); + void handle(const iLinkBinary::EstablishmentReject505 &); + void handle(const iLinkBinary::Sequence506 &); + void handle(const iLinkBinary::Terminate507 &); + void handle(const iLinkBinary::Retransmission509 &); + void handle(const iLinkBinary::RetransmitReject510 &); + void handle(const iLinkBinary::NotApplied513 &); + void handle(const iLinkBinary::PartyDetailsDefinitionRequestAck519 &); + void handle(const iLinkBinary::BusinessReject521 &); + void handle(const iLinkBinary::ExecutionReportNew522 &); + void handle(const iLinkBinary::ExecutionReportReject523 &); + void handle(const iLinkBinary::ExecutionReportElimination524 &); + void handle(const iLinkBinary::ExecutionReportTradeOutright525 &); + void handle(const iLinkBinary::ExecutionReportTradeSpread526 &); + void handle(const iLinkBinary::ExecutionReportTradeSpreadLeg527 &); + void handle(const iLinkBinary::ExecutionReportModify531 &); + void handle(const iLinkBinary::ExecutionReportStatus532 &); + void handle(const iLinkBinary::ExecutionReportCancel534 &); + void handle(const iLinkBinary::OrderCancelReject535 &); + void handle(const iLinkBinary::OrderCancelReplaceReject536 &); + void handle(const iLinkBinary::ExecutionReportTradeAddendumOutright548 &); + void handle(const iLinkBinary::ExecutionReportTradeAddendumSpread549 &); + void handle(const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550 &); }; -}}} //namespace +} // namespace ilink3 +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/actors/order_manager/OrderManager.cpp b/src/lib/orderman/actors/order_manager/OrderManager.cpp index e0dee98f9..252b5968c 100644 --- a/src/lib/orderman/actors/order_manager/OrderManager.cpp +++ b/src/lib/orderman/actors/order_manager/OrderManager.cpp @@ -468,9 +468,8 @@ void OrderManager::init_order_services() { publish(s_ptr->gw_status_change_pub, gw_name, b); }; s->cancel_reject_pub = make_stream(gw_name); - s->gw->on_cancel_reject() = [s_ptr, this](auto const &k, - auto const &msg) { - publish(s_ptr->cancel_reject_pub, k, msg); + s->gw->on_cancel_reject() = [s_ptr, this](auto const&cr) { + publish(s_ptr->cancel_reject_pub,cr); }; // handlers are ready so we can start processing fix events s->gw->start(); diff --git a/src/lib/orderman/events/CancelRejectEvent.h b/src/lib/orderman/events/CancelRejectEvent.h index b173c2022..7e02c17d5 100644 --- a/src/lib/orderman/events/CancelRejectEvent.h +++ b/src/lib/orderman/events/CancelRejectEvent.h @@ -4,30 +4,27 @@ #include "lib/api/services/OrderService.pb.h" #include "lib/domain_model/common.h" -#include "lib/orderman/orderman_utils/orderman_common.h" #include "lib/mercury/events/Event.h" #include "lib/mercury/synopsis/NoSynopsis.h" +#include "lib/orderman/orderman_utils/CancelReject.h" +#include "lib/orderman/orderman_utils/orderman_common.h" namespace bts { namespace orderman { -class CancelRejectEvent : public mercury::Event -{ -public: -// Cancel Rejects are informative only, they have no effect on order -// state. So either they are conveyed to the user when they occur or -// they can be discarded. So no need for synopsis. - using SynopsisPolicy = mercury::NoSynopsis; +class CancelRejectEvent : public mercury::Event { + public: + using SynopsisPolicy = mercury::NoSynopsis; using Tag = GatewayName; - - CancelRejectEvent (OrderKey order_key, std::string const &rej) : - order_key(order_key), reject_msg(rej) - {} - OrderKey key() const{return order_key;} - OrderKey order_key; - std::string reject_msg; + CancelRejectEvent(CancelReject const &cr) : reject(cr) {} + OrderKey key() const { return reject.order_key; } + std::string const &reject_msg() const { return reject.reject_msg; } + CancelRejectReason reason() const {return reject.reason;} + + private: + CancelReject reject; }; -}} - +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orderman_utils/CancelReject.h b/src/lib/orderman/orderman_utils/CancelReject.h new file mode 100644 index 000000000..43457b6fc --- /dev/null +++ b/src/lib/orderman/orderman_utils/CancelReject.h @@ -0,0 +1,22 @@ +#pragma once + +#include "lib/orderman/orderman_utils/orderman_common.h" +#include + +namespace bts { +namespace orderman { + +enum class CancelRejectReason { + UnknownOrder, Other +}; + +class CancelReject { +public: + OrderKey order_key; + CancelRejectReason reason; + std::string reject_msg; +}; + + + +}} diff --git a/src/lib/orderman/orders/GLBXNativeOrder.cpp b/src/lib/orderman/orders/GLBXNativeOrder.cpp index d6377345e..9b09c6d42 100644 --- a/src/lib/orderman/orders/GLBXNativeOrder.cpp +++ b/src/lib/orderman/orders/GLBXNativeOrder.cpp @@ -970,16 +970,24 @@ void GLBXNativeOrder::on_cancel_reject(const orderman::CancelRejectEvent &cr) { break; case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_ERROR: { + auto &state = me->state; + state.set_last_msg(cr.reject_msg()); + report_state(); + break; + } + case ORDER_STATUS_PENDING_WORKING: case ORDER_STATUS_WORKING: { auto &state = me->state; - state.set_last_msg(cr.reject_msg); + state.set_last_msg(cr.reject_msg()); + if (cr.reason() == CancelRejectReason::UnknownOrder) + transition(ORDER_STATUS_CANCELED); report_state(); break; } case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_ERROR: case ORDER_STATUS_REJECTED_BY_SPARK: case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: diff --git a/src/lib/orderman/orders/ICENativeOrder.cpp b/src/lib/orderman/orders/ICENativeOrder.cpp index 7c36d2335..5287b5201 100644 --- a/src/lib/orderman/orders/ICENativeOrder.cpp +++ b/src/lib/orderman/orders/ICENativeOrder.cpp @@ -968,7 +968,7 @@ void ICENativeOrder::handle_buffered_state(const std::string& condition) void ICENativeOrder::on_cancel_reject(const orderman::CancelRejectEvent &cr) { auto &state = me->state; - state.set_last_msg(cr.reject_msg); + state.set_last_msg(cr.reject_msg()); LOG(OrderMan, Warn, "Cancel reject received for order {}", key().value()); switch (me->state.status()) diff --git a/testing/manual/orders/order_entry.txt b/testing/manual/orders/order_entry.txt index 6699aa96a..c90e0c651 100644 --- a/testing/manual/orders/order_entry.txt +++ b/testing/manual/orders/order_entry.txt @@ -38,8 +38,6 @@ - Restart the server - Verify that the orders are recreated as well as the fills - Verify you can update and cancel the GTC order - - * Multiple accounts - Enter an order via one account, observe that the fills for that order go into the right place - Repeat on a second account, check the same