diff --git a/src/lib/orderman/actors/ilink3/IL3Dispatcher.h b/src/lib/orderman/actors/ilink3/IL3Dispatcher.h index 36c97ae30..167e3f38b 100644 --- a/src/lib/orderman/actors/ilink3/IL3Dispatcher.h +++ b/src/lib/orderman/actors/ilink3/IL3Dispatcher.h @@ -9,13 +9,13 @@ namespace ilink3 { template void handle(Handler& h, const char* data, uint16_t len) { - h.handle( - T { - const_cast(data), - sizeof(FramingHeader) + iLinkBinary::MessageHeader::encodedLength(), - len, - T::sbeBlockLength(), - T::sbeSchemaVersion() }); + T t { + const_cast(data), + sizeof(FramingHeader) + iLinkBinary::MessageHeader::encodedLength(), + len, + T::sbeBlockLength(), + T::sbeSchemaVersion() }; + h.handle(t); } diff --git a/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.cpp b/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.cpp index 6a21a444b..0e5ed0ba5 100644 --- a/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.cpp +++ b/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.cpp @@ -9,8 +9,10 @@ namespace bts { namespace orderman { namespace ilink3 { -IL3ExecutionReportParser::IL3ExecutionReportParser(md::SecurityOracle* o): oracle(o) { -} +IL3ExecutionReportParser::IL3ExecutionReportParser(md::SecurityOracle* o): + oracle(o), + most_recent_account() +{} void IL3ExecutionReportParser::cache(const api::Security* security) { auto id = SecurityKey { security->id() }; @@ -32,7 +34,8 @@ const api::Security* IL3ExecutionReportParser::get_security(SecurityKey id) { template void IL3ExecutionReportParser::common(const T& msg, ExecutionReport* data) { - // data->account_name ?? + data->account_name = most_recent_account; + static_assert(sizeof(OperatorID) == T::senderIDLength()); memcpy(&data->operator_id.value(), msg.senderID(), msg.senderIDLength()); auto& price = const_cast(msg).price(); @@ -126,7 +129,19 @@ bool IL3ExecutionReportParser::parse(const iLinkBinary::ExecutionReportCancel534 data->order_status = api::orderman::NativeOrderStatus::NATIVE_ORDER_STATUS_CANCELED; return true; } - +void IL3ExecutionReportParser::set_account(const iLinkBinary::PartyDetailsDefinitionRequestAck519& msg) { + // When using on-demand format the PartyDetailsDefinitionRequestAck519 + // is sent back immediately preceding the execution report on the wire. + auto details =const_cast (msg).noPartyDetails(); + while(details.hasNext()) { + details.next(); + if (details.partyDetailRole() == iLinkBinary::PartyDetailRole::CustomerAccount) { + const char* p_account = details.partyDetailID(); + strncpy(most_recent_account.value().data(), p_account, most_recent_account.value().size()); + break; + } + } +} struct ParseHandler { IL3ExecutionReportParser& parser; @@ -134,10 +149,10 @@ struct ParseHandler { bool success = false; template void handle(const T& t) { success = parser.parse(t, result); } + void handle(iLinkBinary::PartyDetailsDefinitionRequestAck519& t) { parser.set_account(t); } }; -bool parse_report(const std::string& data, md::SecurityOracle& oracle, ExecutionReport* result) { - IL3ExecutionReportParser parser(&oracle); +bool parse_report(const std::string& data, IL3ExecutionReportParser& parser, ExecutionReport* result) { ParseHandler handler { parser, result }; consume_messages(handler, data.c_str(), data.size(), dispatch_execution_reports); return handler.success; diff --git a/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.h b/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.h index 286d86fd0..6d9b8f1d7 100644 --- a/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.h +++ b/src/lib/orderman/actors/ilink3/IL3ExecutionReportParser.h @@ -14,6 +14,7 @@ namespace ilink3 { class IL3ExecutionReportParser { btree::btree_map security_cache; md::SecurityOracle* oracle; + AccountName most_recent_account; const api::Security* get_security(SecurityKey); @@ -30,10 +31,11 @@ public: bool parse(const iLinkBinary::ExecutionReportModify531&, ExecutionReport*); bool parse(const iLinkBinary::ExecutionReportStatus532&, ExecutionReport*); bool parse(const iLinkBinary::ExecutionReportCancel534&, ExecutionReport*); + void set_account(const iLinkBinary::PartyDetailsDefinitionRequestAck519&); template void common(const T&, ExecutionReport*); }; -bool parse_report(const std::string&, md::SecurityOracle&, ExecutionReport*); +bool parse_report(const std::string&, IL3ExecutionReportParser&, ExecutionReport*); }}}//namespace diff --git a/src/lib/orderman/actors/ilink3/ILinkGW.cpp b/src/lib/orderman/actors/ilink3/ILinkGW.cpp index 31ca0ae33..ce7c30f9f 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 "IL3Dispatcher.h" -#include "IL3GeneratedFull.h" -#include "IL3MessageFramer.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/SecureLogon.h" +#include "ILink3Utils.h" +#include "IL3GeneratedFull.h" +#include "IL3Dispatcher.h" +#include "IL3MessageFramer.h" #include "lib/utils/datetime.h" +#include "lib/orderman/orderman_utils/fix_order_codec.h" /* # Some notes about session binding and initialization: # @@ -33,15 +33,28 @@ 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, - md::SecurityOracle *oracle, const Session &session, - const Config &conf) - : _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(oracle), _retransmit() { +ILinkGW::ILinkGW( + IL3Connection& con, + IL3MessageFramer& buffer, + md::SecurityOracle* oracle, + const Session& session, + const Config& conf) : + _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(oracle), + _retransmit() +{ _clorid_buffer.resize(clordid_sz()); } @@ -53,10 +66,9 @@ 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); @@ -66,27 +78,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}); + msg.putHMACSignature(std::string_view { nullptr, 0 }); log_out(msg); // 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()); @@ -97,34 +109,34 @@ 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()), + // 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}); + msg.putHMACSignature(std::string_view { nullptr, 0 }); log_out(msg); // expect -> EstablishmentAck504 or EstablishmentReject505 } @@ -134,14 +146,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); + msg.keepAliveIntervalLapsed( + lapsed ? + iLinkBinary::KeepAliveLapsed::Lapsed : + iLinkBinary::KeepAliveLapsed::NotLapsed); log_out(msg); } -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(); @@ -153,20 +165,18 @@ void ILinkGW::send_retransmit_request(uint64_t uuid, uint32_t from, log_out(msg); } -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); @@ -174,25 +184,25 @@ 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()); @@ -204,32 +214,28 @@ 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 + // In the future we may check for existing party details definitions and return that id log_out(msg); 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()); @@ -237,44 +243,36 @@ 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); @@ -285,8 +283,8 @@ void ILinkGW::send_order(const CreateOrderMsg &create) { log_out(msg); } -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()); @@ -296,35 +294,27 @@ 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); @@ -334,7 +324,7 @@ void ILinkGW::send_cancel_replace(const CancelReplaceOrderMsg &replace) { log_out(msg); } -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()); @@ -344,12 +334,10 @@ 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()); @@ -371,26 +359,18 @@ void ILinkGW::send_terminate(uint16_t code) { 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"; } @@ -398,11 +378,10 @@ 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); } } @@ -411,15 +390,14 @@ 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(); @@ -432,31 +410,33 @@ 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); } @@ -464,49 +444,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); - // 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()))); +void ILinkGW::handle(const iLinkBinary::NegotiationReject502& msg) { + LOG(iLink3, Error, "Negotiate Reject: {} '{}'.", + msg.errorCodes(), + std::string(translate_negotiation_reject(msg.errorCodes()))); log_in(msg); _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(); @@ -525,7 +505,7 @@ 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; @@ -536,22 +516,23 @@ void ILinkGW::handle(const iLinkBinary::EstablishmentAck504 &msg) { 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); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::Sequence506 &msg) { +void ILinkGW::handle(const iLinkBinary::Sequence506& msg) { log_in(msg); _session.from_cme = msg.nextSeqNo() - 1; publish_session_update(); @@ -566,6 +547,7 @@ void ILinkGW::handle(const iLinkBinary::Terminate507 &msg) { 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 ++; publish_session_update(); } @@ -573,28 +555,27 @@ void ILinkGW::handle(const iLinkBinary::Terminate507 &msg) { _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); } -void ILinkGW::handle(const iLinkBinary::RetransmitReject510 &msg) { - LOG(iLink3, Error, "Retransmit requeste rejected. {}", - msg.getReasonAsString()); +void ILinkGW::handle(const iLinkBinary::RetransmitReject510& msg) { + LOG(iLink3, Error, "Retransmit requeste rejected. {}", msg.getReasonAsString()); log_in(msg); set_state(State::ERROR); } -void ILinkGW::handle(const iLinkBinary::NotApplied513 &msg) { +void ILinkGW::handle(const iLinkBinary::NotApplied513& msg) { log_in(msg); send_sequence(); } -void ILinkGW::handle( - const iLinkBinary::PartyDetailsDefinitionRequestAck519 &msg) { - // Future: store party details id +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 @@ -602,65 +583,60 @@ 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); handle_common(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) { handle_common(msg); // TODO: log } -void ILinkGW::handle(const iLinkBinary::OrderCancelReplaceReject536 &msg) { +void ILinkGW::handle(const iLinkBinary::OrderCancelReplaceReject536& msg) { handle_common(msg); // TODO: log } -void ILinkGW::handle(const iLinkBinary::ExecutionAck539 &) { +void ILinkGW::handle(const iLinkBinary::ExecutionAck539&) { // 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 ilink3 -} // namespace orderman -} // namespace bts +}}} //namespace