Files
spark/src/lib/orderman/actors/GLBXExecutionGateway.cpp
T

338 lines
12 KiB
C++

#include "GLBXExecutionGateway.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 <boost/pool/object_pool.hpp>
namespace bts {
namespace orderman {
using namespace jetfix;
using JFGw =
JetFIXGateway<fix::ExecutionReportMsg, fix::BusinessMessageRejectMsg,
fix::RejectMsg, fix::CancelRejectMsg>;
struct GLBXExecutionGateway::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<ExecutionReport> exe_report_pool;
State state;
std::unordered_map<SecurityKey::Value, api::Security const *> securities;
std::unordered_map<std::string, api::Security const *>
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;
};
GLBXExecutionGateway::GLBXExecutionGateway(config::JetFIX::Connection const &cfg,
trace::PerfLog &log, md::SecurityOracle o)
: me(new PImpl(cfg, log, o)) {
me->state = State::WAITING_FOR_SECURITIES;
}
GLBXExecutionGateway::~GLBXExecutionGateway() {}
void GLBXExecutionGateway::on_admin_data(const mercury::Update<NewAdminDataEvent> &) {}
void GLBXExecutionGateway::on_securities(
const mercury::Update<NewSecuritiesEvent> &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<fix::ExecutionReportMsg>() = [this](auto const &msg) {
this->on_exe_report(msg);
};
me->gw.on<fix::CancelRejectMsg>() = [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<fix::BusinessMessageRejectMsg>() = [this](auto const &m) {
this->on_business_reject(m);
};
me->gw.on<fix::RejectMsg>() = [this](auto const &m) {
this->on_session_reject(m);
};
}
}
}
void GLBXExecutionGateway::start() { me->gw.start(); }
OnExeReport &GLBXExecutionGateway::on_exe_report() { return me->on_exe_report; }
OnGwStatusChange &GLBXExecutionGateway::on_gw_status_change() {
return me->on_gw_status_change;
}
OnCancelReject &GLBXExecutionGateway::on_cancel_reject() {
return me->on_cancel_reject;
}
void GLBXExecutionGateway::on_exe_report(
const jetfix::fix::ExecutionReportMsg &msg) {
OrderKey ok;
SecurityKey sk;
decode_clorid(msg.get<fix::ClOrdID>(), &ok, &sk);
auto scoped_log =
trace::log_scope(me->perf_log, msg.trace(),
"GLBXExecutionGateway::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<fix::ExecType>() == api::orderman::EXEC_TYPE_TRADE_CORRECT) {
auto new_price = securities::decode_exchange_price(
*sec, Price(msg.get<fix::LastPx>()));
auto ref_exec_id = msg.get<fix::ExecRefID>();
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<fix::ExecType>() == 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<fix::MultiLegReportingType>() &&
msg.get<fix::MultiLegReportingType>() == 2) {
auto it =
me->securities_by_descriptor.find(msg.get<fix::SecurityDesc>());
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<fix::SecurityDesc>());
return;
}
leg_security = it->second;
}
std::string text_msg;
if (msg.has<fix::Text>())
text_msg = msg.get<fix::Text>();
// allocate from our pool
auto data = me->exe_report_pool.construct();
data->exec_type = api::orderman::ExecType(msg.get<fix::ExecType>());
data->msg_seq_num = msg.get<fix::MsgSeqNum>();
// copy data from fix msg to our structure
if (msg.has<fix::Account>())
str_to(msg.get<fix::Account>(), &data->account_name);
if (msg.has<fix::TargetSubID>())
str_to(msg.get<fix::TargetSubID>(), &data->operator_id);
data->order_key = ok;
data->security = sec;
data->leg_security = leg_security;
data->side = api::Side(msg.get<fix::Side>());
if (msg.has<fix::TimeInForce>())
data->time_in_force =
api::orderman::TimeInForce(msg.get<fix::TimeInForce>());
else
data->time_in_force = api::orderman::TIME_IN_FORCE_UNDEFINED;
data->order_type =
api::orderman::NativeOrderType(msg.get<fix::OrdType>());
data->order_status =
api::orderman::NativeOrderStatus(msg.get<fix::OrdStatus>());
data->manual_order_indicator =
msg.get<fix::ManualOrderIndicator>()
? api::orderman::MANUAL_ORDER_INDICATOR_YES
: api::orderman::MANUAL_ORDER_INDICATOR_YES;
str_to(msg.get<fix::OrderID>(),
& std::get<ExchangeOrderID>(
data->exchange_order_id));
if (msg.has<fix::Price>())
data->price = securities::decode_exchange_price(
*sec, Price(msg.get<fix::Price>()));
else
data->price = Price(os::nan());
if (msg.has<fix::StopPx>())
data->stop_price = securities::decode_exchange_price(
*sec, Price(msg.get<fix::StopPx>()));
else
data->stop_price = Price(os::nan());
if (msg.has<fix::MaxShow>())
data->max_show = Quantity(msg.get<fix::MaxShow>());
else
data->max_show = Quantity(0);
if (msg.has<fix::OrderQty>())
data->quantity = Quantity(msg.get<fix::OrderQty>());
else
data->quantity = Quantity(0);
data->filled_quantity = Quantity(msg.get<fix::CumQty>());
data->last_shares = msg.has<fix::LastShares>()
? Quantity(msg.get<fix::LastShares>())
: Quantity(0);
auto last_px_sec = data->leg_security ? data->leg_security : sec;
data->last_price = msg.has<fix::LastPx>()
? securities::decode_exchange_price(
*last_px_sec, Price(msg.get<fix::LastPx>()))
: Price(0);
data->avg_price = msg.has<fix::AvgPx>()
? securities::decode_exchange_price(
*last_px_sec, Price(msg.get<fix::AvgPx>()))
: Price(0);
if (msg.has<fix::ExecID>())
str_to(msg.get<fix::ExecID>(), &data->exchange_fill_id);
orderman::ExchangeTimeStampStr t;
str_to(msg.get<fix::TransactTimeStr>(), &t);
data->transact_time = t;
if (msg.has<fix::CustOrderHandlingInst>())
data->cust_order_handling_inst = msg.get<fix::CustOrderHandlingInst>();
data->cfg = &me->cfg;
data->msg = text_msg;
data->exchange = api::Venue::VENUE_GLBX;
me->on_exe_report(*data, msg.trace());
}
}
void GLBXExecutionGateway::on_cancel_reject(
const jetfix::fix::CancelRejectMsg &msg) {
OrderKey ok;
SecurityKey sk;
decode_clorid(msg.get<fix::ClOrdID>(), &ok, &sk);
std::string reject_msg;
CancelRejectReason reason = CancelRejectReason::Other;
if (msg.has<fix::Text>())
reject_msg = msg.get<fix::Text>();
else if (msg.has<fix::CXlRejReason>()) {
if (msg.get<fix::CXlRejReason>() == 2045)
reason = CancelRejectReason::UnknownOrder;
reject_msg = fmt::format("Order cancel was rejected with error code {}",
msg.get<fix::CXlRejReason>());
}
me->on_cancel_reject({ok, reason,reject_msg});
}
void GLBXExecutionGateway::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 GLBXExecutionGateway::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<fix::Text>() ? m.get<fix::Text>() : std::string("Unknown"));
}
void GLBXExecutionGateway::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<fix::Text>() ? m.get<fix::Text>() : std::string("Unknown"));
}
void GLBXExecutionGateway::dispatch_incoming_fix_messages() {
me->gw.dispatch_events();
}
void GLBXExecutionGateway::send_fix(jetfix::OutFIXPtr const &fix,
trace::CorID trace) {
auto scoped_log =
trace::log_scope(me->perf_log, trace, "GLBXExecutionGateway::send_fix");
me->gw.send(fix, trace);
me->gw.dispatch_events();
}
} // namespace orderman
} // namespace bts