From 4c21e328385a703f4e6701e9fd178860af784aaf Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 14 Feb 2020 16:04:39 -0600 Subject: [PATCH] ILink3GW core gateway --- src/lib/orderman/actors/ilink3/ILink3Utils.h | 112 +++++++++ src/lib/orderman/actors/ilink3/ILinkGW.cpp | 237 +++++++++++++++++++ src/lib/orderman/actors/ilink3/ILinkGW.h | 199 ++++++++++++++++ 3 files changed, 548 insertions(+) create mode 100644 src/lib/orderman/actors/ilink3/ILink3Utils.h create mode 100644 src/lib/orderman/actors/ilink3/ILinkGW.cpp create mode 100644 src/lib/orderman/actors/ilink3/ILinkGW.h diff --git a/src/lib/orderman/actors/ilink3/ILink3Utils.h b/src/lib/orderman/actors/ilink3/ILink3Utils.h new file mode 100644 index 000000000..eb69cff44 --- /dev/null +++ b/src/lib/orderman/actors/ilink3/ILink3Utils.h @@ -0,0 +1,112 @@ +#pragma once + +namespace bts { +namespace orderman_v2 { + +const char* translate_business_reject_reason(int reason) { + switch(reason) { + case 0: return "Other"; + case 1: return "Unknown ID (unknown PartyDetailsListReqID being referenced in business message)"; + case 2: return "Unknown Security"; + case 3: return "Unsupported Message Type (for example using messages specific to cash markets for futures)"; + case 5: return "Required Field Missing"; + case 6: return "Not Authorized"; + case 8: return "Throttle Limit Exceeded (volume controls)"; + case 100: return "Value is incorrect (out of range) for this tag (for example using a value outside defined range of integer) "; + case 101: return "Incorrect data format for value (for example using ASCII character outside 32-126 in string field)"; + case 102: return "Rejected due to Kill Switch"; + case 103: return "Rejected due to Risk Management API"; + case 104: return "Rejected due to Globex Credit Controls"; + case 105: return "Not Authorized to trade Deliverable Swap Futures"; + case 106: return "Not Authorized to trade Interest Rate Swap Futures"; + case 107: return "Rejected due to Inline Credit Controls"; + case 108: return "Invalid PartyDetailsListReqID (reusing already existing PartyDetailsListReqID while creating Party Details Definition Request)"; + case 109: return "Incoming message could not be decoded"; + case 110: return "Same repeating group entry appears more than once"; + case 111: return "Exceeded maximum number of allowable Party Details Definition Requests"; + case 112: return "Technical Error in Registering Party Details"; + case 113: return "Rejected due to Cross Venue Risk"; + case 114: return "Order Status Not Available"; + case 115: return "Enum Not Supported"; + case 116: return "Order Status Not Found"; + case 117: return "Mass Order Status Cannot be Completed"; + case 118: return "Exceeded Maximum Number of Allowable RequestingPartyID's in Party Details List Request"; + case 119: return "Duplicate Order Threshold Exceeded"; + case 120: return "On-Demand Message Rejected Due to Preceding Party Details Definition Request Being Rejected"; + case 121: return "Message Rejected Since PartyDetailsListReqID Does Not Match with Immediately Preceding Party Details Definition Request sent to MSGW when using On-demand administrative information"; + case 122: return "Party Details Definition Request sent to MSGW Being Rejected Due to Corresponding Business Message Being Rejected"; + case 123: return "Another Message Sent in Between Party Details Definition Request and Business Message when using On-demand administrative information"; + case 124: return "Cannot Have More Than One In-Flight Mass Order Status Request in Progress"; + case 125: return "Exceeded Maximum Number of In-Flight Order Status Requests"; + case 126: return "Cannot Have More Than One In-Flight Party Details List Request in Progress"; + case 127: return "Party Details List Request is Missing Requesting Party ID and Party ID"; + case 128: return "Party Details List Request cannot contain both RequestingPartyID and PartyID"; + case 129: return "Party Details Definition Request Being Rejected Since Another Message was sent in Between On-Demand Message"; + case 130: return "Buy Side Firm ID Does Not Match Sell Side Firm ID in New Order Cross"; + case 131: return "Message Type Not Supported on Backup Instance"; + case 132: return "New Order Cross Does Not Contain Buy Side Followed by Sell Side"; + } + return "Unknown or invalid business reject reason."; +} + +const char* translate_negotiation_reject(int reason) { + // https://www.cmegroup.com/confluence/display/EPICSANDBOX/Negotiation+Reject + // 01/13/2020 + switch(reason) { + case 0: return "HMACNotAuthenticated: failed authentication because identity is not recognized"; + case 1: return "HMACNotAvailable: HMAC component is not responding (5sec)"; + case 2: return "InvalidUUID: UUID is not greater than the one last used or value sent by the client is out of acceptable range (MIN, MAX)"; + case 3: return "InvalidTimestamp: Timestamp is not greater than the one last used or value sent by the client is out of acceptable range (MIN, MAX)"; + case 4: return "RequiredHMACSignatureMissing: empty bytes in HMACSignature field"; + case 5: return "RequiredAccessKeyIDMissing: empty bytes in AccessKeyID field"; + case 6: return "RequiredSessionMissing: empty bytes in Session field"; + case 7: return "RequiredFirmMissing: empty bytes in Firm field"; + case 8: return "RequiredUUIDMisssing: null value in UUID field"; + case 9: return "RequiredRequestTimestampMissing: null value in RequestTimestamp field"; + case 10: return "SessionBlocked: session and firm are not authorized for this port"; + case 12: return "InvalidAccessKeyID: contains non-printable ASCII character"; + case 13: return "InvalidSession: contains non-printable ASCII character"; + case 14: return "InvalidFirm: contains non-printable ASCII character"; + case 15: return "Volume Controls - exceeding TPS limit as defined for volume controls (reject action)"; + case 16: return "SplitMessageRejected - Messages queued due to split message penalty being rejected because of logout or disconnect"; + case 17: return "SplitMessageQueue - Reached threshold of messages queued due to split message penalty"; + case 27: return "DesignatedBackup - Using Designated backup before designated primary not allowed"; + } + return "Unknown or invalid Negotiate reject reason."; +} + +const char* translate_establish_reject(int reason) { + switch(reason) { + case 0: return "HMACNotAuthenticated: failed authentication because identity is not recognized"; + case 1: return "HMACNotAvailable: HMAC component is not responding (5sec)"; + case 2: return "InvalidUUID: UUID is not greater than the one last used or value sent by the client is out of acceptable range (MIN, MAX)"; + case 3: return "InvalidTimestamp: Timestamp is not greater than the one last used or value sent by the client is out of acceptable range (MIN, MAX)"; + case 4: return "RequiredHMACSignatureMissing: empty bytes in HMACSignature field"; + case 5: return "RequiredAccessKeyIDMissing: empty bytes in AccessKeyID field"; + case 6: return "RequiredSessionMissing: empty bytes in Session field"; + case 7: return "RequiredFirmMissing: empty bytes in Firm field"; + case 8: return "RequiredUUIDMisssing: null value in UUID field"; + case 9: return "RequiredRequestTimestampMissing: null value in RequestTimestamp field"; + case 10: return "SessionBlocked: session and firm are not authorized for this port"; + case 11: return "InvalidKeepAliveInterval: value is out of acceptable range (MIN, MAX)"; + case 12: return "InvalidAccessKeyID: contains non-printable ASCII character"; + case 13: return "InvalidSession: contains non-printable ASCII character"; + case 14: return "InvalidFirm: contains non-printable ASCII character"; + case 15: return "Volume Controls - exceeding TPS limit as defined for volume controls (reject action)"; + case 16: return "SplitMessageRejected - Messages queued due to split message penalty being rejected because of logout or disconnect"; + case 17: return "SplitMessageQueue - Reached threshold of messages queued due to split message penalty"; + case 18: return "RequiredTradingSystemNameMissing: empty bytes in TradingSystemName"; + case 19: return "RequiredTradingSystemVersionMissing: empty bytes in TradingSystemVersion"; + case 20: return "RequiredTradingSystemVendorMissing: empty bytes in TradingSystemVendor"; + case 21: return "RequiredKeepAliveIntervalMissing: null value in KeepAliveInterval field"; + case 22: return "RequiredNextSeqNoMissing: empty bytes in NextSeqNo field"; + case 23: return "InvalidTradingSystemName: contains non-prinatable ASCII character"; + case 24: return "InvalidTradingSystemVersion: contains non-prinatable ASCII character"; + case 25: return "InvalidTradingSystemVendor: contains non-prinatable ASCII character"; + case 26: return "DesignatedBackup - Using Designated backup before designated primary not allowed"; + case 27: return "DesignatedBackup - Using Designated backup before designated primary not allowed"; + } + return "Unknown or invalid Establish reject reason."; +} + +}}//namespace \ No newline at end of file diff --git a/src/lib/orderman/actors/ilink3/ILinkGW.cpp b/src/lib/orderman/actors/ilink3/ILinkGW.cpp new file mode 100644 index 000000000..bab749cae --- /dev/null +++ b/src/lib/orderman/actors/ilink3/ILinkGW.cpp @@ -0,0 +1,237 @@ +#include "ILinkGW.h" +#include "lib/utils/bts_assert.h" +#include "lib/utils/SecureLogon.h" + +namespace bts { +namespace orderman { +namespace ilink3 { + +ILinkGW::ILinkGW(IConnection& con, const Config& conf) : + _config(conf), + _xstate(State::INIT), + _buffer_size(16384), + _next(0), + buffer(new char[_buffer_size]), + _on_state_change([](auto){}), + _connection(con), + _timestamp(datetime::unix_nano_now()) +{ + _session = determine_session(); +} + +void ILinkGW::connect() { + bts_assert(state() == State::INIT); + set_state(State::CONNECTING); + _connection.connect(); // -> on_connect_success +} + +void ILinkGW::send_negotiate() { + // add 2 bytes for the empty 'credentials' (39008) length which must be present + auto msg = frame(2); + // constant msg.customerFlow() + // constant msg.hMACVersion() + msg.uUID(_session); + msg.requestTimestamp(_timestamp); + msg.putSession(_config.session); + // Need this call to set the length of the credential block to 0 + msg.putCredentials(""); + msg.putFirm(_config.firm); + const auto ld = glbx::calculate_hmac( + _config.session, + std::to_string(msg.requestTimestamp()), + std::to_string(msg.uUID()), + _config.session, + _config.firm + ); + msg.putAccessKeyID(ld.access_key); + msg.putHMACSignature(ld.hmac); + + flush(); +} + +void ILinkGW::send_order(const CreateOrderMsg&) { +} + +void ILinkGW::send_cancel_replace(const CancelReplaceOrderMsg&) { +} + +void ILinkGW::send_cancel(const CancelOrderMsg&) { +} + +void ILinkGW::flush() { + _connection.send(std::string_view(buffer.get(), _buffer_size)); + memset(buffer.get(), 0, _next); + _next = 0; + _timestamp = datetime::unix_nano_now(); +} + +uint64_t ILinkGW::determine_session() { + return utils::TimeStamp::now().to_uint64(); +} + +std::string state_string(State s) { + switch(s) { + case State::INIT: return "INIT"; + case State::CONNECTING: return "CONNECTING"; + case State::NEGOTATING: return "NEGOTATING"; + case State::TRANSFER: return "TRANSFER"; + case State::READY: return "READY"; + case State::BUFFERING: return "BUFFERING"; + case State::ERROR: return "ERROR"; + } + return "UNKNOWN"; +} +void ILinkGW::set_state(State s) { + LOG(OrderMan, Diag, "ILinkGW {}: {}->{}", + _session, state_string(_xstate), state_string(s)); + _xstate = s; + if (_on_state_change) _on_state_change(s); +} + + +// +// IConnectionHandler + +void ILinkGW::on_connect_success() { + set_state(State::NEGOTATING); + send_negotiate(); +} +void ILinkGW::on_disconnect() { + LOG(OrderMan, Error, "Disconnected."); + set_state(State::ERROR); + if (_config.failover_on_disconnect) { + LOG(OrderMan, Error, "Attempting failover"); + _connection.failover(); + connect(); + } +} +size_t ILinkGW::on_data(const char* data, size_t len) { + if (len <= sizeof(FramingHeader)) return 0; + size_t read = 0; + do { + // read the FramingHeader + const FramingHeader* header = reinterpret_cast(data); + // Check if we can consume the message + auto msize = header->message_size; + if (msize <= len) { + read += msize; + on_message(header, data); + data += msize; + len -= msize; + } + else { + return read; + } + } while(len > sizeof(FramingHeader)); + return read; +} + +void ILinkGW::on_message(const FramingHeader* header, const char* data) { + using namespace iLinkBinary; + bts_assert_d(header->encoding_type == 0XCAFE); + MessageHeader mheader { + (char*)data, sizeof(FramingHeader), header->message_size, + MessageHeader::sbeSchemaVersion() }; + constexpr size_t offset = sizeof(FramingHeader) + mheader.encodedLength(); + + switch(mheader.templateId()) { + // Originally generated by a tool - operations/codegen/ilink3gen + case 501: handle(data, offset, header->message_size); break; + case 502: handle(data, offset, header->message_size); break; + case 504: handle(data, offset, header->message_size); break; + case 505: handle(data, offset, header->message_size); break; + case 506: handle(data, offset, header->message_size); break; + case 507: handle(data, offset, header->message_size); break; + case 509: handle(data, offset, header->message_size); break; + case 510: handle(data, offset, header->message_size); break; + case 513: handle(data, offset, header->message_size); break; + case 519: handle(data, offset, header->message_size); break; + case 521: handle(data, offset, header->message_size); break; + case 522: handle(data, offset, header->message_size); break; + case 523: handle(data, offset, header->message_size); break; + case 524: handle(data, offset, header->message_size); break; + case 525: handle(data, offset, header->message_size); break; + case 526: handle(data, offset, header->message_size); break; + case 527: handle(data, offset, header->message_size); break; + case 531: handle(data, offset, header->message_size); break; + case 532: handle(data, offset, header->message_size); break; + case 534: handle(data, offset, header->message_size); break; + case 535: handle(data, offset, header->message_size); break; + case 536: handle(data, offset, header->message_size); break; + // case 538: handle(data, offset, header->message_size); break; + case 539: handle(data, offset, header->message_size); break; + // case 544: handle(data, offset, header->message_size); break; + // case 545: handle(data, offset, header->message_size); break; + // case 546: handle(data, offset, header->message_size); break; + // case 547: handle(data, offset, header->message_size); break; + case 548: handle(data, offset, header->message_size); break; + case 549: handle(data, offset, header->message_size); break; + case 550: handle(data, offset, header->message_size); break; + // case 558: handle(data, offset, header->message_size); break; + // case 561: handle(data, offset, header->message_size); break; + } +} + +// Message Handlers +void ILinkGW::handle(const iLinkBinary::NegotiationResponse501&) { +} +void ILinkGW::handle(const iLinkBinary::NegotiationReject502&) { +} +void ILinkGW::handle(const iLinkBinary::EstablishmentAck504&) { +} +void ILinkGW::handle(const iLinkBinary::EstablishmentReject505&) { +} +void ILinkGW::handle(const iLinkBinary::Sequence506&) { +} +void ILinkGW::handle(const iLinkBinary::Terminate507&) { +} +void ILinkGW::handle(const iLinkBinary::Retransmission509&) { +} +void ILinkGW::handle(const iLinkBinary::RetransmitReject510&) { +} +void ILinkGW::handle(const iLinkBinary::NotApplied513&) { +} +void ILinkGW::handle(const iLinkBinary::PartyDetailsDefinitionRequestAck519&) { +} +void ILinkGW::handle(const iLinkBinary::BusinessReject521&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportNew522&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportReject523&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportElimination524&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeOutright525&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpread526&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeSpreadLeg527&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportModify531&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportStatus532&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportCancel534&) { +} +void ILinkGW::handle(const iLinkBinary::OrderCancelReject535&) { +} +void ILinkGW::handle(const iLinkBinary::OrderCancelReplaceReject536&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionAck539&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumOutright548&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumSpread549&) { +} +void ILinkGW::handle(const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550&) { +} + +void ILinkGW::reallocate(size_t sz) { + sz = std::max(sz, _buffer_size*2); + std::unique_ptr new_buffer(new char[sz]); + memcpy(new_buffer.get(), buffer.get(), _buffer_size); + _buffer_size = sz; + buffer.swap(new_buffer); +} + +}}} //namespace diff --git a/src/lib/orderman/actors/ilink3/ILinkGW.h b/src/lib/orderman/actors/ilink3/ILinkGW.h new file mode 100644 index 000000000..16875a9e4 --- /dev/null +++ b/src/lib/orderman/actors/ilink3/ILinkGW.h @@ -0,0 +1,199 @@ +#include +#include +#include +#include + +#include "../IExecutionGateway.h" + +// +// Message templates + +// BTS -> CME +#include "generated/Negotiate500.h" +#include "generated/Establish503.h" +#include "generated/RetransmitRequest508.h" +#include "generated/NewOrderSingle514.h" +#include "generated/OrderCancelReplaceRequest515.h" +#include "generated/OrderCancelRequest516.h" +// #include "generated/MassQuote517.h" +#include "generated/PartyDetailsDefinitionRequest518.h" +// #include "generated/QuoteCancel528.h" +// #include "generated/OrderMassActionRequest529.h" +// #include "generated/OrderMassStatusRequest530.h" +// #include "generated/OrderStatusRequest533.h" +// #include "generated/PartyDetailsListRequest537.h" +// #include "generated/RequestForQuote543.h" +// #include "generated/SecurityDefinitionRequest560.h" + +// CME -> BTS +#include "generated/NegotiationResponse501.h" +#include "generated/NegotiationReject502.h" +#include "generated/EstablishmentAck504.h" +#include "generated/EstablishmentReject505.h" +#include "generated/Sequence506.h" +#include "generated/Terminate507.h" +#include "generated/Retransmission509.h" +#include "generated/RetransmitReject510.h" +#include "generated/NotApplied513.h" +#include "generated/PartyDetailsDefinitionRequestAck519.h" +#include "generated/BusinessReject521.h" +#include "generated/ExecutionReportNew522.h" +#include "generated/ExecutionReportReject523.h" +#include "generated/ExecutionReportElimination524.h" +#include "generated/ExecutionReportTradeOutright525.h" +#include "generated/ExecutionReportTradeSpread526.h" +#include "generated/ExecutionReportTradeSpreadLeg527.h" +#include "generated/ExecutionReportModify531.h" +#include "generated/ExecutionReportStatus532.h" +#include "generated/ExecutionReportCancel534.h" +#include "generated/OrderCancelReject535.h" +#include "generated/OrderCancelReplaceReject536.h" +// #include "generated/PartyDetailsListReport538.h" +#include "generated/ExecutionAck539.h" +// #include "generated/NewOrderCross544.h" +// #include "generated/MassQuoteAck545.h" +// #include "generated/RequestForQuoteAck546.h" +// #include "generated/QuoteCancelAck547.h" +#include "generated/ExecutionReportTradeAddendumOutright548.h" +#include "generated/ExecutionReportTradeAddendumSpread549.h" +#include "generated/ExecutionReportTradeAddendumSpreadLeg550.h" +// #include "generated/OrderMassActionReport558.h" +// #include "generated/SecurityDefinitionResponse561.h" + +namespace bts { +namespace orderman { +namespace ilink3 { + +struct IConnectionHandler { + virtual void on_connect_success() = 0; + virtual void on_disconnect() = 0; + // Send available data and length. Handler will return what it consumed + virtual size_t on_data(const char* data, size_t len) = 0; +}; +struct IConnection { + virtual void connect() = 0; + virtual void disconnect() = 0; + virtual void failover() = 0; + virtual void send(const std::string_view) = 0; +}; + +struct Config { + std::string session; // NGG + std::string firm; // 004 + bool failover_on_disconnect; +}; + +enum class State { + INIT, + CONNECTING, + NEGOTATING, + TRANSFER, + READY, + BUFFERING, // ready for flush + ERROR +}; +typedef std::function OnStateChange; + +struct FramingHeader { + uint16_t message_size; + uint16_t encoding_type; +}; + + +// Does not allow re-entrance +class ILinkGW : IConnectionHandler { + Config _config; + State _xstate; + size_t _buffer_size; + size_t _next; + std::unique_ptr buffer; + OnStateChange _on_state_change; + IConnection& _connection; + uint64_t _session; + uint64_t _timestamp; +public: + ILinkGW(IConnection&, const Config&); + + void connect(); + void send_negotiate(); + void send_order(const CreateOrderMsg&); + void send_cancel_replace(const CancelReplaceOrderMsg&); + void send_cancel(const CancelOrderMsg&); + void flush(); + + // state change + State state() { return _xstate; } + void watch_state(OnStateChange o) { _on_state_change = o; } + +private: // Functions + uint64_t determine_session(); + void set_state(State); + + void on_connect_success() override; + void on_disconnect() override; + size_t on_data(const char* data, size_t len) override; + void on_message(const FramingHeader*, const char* data); + + // + // Message handlers + + template + void handle(const char* data, size_t offset, uint16_t len) { + handle(T { const_cast(data), offset, len, T::sbeBlockLength(), T::sbeSchemaVersion() }); + } + + 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::ExecutionAck539&); + void handle(const iLinkBinary::ExecutionReportTradeAddendumOutright548&); + void handle(const iLinkBinary::ExecutionReportTradeAddendumSpread549&); + void handle(const iLinkBinary::ExecutionReportTradeAddendumSpreadLeg550&); + + + // + // Framing + template + Msg frame(size_t extra) { + auto size = + sizeof(FramingHeader) + + iLinkBinary::MessageHeader::encodedLength() + + Msg::sbeBlockLength() + + extra; + auto end = _next + size; + if (end > _buffer_size) { + // Guaranteed to be enough space in buffer by after the realloc call + reallocate(end); + } + FramingHeader* fhead = reinterpret_cast(&buffer[_next]); + fhead->message_size = size; + fhead->encoding_type = 0xCAFE; + Msg msg; + msg.wrapAndApplyHeader(&buffer[_next], sizeof(FramingHeader), size+sizeof(FramingHeader)); + return msg; + } + void reallocate(size_t); + + +}; + +}}} //namespace