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

320 lines
12 KiB
C++

#include "ServiceBridge.h"
#include "lib/api/public/ServiceContext.h"
#include "lib/api/services/OrderService.pb.h"
#include "lib/api/services/PositionService.pb.h"
#include "lib/mercury/broker/BrokerProxy.h"
#include "lib/orderman/events/AccountPnLUpdateEvent.h"
#include "lib/orderman/events/ActivateOrderEvent.h"
#include "lib/orderman/events/CancelOrderEvent.h"
#include "lib/orderman/events/DetachOrderEvent.h"
#include "lib/orderman/events/FilledPositionEvent.h"
#include "lib/orderman/events/ExcessLiquidityUpdateEvent.h"
#include "lib/orderman/events/NewAdminDataEvent.h"
#include "lib/orderman/events/OrderManagerReadyEvent.h"
#include "lib/orderman/events/OrderOpResultEvent.h"
#include "lib/orderman/events/StoredFillEvent.h"
#include "lib/orderman/events/StoredOrderEvent.h"
#include "lib/orderman/events/UpdateOrderEvent.h"
#include "lib/orderman/order_factory/OrderFactory.h"
#include "lib/orderman/order_router/OrderRouter.h"
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/orderman/orders/Order.h"
#include "lib/orderman/securities/MapSecurityDB.h"
#include "lib/tracing/PerfLog.h"
#include "lib/utils/PBUtils.h"
#include "lib/api/service_helpers/PositionUtilities.h"
#include <future>
namespace bts {
namespace orderman {
struct ServiceBridge::PImpl {
PImpl(OnReady const &on_ready, OnOrders const &on_orders,
OnFills const &on_fills, OnOrderOpResult const &on_order_op_result,
DynamicOrderRegistry const &dyn_order_registry,
mercury::BrokerProxy &service_call_marshaller, md::SecurityOracle o)
: on_ready(on_ready), on_orders(on_orders), on_fills(on_fills),
on_order_op_result(on_order_op_result), have_orders(false),
order_manager_ready(false), sec_db(o), order_router(),
order_factory(sec_db, order_router, dyn_order_registry),
known_orders(), service_call_marshaller(service_call_marshaller) {}
OnReady on_ready;
OnOrders on_orders;
OnFills on_fills;
OnOrderOpResult on_order_op_result;
bool have_orders;
bool order_manager_ready;
securities::MapSecurityDB sec_db;
OrderRouter order_router;
OrderFactory order_factory;
mercury::Stream<ActivateOrderEvent> activate_order_pub;
mercury::Stream<UpdateOrderEvent> update_order_pub;
mercury::Stream<CancelOrderEvent> cancel_order_pub;
mercury::Stream<DetachOrderEvent> detach_order_pub;
mercury::Stream<NewAdminDataEvent> new_admin_data_pub;
mercury::Stream<AccountPnLUpdateEvent> account_pnl_pub;
mercury::Stream<FilledPositionEvent> filled_position_pub;
mercury::Stream<ExcessLiquidityUpdateEvent> excess_liquidity_pub;
std::unordered_set<OrderKey> known_orders;
std::vector<std::shared_ptr<const api::admin::AdminData>> admin_data_updates;
mercury::BrokerProxy &service_call_marshaller;
std::promise<void> ready;
};
ServiceBridge::ServiceBridge(OnReady const &on_ready, OnOrders const &on_orders,
OnFills const &on_fills,
OnOrderOpResult const &on_order_op_result,
DynamicOrderRegistry const &dyn_order_registry,
mercury::BrokerProxy &service_call_marshaller,
md::SecurityOracle o)
: me(new PImpl(on_ready, on_orders, on_fills, on_order_op_result,
dyn_order_registry, service_call_marshaller, o)) {}
ServiceBridge::~ServiceBridge() {}
void ServiceBridge::block_until_ready() { me->ready.get_future().wait(); }
void ServiceBridge::init() {
subscribe<NewAdminDataEvent>([this](auto const &u) { this->on(u); });
subscribe<StoredFillEvent>([this](auto const &u) { this->on(u); });
subscribe<StoredOrderEvent>([this](auto const &u) { this->on(u); });
subscribe<OrderManagerReadyEvent>([this](auto const &u) { this->on(u); });
subscribe<OrderOpResultEvent>([this](auto const &u) { this->on(u); });
me->activate_order_pub = make_stream<ActivateOrderEvent>();
me->update_order_pub = make_stream<UpdateOrderEvent>();
me->cancel_order_pub = make_stream<CancelOrderEvent>();
me->detach_order_pub = make_stream<DetachOrderEvent>();
me->new_admin_data_pub = make_stream<NewAdminDataEvent>();
me->account_pnl_pub = make_stream<AccountPnLUpdateEvent>();
me->filled_position_pub = make_stream<FilledPositionEvent>();
me->excess_liquidity_pub = make_stream<ExcessLiquidityUpdateEvent>();
me->ready.set_value();
}
void ServiceBridge::on(mercury::Update<StoredFillEvent> const &update) {
if (update.events) {
std::vector<api::orderman::Fill> fills;
fills.reserve(update.events->size());
for (auto ev : *(update.events))
fills.push_back(ev.fill);
me->on_fills(fills);
}
}
void ServiceBridge::on(mercury::Update<StoredOrderEvent> const &update) {
if (update.events) {
bool was_ready = is_ready();
me->have_orders = true;
std::vector<api::orderman::OrderRecord> orders;
orders.reserve(update.events->size());
for (auto ev : *(update.events)) {
me->known_orders.insert(OrderKey(ev.order_record.key()));
orders.push_back(ev.order_record);
}
me->on_orders(orders);
maybe_signal_ready(was_ready);
}
}
void ServiceBridge::on(mercury::Update<OrderManagerReadyEvent> const &update) {
if (update.events) {
bool was_ready = is_ready();
me->order_manager_ready = true;
maybe_signal_ready(was_ready);
}
}
void ServiceBridge::on(mercury::Update<NewAdminDataEvent> const &update) {
if (update.events)
for (auto ev : *(update.events))
me->order_router.update(*ev.admin_data);
}
void ServiceBridge::on(mercury::Update<OrderOpResultEvent> const &update) {
if (update.events)
for (auto ev : *(update.events))
me->on_order_op_result(ev);
}
void ServiceBridge::create_order(uint32_t rid, api::orderman::Create const &c) {
LOG(OrderMan, Info, "Received new order from client: {}",
utils::pb::to_string(c));
me->service_call_marshaller.schedule_action([this, c, rid]() {
if (is_ready()) {
auto &order =
me->order_factory.create(null_order_key(), c.new_order());
me->known_orders.insert(order.key());
publish(me->activate_order_pub, rid, order, Price(c.price()),
Quantity(c.quantity()));
} else
me->on_order_op_result(OrderOpResultEvent(
null_order_key(), rid,
OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY)));
});
}
void ServiceBridge::update_order(uint32_t rid, api::orderman::Update const &c) {
LOG(OrderMan, Info, "Received order update from client: {}",
utils::pb::to_string(c));
me->service_call_marshaller.schedule_action([this, c, rid]() {
auto ok = OrderKey(c.order_key());
if (is_ready()) {
if (me->known_orders.count(ok))
publish(me->update_order_pub, rid, c);
else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER)));
} else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY)));
});
}
void ServiceBridge::cancel_order(uint32_t rid, api::orderman::Cancel const &c) {
LOG(OrderMan, Info, "Received order cancel from client: {}",
utils::pb::to_string(c));
me->service_call_marshaller.schedule_action([this, c, rid]() {
auto ok = OrderKey(c.order_key());
if (is_ready()) {
if (me->known_orders.count(ok))
publish(me->cancel_order_pub, rid, ok);
else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER)));
} else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY)));
});
}
void ServiceBridge::detach_order(uint32_t rid, api::orderman::Detach const &c) {
LOG(OrderMan, Info, "Received order detach from client: {}",
utils::pb::to_string(c));
me->service_call_marshaller.schedule_action([this, c, rid]() {
auto ok = OrderKey(c.order_key());
if (is_ready()) {
if (me->known_orders.count(ok))
publish(me->detach_order_pub, rid, ok);
else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_UNKNOWN_ORDER)));
} else
me->on_order_op_result(OrderOpResultEvent(
ok, rid,
OrderOpResult(api::orderman::ORDER_ERROR_SERVER_NOT_READY)));
});
}
void ServiceBridge::update_admin_data(
std::shared_ptr<const api::admin::AdminData> const &admin) {
me->service_call_marshaller.schedule_action([this, admin]() {
me->admin_data_updates.push_back(admin);
publish(me->new_admin_data_pub, *admin);
});
}
void ServiceBridge::update_account_pnl(
api::position::Pnl_account_dataUpdate const &pnl) {
me->service_call_marshaller.schedule_action([this, pnl]() {
for (auto const &account_pnl : pnl.added()) {
publish(me->account_pnl_pub, AccountID(account_pnl->account_id()),
account_pnl->day_pnl());
}
for (auto const &account_pnl : pnl.changed()) {
publish(me->account_pnl_pub,
AccountID(account_pnl.current()->account_id()),
account_pnl.current()->day_pnl());
}
});
}
void ServiceBridge::update_excess_liquidity_report(
api::position::Excess_liquidity_reportUpdate const &elr) {
me->service_call_marshaller.schedule_action([this, elr]() {
for (auto const &elr : elr.added()) {
publish(me->excess_liquidity_pub, AccountID(elr->account_id()),
elr->excess_liquidity());
}
for (auto const &elr : elr.changed()) {
publish(me->excess_liquidity_pub,
AccountID(elr.current()->account_id()),
elr.current()->excess_liquidity());
}
});
}
std::optional<FilledPositionEvent>
make_pos_event(api::position::PositionUnit const &pu,
securities::MapSecurityDB const &o) {
auto sec = o.resolve(SecurityKey(pu.security_id()));
if (sec) {
uint32_t total_long_pos, total_short_pos;
bts::position::PositionUtilities::day_position(pu,
total_long_pos,
total_short_pos);
FilledPositionEvent ev{
*sec, AccountID(pu.account_id()),
Quantity(total_long_pos),
Quantity(total_short_pos)
};
return {ev};
} else
return {};
}
void ServiceBridge::update_position(
api::position::Position_dataUpdate const &pos) {
std::vector<FilledPositionEvent> evs;
for (auto const &pu : pos.added()) {
auto ev = make_pos_event(*pu, me->sec_db);
if (ev.has_value())
evs.push_back(ev.value());
else
LOG(OrderMan, Error,
"Could not update position limiter for unknown security {}. This "
"should not happen",
pu->security_id());
}
for (auto const &pu_change : pos.changed()) {
auto ev = make_pos_event(*pu_change.current(), me->sec_db);
if (ev.has_value())
evs.push_back(ev.value());
else
LOG(OrderMan, Error,
"Could not update position limiter for unknown security {}. This "
"should not happen",
pu_change.current()->security_id());
}
me->service_call_marshaller.schedule_action([this, evs]() {
publish_batch(me->filled_position_pub, evs);
});
}
bool ServiceBridge::is_ready() const {
return me->have_orders && me->order_manager_ready;
}
void ServiceBridge::maybe_signal_ready(bool old_ready) {
if (!old_ready && is_ready())
me->on_ready();
}
} // namespace orderman
} // namespace bts