#include "ExecutionGateway.h" #include "lib/jetfix/codec/MessageDefinitions.h" #include "lib/jetfix/common/OutFIX.h" #include "lib/jetfix/gateway/JetFIXGateway.h" #include "lib/logging/logging.h" #include "lib/md/SecurityOracle.h" #include "lib/orderman/events/CancelRejectEvent.h" #include "lib/orderman/events/GatewayStatusChangeEvent.h" #include "lib/orderman/events/NewExecutionReportEvent.h" #include "lib/orderman/events/NewSecuritiesEvent.h" #include "lib/orderman/orderman_utils/fix_order_codec.h" #include "lib/tracing/bts_trace.h" #include "lib/utils/TimeStamp.h" #include "lib/utils/bts_chrono.h" #include namespace bts { namespace orderman { using namespace jetfix; using JFGw = JetFIXGateway; struct ExecutionGateway::PImpl { PImpl(config::JetFIX::Connection const &cfg, trace::PerfLog &l, md::SecurityOracle o) : gw(cfg, l), exe_report_pool(), state(State::WAITING_FOR_SECURITIES), securities(), securities_by_descriptor(), gw_name(cfg.name()), cfg(cfg), perf_log(l), sec_oracle(o) {} JFGw gw; boost::object_pool exe_report_pool; State state; std::unordered_map securities; std::unordered_map securities_by_descriptor; GatewayName gw_name; config::JetFIX::Connection cfg; OnExeReport on_exe_report; OnGwStatusChange on_gw_status_change; OnCancelReject on_cancel_reject; trace::PerfLog &perf_log; md::SecurityOracle sec_oracle; }; ExecutionGateway::ExecutionGateway(config::JetFIX::Connection const &cfg, trace::PerfLog &log, md::SecurityOracle o) : me(new PImpl(cfg, log, o)) { me->state = State::WAITING_FOR_SECURITIES; } ExecutionGateway::~ExecutionGateway() {} void ExecutionGateway::on_securities( const mercury::Update &update) { if (update.events) { for (auto const &ev : *(update.events)) { auto sec_ptr = ev.security; me->securities[sec_ptr->id()] = sec_ptr; me->securities_by_descriptor[securities::descriptor(*sec_ptr)] = sec_ptr; } if (me->state == State::WAITING_FOR_SECURITIES) { LOG(OrderMan, Warn, "Received first set of {} securities. Proceeding " "with initialization of execution gateway {}", update.events->size(), me->gw_name.value()); // got our security synopsis, ready to start the GW me->state = State::READY; // subscribe to gateway events me->gw.on() = [this](auto const &msg) { this->on_exe_report(msg); }; me->gw.on() = [this](auto const &msg) { this->on_cancel_reject(msg); }; me->gw.on_ready() = [this]() { this->on_connection_status_change(true); }; me->gw.on_disconnect() = [this]() { this->on_connection_status_change(false); }; me->gw.on() = [this](auto const &m) { this->on_business_reject(m); }; me->gw.on() = [this](auto const &m) { this->on_session_reject(m); }; } } } void ExecutionGateway::start() { me->gw.start(); } OnExeReport &ExecutionGateway::on_exe_report() { return me->on_exe_report; } OnGwStatusChange &ExecutionGateway::on_gw_status_change() { return me->on_gw_status_change; } OnCancelReject &ExecutionGateway::on_cancel_reject() { return me->on_cancel_reject; } void ExecutionGateway::on_exe_report( const jetfix::fix::ExecutionReportMsg &msg) { OrderKey ok; SecurityKey sk; decode_clorid(msg.get(), &ok, &sk); auto scoped_log = trace::log_scope(me->perf_log, msg.trace(), "ExecutionGateway::on_exe_report", ok.value()); LOG(Latency, Info, "Started handling of execution report for order {}", ok.value()); auto &sec = me->securities[sk.value()]; if (!sec) { sec = me->sec_oracle.get_security(SecurityKey(sk.value())); me->securities_by_descriptor[securities::descriptor(*sec)] = sec; } if (!sec) LOG(OrderMan, Error, "Received execution report for an unknown security {}. Will not be " " able to process this report. This is likely a bug that could lead " "to" " lost fills. Please investigate.", sk.value()); else { // Ignore trade correction messages. CME does not included the full // id of the trade being corrected and we have no way of // resolving it here. We could still parse the correction and // push the resolution problem downstream but that would make // downstream code CME specific and generate a fair amout of // complexity for a rare and moderately benign event (the only // thing that can be corrected is the fill price). We might come // back to this when the system is more mature. if (msg.get() == api::orderman::EXEC_TYPE_TRADE_CORRECT) { auto new_price = securities::decode_exchange_price( *sec, Price(msg.get())); auto ref_exec_id = msg.get(); LOG(OrderMan, Error, "Received unsupported trade correction msg. " "This correction will not be forwarded. The trader should be " "alerted. " "Order: {} SecKey: {} Partial original fill id: {}. New price: {}", ok.value(), sk.value(), ref_exec_id, new_price.value()); return; } // Ignore unsupported trade cancelation messages. if (msg.get() == api::orderman::EXEC_TYPE_TRADE_CANCEL) { LOG(OrderMan, Error, "Received unsupported trade cancel msg. " "This correction will not be forwarded. The trader should be " "alerted. " "Order: {} SecKey: {} ", ok.value(), sk.value()); return; } api::Security const *leg_security = nullptr; if (msg.has() && msg.get() == 2) { auto it = me->securities_by_descriptor.find(msg.get()); if (it == me->securities_by_descriptor.end()) { LOG(OrderMan, Error, "Received execution report for an unknown spread leg" "security {}. Will not be " " able to process this report. This is likely a " "bug that could lead to" " lost leg fills. Please investigate. Spread sec_key: {} leg " "exchange " "desc: {}", sk.value(), msg.get()); return; } leg_security = it->second; } std::string text_msg; if (msg.has()) text_msg = msg.get(); // allocate from our pool auto data = me->exe_report_pool.construct(); data->exec_type = api::orderman::ExecType(msg.get()); data->msg_seq_num = msg.get(); // copy data from fix msg to our structure if (msg.has()) str_to(msg.get(), &data->account_name); if (msg.has()) str_to(msg.get(), &data->operator_id); data->order_key = ok; data->security = sec; data->leg_security = leg_security; data->side = api::Side(msg.get()); if (msg.has()) data->time_in_force = api::orderman::TimeInForce(msg.get()); else data->time_in_force = api::orderman::TIME_IN_FORCE_UNDEFINED; data->order_type = api::orderman::NativeOrderType(msg.get()); data->order_status = api::orderman::NativeOrderStatus(msg.get()); data->manual_order_indicator = msg.get() ? api::orderman::MANUAL_ORDER_INDICATOR_YES : api::orderman::MANUAL_ORDER_INDICATOR_YES; str_to(msg.get(), &data->exchange_order_id); if (msg.has()) data->price = securities::decode_exchange_price( *sec, Price(msg.get())); else data->price = Price(os::nan()); if (msg.has()) data->stop_price = securities::decode_exchange_price( *sec, Price(msg.get())); else data->stop_price = Price(os::nan()); if (msg.has()) data->max_show = Quantity(msg.get()); else data->max_show = Quantity(0); if (msg.has()) data->quantity = Quantity(msg.get()); else data->quantity = Quantity(0); data->filled_quantity = Quantity(msg.get()); data->last_shares = msg.has() ? Quantity(msg.get()) : Quantity(0); auto last_px_sec = data->leg_security ? data->leg_security : sec; data->last_price = msg.has() ? securities::decode_exchange_price( *last_px_sec, Price(msg.get())) : Price(0); data->avg_price = msg.has() ? securities::decode_exchange_price( *last_px_sec, Price(msg.get())) : Price(0); if (msg.has()) str_to(msg.get(), &data->exchange_fill_id); str_to(msg.get(), &data->transact_time); data->cfg = &me->cfg; data->msg = text_msg; me->on_exe_report(*data, msg.trace()); } } void ExecutionGateway::on_cancel_reject( const jetfix::fix::CancelRejectMsg &msg) { OrderKey ok; SecurityKey sk; decode_clorid(msg.get(), &ok, &sk); std::string reject_msg; if (msg.has()) reject_msg = msg.get(); else if (msg.has()) reject_msg = fmt::format("Order cancel was rejected with error code {}", msg.get()); me->on_cancel_reject(ok, reject_msg); } void ExecutionGateway::on_connection_status_change(bool is_connected) { LOG(OrderMan, Info, "Connection state of {} changed to {}", me->gw_name.value(), is_connected ? std::string("connected") : std::string("disconnected")); me->on_gw_status_change(is_connected); } void ExecutionGateway::on_business_reject( jetfix::fix::BusinessMessageRejectMsg const &m) { LOG(OrderMan, Error, "Unexpected business reject in {} gateway . Reason: " "{}. This should be investigated", me->gw_name.value(), m.has() ? m.get() : std::string("Unknown")); } void ExecutionGateway::on_session_reject(jetfix::fix::RejectMsg const &m) { LOG(OrderMan, Error, "Unexpected reject message in {} gateway . Reason: {}. " "This should be investigated", me->gw_name.value(), m.has() ? m.get() : std::string("Unknown")); } void ExecutionGateway::dispatch_incoming_fix_messages() { me->gw.dispatch_events(); } void ExecutionGateway::send_fix(jetfix::OutFIXPtr const &fix, trace::CorID trace) { auto scoped_log = trace::log_scope(me->perf_log, trace, "ExecutionGateway::send_fix"); me->gw.send(fix, trace); me->gw.dispatch_events(); } } // namespace orderman } // namespace bts