Files
spark/src/server/sparkd/orderman/actors/ExecutionGateway.cpp
T

274 lines
10 KiB
C++

#include "ExecutionGateway.h"
#include "lib/utils/TimeStamp.h"
#include "server/sparkd/jetfix/codec/MessageDefinitions.h"
#include "server/sparkd/jetfix/gateway/JetFIXGateway.h"
#include "server/sparkd/orderman/events/CancelRejectEvent.h"
#include "server/sparkd/orderman/events/GatewayStatusChangeEvent.h"
#include "server/sparkd/orderman/events/NewExecutionReportEvent.h"
#include "server/sparkd/orderman/events/NewSecuritiesEvent.h"
#include "server/sparkd/orderman/orderman_utils/fix_order_codec.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "lib/logging/logging.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 ExecutionGateway::PImpl {
PImpl(config::JetFIX::Connection const &cfg)
: gw(cfg), exe_report_pool(), state(State::WAITING_FOR_SECURITIES),
securities(), exe_report_stream(), gw_status_change_stream(),
cancel_reject_stream(), gw_name(cfg.name()), cfg(cfg) {}
JFGw gw;
boost::object_pool<ExecutionReport> exe_report_pool;
State state;
std::unordered_map<SecurityKey::Value, api::Security const *> securities;
mercury::Stream<NewExecutionReportEvent> exe_report_stream;
mercury::Stream<GatewayStatusChangeEvent> gw_status_change_stream;
mercury::Stream<CancelRejectEvent> cancel_reject_stream;
GatewayName gw_name;
config::JetFIX::Connection cfg;
};
ExecutionGateway::ExecutionGateway(config::JetFIX::Connection const &cfg)
: me(new PImpl(cfg)) {}
ExecutionGateway::~ExecutionGateway() {}
void ExecutionGateway::init() {
me->state = State::WAITING_FOR_SECURITIES;
subscribe<NewSecuritiesEvent>(
[this](auto const &sec_update) { this->on_securities(sec_update); });
subscribe<OutFIXMsgEvent>(
me->gw_name, [this](auto const &fix) { this->on_outgoing_fix(fix); });
}
void ExecutionGateway::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;
}
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);
};
// stream of execution reports
me->exe_report_stream =
make_stream<NewExecutionReportEvent>(me->gw_name);
// stream for gateway status
me->gw_status_change_stream =
make_stream<GatewayStatusChangeEvent>(me->gw_name);
// stream for cancel rejects
me->cancel_reject_stream = make_stream<CancelRejectEvent>(me->gw_name);
// start the gateway
me->gw.start();
}
}
}
void ExecutionGateway::on_exe_report(
const jetfix::fix::ExecutionReportMsg &msg) {
OrderKey ok;
SecurityKey sk;
decode_clorid(msg.get<fix::ClOrdID>(), &ok, &sk);
auto sec = me->securities[sk.value()];
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;
}
// Ignore leg fills, we care only about the actual security fill
if (msg.has<fix::MultiLegReportingType>() &&
msg.get<fix::MultiLegReportingType>() == 2)
return;
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->side = api::Side(msg.get<fix::Side>());
data->time_in_force =
api::orderman::TimeInForce(msg.get<fix::TimeInForce>());
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>(), &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());
data->quantity = Quantity(msg.get<fix::OrderQty>());
data->filled_quantity = Quantity(msg.get<fix::CumQty>());
data->last_shares = msg.has<fix::LastShares>()
? Quantity(msg.get<fix::LastShares>())
: Quantity(0);
data->last_price = msg.has<fix::LastPx>()
? securities::decode_exchange_price(
*sec, Price(msg.get<fix::LastPx>()))
: Price(0);
data->avg_price = msg.has<fix::AvgPx>()
? securities::decode_exchange_price(
*sec, Price(msg.get<fix::AvgPx>()))
: Price(0);
if (msg.has<fix::ExecID>())
str_to(msg.get<fix::ExecID>(), &data->exchange_fill_id);
str_to(msg.get<fix::TransactTimeStr>(), &data->transact_time);
data->cfg = &me->cfg;
data->msg = text_msg;
publish(me->exe_report_stream, data);
}
}
void ExecutionGateway::on_cancel_reject(
const jetfix::fix::CancelRejectMsg &msg) {
OrderKey ok;
SecurityKey sk;
decode_clorid(msg.get<fix::ClOrdID>(), &ok, &sk);
std::string reject_msg;
if (msg.has<fix::Text>())
reject_msg = msg.get<fix::Text>();
else if (msg.has<fix::CXlRejReason>())
reject_msg = fmt::format("Order cancel was rejected with error code {}",
msg.get<fix::CXlRejReason>());
publish(me->cancel_reject_stream, 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"));
publish(me->gw_status_change_stream, GatewayStatusChangeEvent(me->gw_name,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<fix::Text>() ? m.get<fix::Text>() : 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<fix::Text>() ? m.get<fix::Text>() : std::string("Unknown"));
}
void ExecutionGateway::on_poll() { me->gw.dispatch_events(); }
void ExecutionGateway::on_outgoing_fix(
mercury::Update<OutFIXMsgEvent> const &msg) {
if (msg.events)
for (auto const &ev : *(msg.events)) {
tracepoint (bts_trace,trace_order,(char*) "on_outgoing_fix", 0,ev.cid,0);
me->gw.send(ev.cid, ev.msg);
}
}
}
}