Files
spark/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp
T

1090 lines
35 KiB
C++

#include "lib/orderman/orders/algo/AlgoWrapperOrder.h"
#include "lib/orderman/actors/order_manager/ChildOrder.h"
#include "lib/orderman/actors/order_manager/OrderBuilder.h"
#include "lib/orderman/actors/order_manager/OrderServices.h"
#include "lib/orderman/orderman_utils/orderman_utils.h"
#include "lib/orderman/orders/PreActivationOrderServices.h"
#include "lib/orderman/orders/algo/IAlgoOrder.h"
#include "lib/utils/bts_assert.h"
#include <boost/container/flat_map.hpp>
#include <optional>
namespace bts {
namespace orderman {
using namespace api::orderman;
template <class K, class V> using Map = boost::container::flat_map<K, V>;
enum class AlgoWrapperOrder::Status {
INACTIVE,
W_ATTACH,
WORKING,
SHUTTING_DOWN,
COMPLETED
};
class ChildTemplate {
public:
ChildTemplate() {}
ChildTemplate(OrderKey parent_key, api::orderman::OrderDefinition const &def,
IOrderFactory *factory, size_t reserve_sz)
: builder(parent_key, def, *factory, reserve_sz) {}
OrderBuilder builder;
};
struct AlgoWrapperOrder::ChildRecord {
ChildOrder order;
std::optional<ChildState> state;
bool is_subscribing = false;
};
struct AlgoWrapperOrder::PImpl {
using Edge = std::pair<Status, Status>;
using Action = std::function<void()>;
PImpl(std::unique_ptr<IAlgoOrder> &&algo)
: algo(std::move(algo)), _my_key(null_order_key()) {}
std::unique_ptr<IAlgoOrder> algo;
Status status = Status::INACTIVE;
OrderServices *services = nullptr;
OrderDefinition definition;
const api::Security *security;
OrderState const &state() const { return _state; }
Map<SecurityKey, OrderServices::BookSubID> book_subs;
Map<SecurityKey, OrderServices::SettlementSubID> settlement_subs;
Map<SecurityKey, OrderServices::TickerSubID> ticker_subs;
Map<SecurityKey, OrderServices::StatusSubID> status_subs;
Map<OrderKey, ChildRecord> children;
bool has_timer_sub = false;
bool has_position_sub = false;
bool is_state_dirty = false;
Map<Edge, Action> transition_actions;
Map<Status, Action> invariants;
securities::ISecurityDB const *security_db = nullptr;
IOrderFactory *order_factory = nullptr;
std::vector<std::unique_ptr<ChildTemplate>> child_templates;
OrderKey attach_target = null_order_key();
std::optional<api::orderman::Update> pending_update;
std::optional<std::pair<OrderStatus, std::string>> pending_terminate;
OrderStatus external_status() const { return _state.status(); }
bool in_do_launch_attached = false;
void set_external_status(OrderStatus s) {
is_state_dirty = true;
_state.set_status(s);
}
void set_state(OrderState const &new_state) {
is_state_dirty = true;
_state = new_state;
}
void set_last_msg(std::string const &msg) {
is_state_dirty = true;
_state.set_last_msg(msg);
}
void set_price_quantity(Price p, Quantity q) {
is_state_dirty = true;
_state.set_price(p.value());
_state.set_quantity(q.value());
}
void set_fill_quantities(Quantity total_fills, Price last_price,
Price avg_price, bool set_attach_time_fills) {
is_state_dirty = true;
_state.set_filled_quantity(total_fills.value());
_state.set_last_price(last_price.value());
_state.set_avg_price(avg_price.value());
if (set_attach_time_fills) {
LOG(OrderMan, Diag,
"AlgoWrapperOrder {} setting fill at attach time to {}",
_my_key.value(), total_fills.value());
_state.set_filled_at_attach_time_quantity(total_fills.value());
} else
LOG(OrderMan, Diag, "AlgoWrapperOrder {} settings fills to {}",
_my_key.value(), total_fills.value());
}
void set_ladder_visibility(bool is_visible) {
is_state_dirty = true;
_state.set_display_status(is_visible ? OrderState::VISIBLE
: OrderState::HIDDEN);
}
void update_custom_state(api::orderman::DynamicOrderState const&cstate) {
is_state_dirty = true;
bts_assert(definition.has_custom_def());
bts_assert(definition.custom_def().has_dynamic());
*_state.mutable_dynamic() = cstate;
}
void set_key(OrderKey k) { _my_key = k; }
private:
OrderState _state;
OrderKey _my_key;
};
struct AlgoWrapperOrder::ReportStateGuard {
ReportStateGuard(AlgoWrapperOrder &owner) : owner(owner) {}
~ReportStateGuard() {
if (owner.me->is_state_dirty) {
owner.me->is_state_dirty = false;
LOG(OrderMan, Diag,
"AlgoWrapperOrder::ReportStateGuard. k: {} fills: fills at "
"attach: {}",
owner.key().value(), owner.me->state().filled_quantity(),
owner.me->state().filled_at_attach_time_quantity());
owner.me->services->report_state(owner.me->state());
}
}
AlgoWrapperOrder &owner;
};
AlgoWrapperOrder::AlgoWrapperOrder(std::unique_ptr<IAlgoOrder> &&algo)
: me(new PImpl(std::move(algo))) {
setup_transitions();
}
AlgoWrapperOrder::~AlgoWrapperOrder() {}
// --------------------------------------------------------------------------------
// Order
// --------------------------------------------------------------------------------
void AlgoWrapperOrder::on_init_new(OrderDefinition const &def,
const PreActivationOrderServices &serv) {
bts_assert(def.has_custom_def());
// cache these so we can resolve securities and create order builders
me->security_db = &serv.sec_db;
me->order_factory = &serv.order_factory;
// Save our order definition
me->definition = def;
// Save our key
me->set_key(key());
// If we are consuming the attachment we remove it from our definition so
// that derived orders can use our definition to create their children
// without triggering an attachment.
if (_is_attaching(me->definition)) {
if (can_consume_attachment(me->definition.custom_def().custom_case())) {
me->attach_target = OrderKey(me->definition.attach_target_order_key());
me->definition.clear_attach_target_order_key();
} else {
terminate(ORDER_STATUS_REJECTED_BY_SPARK,
"Algo does not support attachment");
return;
}
}
me->security = serv.sec_db.resolve(SecurityKey(def.security_key()));
if (me->security == nullptr)
terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Unknown security");
auto result = me->algo->do_before_launch(*this);
if (result.fail())
terminate(ORDER_STATUS_REJECTED_BY_SPARK, result.error_msg);
}
void AlgoWrapperOrder::on_init_recovered(
OrderRecord const &rec, const PreActivationOrderServices &serv) {
auto const &def = rec.def();
me->definition = def;
me->set_key(key());
me->set_state(rec.state());
me->security_db = &serv.sec_db;
me->order_factory = &serv.order_factory;
// Infer internal status from persisted external status
switch (me->external_status()) {
case ORDER_STATUS_WORKING:
case ORDER_STATUS_PENDING_WORKING:
terminate(ORDER_STATUS_ERROR, "System restarted with active algo order");
return;
// Terminal states
case ORDER_STATUS_ERROR:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_CANCELED:
terminate(rec.state().status(), rec.state().last_msg());
break;
// It should not be possible to reach these
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_INACTIVE:
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
bts_assert(false);
break;
}
}
OrderOpResult AlgoWrapperOrder::on_activate(Price p, Quantity q,
OrderServices &services) {
bts_assert(!me->services);
me->services = &services;
me->security_db = &services.sec_db();
me->order_factory = &services.order_factory();
switch (me->status) {
case Status::INACTIVE: {
me->services->subscribe_to_child_updates([this](auto const &u) {
this->on_child_order_update(u.key, u.quick_rebuild_state());
});
me->set_external_status(ORDER_STATUS_WORKING);
me->set_price_quantity(p, q);
for (auto &ct : me->child_templates)
ct->builder.activate(*me->services);
if (q.value() == 0) {
ReportStateGuard _(*this);
terminate(ORDER_STATUS_COMPLETED);
}
else if (is_attaching())
// Do not report state until the attachment is complete, so
// that we can correctly populate the
// filled_at_attach_time_quantity field
transition(Status::W_ATTACH);
else {
ReportStateGuard _(*this);
transition(Status::WORKING);
}
return {};
}
case Status::COMPLETED: {
ReportStateGuard _(*this);
return {};
}
case Status::W_ATTACH:
case Status::SHUTTING_DOWN:
case Status::WORKING:
bts_assert(false);
}
bts_assert(false);
return {};
}
OrderOpResult AlgoWrapperOrder::on_update(Update const &update) {
switch (me->status) {
case Status::W_ATTACH:
// We do not want to report state until the attach is complete
// so there is no report guard here
me->pending_update = update;
return {};
case Status::COMPLETED:
case Status::SHUTTING_DOWN: {
ReportStateGuard _(*this);
return {};
}
case Status::WORKING: {
ReportStateGuard _(*this);
me->set_price_quantity(Price(update.price()),
Quantity(update.quantity()));
if (update.has_custom()) {
*me->definition.mutable_custom_def() = update.custom();
me->services->report_definition(me->definition);
}
me->algo->do_update(update);
return {};
}
case Status::INACTIVE:
bts_assert(false);
return {};
}
bts_assert(false);
return {};
}
OrderOpResult AlgoWrapperOrder::on_update(Price p, Quantity q) {
Update up;
up.set_price(p.value());
up.set_quantity(q.value());
return on_update(up);
}
orderman::OrderOpResult AlgoWrapperOrder::on_detach() {
ReportStateGuard _(*this);
LOG(OrderMan, Info, "AlgoOrder order with key {} received detach",
key().value());
switch (me->status) {
case Status::W_ATTACH:
case Status::WORKING:
case Status::SHUTTING_DOWN:
for (auto &[_, c] : me->children) {
(void)_;
c.order.mark_detached_from_parent();
}
me->children.clear();
terminate(ORDER_STATUS_CANCELED);
break;
case Status::COMPLETED:
break;
case Status::INACTIVE:
bts_assert(false);
break;
}
return {};
}
orderman::OrderOpResult AlgoWrapperOrder::on_cancel() {
ReportStateGuard _(*this);
switch (me->status) {
case Status::W_ATTACH:
terminate(ORDER_STATUS_CANCELED);
break;
case Status::WORKING:
switch (me->algo->on_cancel()) {
case IAlgoOrder::OnCancelResponse::HONOR:
cancel();
break;
case IAlgoOrder::OnCancelResponse::IGNORE:
LOG(OrderMan, Info, "Algo order with key {} ignored cancel request",
key().value());
break;
}
break;
case Status::SHUTTING_DOWN:
case Status::COMPLETED:
break;
case Status::INACTIVE:
bts_assert(false);
break;
}
return {};
}
// --------------------------------------------------------------------------------
// IBeforeLaunchAlgoServices
// --------------------------------------------------------------------------------
api::orderman::OrderDefinition const &AlgoWrapperOrder::definition() const {
return *def();
}
api::Security const &AlgoWrapperOrder::security() const {
return *me->security;
}
OrderKey AlgoWrapperOrder::order_key() const { return key(); }
OrderKey AlgoWrapperOrder::parent_order_key() const { return parent_key(); }
api::Security const *AlgoWrapperOrder::lookup_security(SecurityKey k) const {
return me->security_db->resolve(k);
}
std::vector<api::Security const *> AlgoWrapperOrder::known_securities() const {
return me->security_db->get_securities();
}
Price AlgoWrapperOrder::price() const { return Price(me->state().price()); }
Quantity AlgoWrapperOrder::quantity() const {
return Quantity(me->state().quantity());
}
Quantity AlgoWrapperOrder::total_fills() const {
return Quantity(me->state().filled_quantity());
}
bool AlgoWrapperOrder::is_shutting_down() const {
return me->status == Status::SHUTTING_DOWN;
}
std::vector<PositionUpdate> const&AlgoWrapperOrder::current_positions() const {
return me->services->current_positions();
}
void AlgoWrapperOrder::subscribe_book(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->book_subs.find(k) == me->book_subs.end());
me->book_subs[k] =
me->services->subscribe_to_book(k, [this, k](auto const &ev) {
ReportStateGuard _(*this);
me->algo->on_book(k, ev.book);
});
}
void AlgoWrapperOrder::unsubscribe_book(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->book_subs.find(k) != me->book_subs.end());
if (auto it = me->book_subs.find(k); it != me->book_subs.end())
me->services->unsubscribe_from_book(it->second);
}
void AlgoWrapperOrder::subscribe_settlement(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->settlement_subs.find(k) == me->settlement_subs.end());
me->settlement_subs[k] =
me->services->subscribe_to_settlements(k, [this, k](auto const &ev) {
ReportStateGuard _(*this);
me->algo->on_settlement(k, Price(ev.settlement_price.price()));
});
}
void AlgoWrapperOrder::unsubscribe_settlement(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->settlement_subs.find(k) != me->settlement_subs.end());
if (auto it = me->settlement_subs.find(k); it != me->settlement_subs.end())
me->services->unsubscribe_from_settlements(it->second);
}
void AlgoWrapperOrder::subscribe_ticker(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->ticker_subs.find(k) == me->ticker_subs.end());
me->ticker_subs[k] =
me->services->subscribe_to_ticker(k, [this, k](const auto &ev) {
ReportStateGuard _(*this);
me->algo->on_ticker(k, ev.trades);
});
}
void AlgoWrapperOrder::unsubscribe_ticker(SecurityKey k) {
if (!is_working())
return;
bts_assert(me->ticker_subs.find(k) != me->ticker_subs.end());
if (auto it = me->ticker_subs.find(k); it != me->ticker_subs.end())
me->services->unsubscribe_from_ticker(it->second);
}
void AlgoWrapperOrder::subscribe_status(SecurityKey k) {
if (!is_working()) return;
bts_assert(me->status_subs.find(k) == me->status_subs.end());
me->status_subs[k] =
me->services->subscribe_to_status(k, [this,k](const auto& ev) {
ReportStateGuard _(*this);
me->algo->on_status(k, ev.status);
});
}
void AlgoWrapperOrder::unsubscribe_status(SecurityKey k) {
if (!is_working()) return;
bts_assert(me->status_subs.find(k) != me->status_subs.end());
auto it = me->status_subs.find(k);
if (it != me->status_subs.end()) {
me->services->unsubscribe_from_status(it->second);
}
}
void AlgoWrapperOrder::subscribe_child_change(OrderKey k) {
if (!is_working())
return;
auto it = me->children.find(k);
bts_assert(it != me->children.end());
auto &child_record = it->second;
bts_assert(!child_record.is_subscribing);
child_record.is_subscribing = true;
}
void AlgoWrapperOrder::unsubscribe_child_change(OrderKey k) {
if (!is_working())
return;
auto it = me->children.find(k);
bts_assert(it != me->children.end());
auto &child_record = it->second;
bts_assert(child_record.is_subscribing);
child_record.is_subscribing = false;
}
void AlgoWrapperOrder::subscribe_timer() {
if (!is_working())
return;
bts_assert(!me->has_timer_sub);
me->has_timer_sub = true;
me->services->subscribe_to_time([this](auto const &) {
ReportStateGuard _(*this);
me->algo->on_timer();
});
}
void AlgoWrapperOrder::unsubscribe_timer() {
if (!is_working())
return;
bts_assert(me->has_timer_sub);
me->services->unsubscribe_from_time();
me->has_timer_sub = false;
}
void AlgoWrapperOrder::subscribe_position() {
if (!is_working())
return;
bts_assert(!me->has_position_sub);
me->has_position_sub = true;
me->services->subscribe_to_position_updates([this](auto const &ev) {
ReportStateGuard _(*this);
me->algo->on_position({ev.security,ev.account_id,ev.long_quantity, ev.short_quantity});
});
}
void AlgoWrapperOrder::unsubscribe_position() {
if (!is_working())
return;
bts_assert(me->has_position_sub);
me->services->unsubscribe_from_position_updates();
me->has_position_sub = false;
}
bool AlgoWrapperOrder::is_attaching() const {
return me->attach_target != null_order_key();
}
ChildTemplate &AlgoWrapperOrder::make_child_template(
api::orderman::OrderDefinition const &child_def, size_t reserve) {
auto t = std::make_unique<ChildTemplate>(key(), child_def, me->order_factory,
reserve);
if (me->services)
t->builder.activate(*me->services);
me->child_templates.emplace_back(std::move(t));
return *(me->child_templates.back());
}
// --------------------------------------------------------------------------------
// IAlgoServices
// --------------------------------------------------------------------------------
OrderKey AlgoWrapperOrder::launch_child(ChildTemplate &t, Price p, Quantity q,
bool subscribe_to_changes) {
if (!is_working())
return null_order_key();
return index_and_launch_child(t.builder.build(), p, q, subscribe_to_changes);
}
OrderKey
AlgoWrapperOrder::launch_child(api::orderman::OrderDefinition const &def,
Price p, Quantity q, bool subscribe_to_changes) {
if (!is_working())
return null_order_key();
return index_and_launch_child(ChildOrder{def, *me->services}, p, q,
subscribe_to_changes);
}
void AlgoWrapperOrder::update_child(OrderKey child,
api::orderman::Update const &update) {
if (!is_working())
return;
bts_assert(me->status == Status::WORKING);
if (auto it = me->children.find(child); it != me->children.end())
it->second.order.update(update);
else
terminate_error(fmt::format("Algo {} tried to update unknown child: {}",
key().value(), child.value()));
}
void AlgoWrapperOrder::cancel_child(OrderKey child) {
if (!is_working())
return;
bts_assert(me->status == Status::WORKING);
if (auto it = me->children.find(child); it != me->children.end())
it->second.order.cancel();
else
terminate_error(fmt::format("Algo {} tried to cancel unknown child: {}",
key().value(), child.value()));
}
void AlgoWrapperOrder::detach_child(OrderKey child) {
if (!is_working())
return;
if (auto it = me->children.find(child); it != me->children.end()) {
it->second.order.mark_detached_from_parent();
me->children.erase(it);
} else
terminate_error(fmt::format("Algo {} tried to cancel unknown child: {}",
key().value(), child.value()));
}
void AlgoWrapperOrder::detach_all_children() {
if (!is_working())
return;
for (auto &[_, c] : me->children) {
(void)_;
c.order.mark_detached_from_parent();
}
me->children.clear();
}
void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) {
if (!is_working() && !is_shutting_down())
return;
auto previous_qty = me->state().filled_quantity();
if (previous_qty > q.value()) {
LOG(OrderMan, Error,
"AlgoOrder {} is reporting a decrease in fill quantity "
"from {} to {}. This should never happen. Canceling {}",
key().value(), previous_qty, q.value(), key().value());
terminate_error("Internal algo error. Report fill size decreased");
} else {
auto new_avg_price = Price(0);
if (q.value() > 0)
new_avg_price.value() =
(me->state().filled_quantity() * me->state().avg_price() +
(q.value() - previous_qty) * p.value()) /
q.value();
LOG(OrderMan, Diag,
"AlgoWrapperOrder updated its fill state. Total fills: {} Is "
"attaching: {}",
q.value(), me->in_do_launch_attached);
me->set_fill_quantities(q, p, new_avg_price, me->in_do_launch_attached);
}
}
void AlgoWrapperOrder::set_ladder_visibility(bool is_visible) {
if (!is_working())
return;
me->set_ladder_visibility(is_visible);
}
void AlgoWrapperOrder::update_custom_state(api::orderman::DynamicOrderState const&cstate) {
if (!is_working())
return;
me->update_custom_state(cstate);
}
void AlgoWrapperOrder::cancel(std::string const &msg) {
if (!is_working())
return;
if (working_children_count() == 0)
terminate(ORDER_STATUS_CANCELED, msg);
else
shutdown(ORDER_STATUS_CANCELED, msg);
}
void AlgoWrapperOrder::terminate_error(std::string const &msg) {
if (!is_working() && !is_shutting_down() && me->status != Status::W_ATTACH)
return;
// If we attached and an error was signaled we do not want to
// cancel our child because that child might be a long running
// order with a good queue position that we want to preserve
if (is_attaching())
me->children.erase(me->attach_target);
terminate(ORDER_STATUS_ERROR, msg);
}
void AlgoWrapperOrder::complete() {
if (!is_working())
return;
if (working_children_count() == 0)
terminate(ORDER_STATUS_COMPLETED);
else
shutdown(ORDER_STATUS_COMPLETED);
}
// --------------------------------------------------------------------------------
// Private methods
// --------------------------------------------------------------------------------
void AlgoWrapperOrder::on_attach_complete(
OrderOpResult r, ChildOrder const &child,
api::orderman::OrderDefinition const &,
api::orderman::OrderState const &state) {
ReportStateGuard _(*this);
switch (me->status) {
case Status::W_ATTACH:
if (r.ok()) {
bts_assert(state.status() == ORDER_STATUS_WORKING);
LOG(OrderMan, Info,
"AlgoOrder order with key {} successfully attached to {}",
key().value(), child.key().value());
// Store the order
auto &child_record = (me->children)[child.key()];
child_record.is_subscribing = true;
child_record.order = child;
update_child_record(state, &child_record);
transition(Status::WORKING);
} else {
terminate_error(fmt::format(
"AlgoOrder order with key {} failed to attach to {}: {}",
key().value(), me->attach_target.value(), r.error_msg));
}
break;
case Status::COMPLETED: {
break;
}
case Status::SHUTTING_DOWN:
case Status::INACTIVE:
case Status::WORKING:
bts_assert(false);
break;
}
}
void AlgoWrapperOrder::on_child_order_update(
OrderKey child_key, api::orderman::OrderState const &new_child_state) {
ReportStateGuard _(*this);
switch (me->status) {
case Status::WORKING:
case Status::W_ATTACH:
case Status::SHUTTING_DOWN:
if (auto it = me->children.find(child_key); it != me->children.end()) {
auto &child_record = it->second;
switch (new_child_state.status()) {
case ORDER_STATUS_COMPLETED:
case ORDER_STATUS_WORKING:
case ORDER_STATUS_PENDING_WORKING:
case ORDER_STATUS_CANCELED:
if (child_record.state.has_value() &&
child_record.state.value().total_fills.value() >
new_child_state.filled_quantity()) {
LOG(OrderMan, Error,
"AlgoOrder {} observed child {} decrease its total fills "
"from {} to {}. This should never happen. Canceling {}",
key().value(), child_key.value(),
child_record.state.value().total_fills.value(),
new_child_state.filled_quantity(), key().value());
terminate_error("Child order filled quantity decreased");
} else {
update_child_record(new_child_state, &child_record);
if (child_record.is_subscribing)
me->algo->on_child_change(child_key,
child_record.state.value());
}
break;
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_ERROR:
terminate_error("Unexpected child order state");
break;
case ORDER_STATUS_INACTIVE:
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_:
bts_assert(false);
break;
}
} else
LOG(OrderMan, Info,
"AlgoOrder {} received update for presumably detached order {}. "
"Ignoring it",
key().value(), child_key.value());
break;
case Status::COMPLETED:
return;
case Status::INACTIVE:
bts_assert(false);
return;
}
if (me->status == Status::SHUTTING_DOWN)
try_complete_shutdown();
}
void AlgoWrapperOrder::try_complete_shutdown() {
bts_assert(me->status == Status::SHUTTING_DOWN);
bts_assert(me->children.size());
bts_assert(me->pending_terminate.has_value());
if (working_children_count() == 0) {
LOG(OrderMan, Info, "AlgoOrder {} completed shutdown. Terminated",
key().value());
terminate(me->pending_terminate.value().first,
me->pending_terminate.value().second);
} else {
LOG(OrderMan, Info,
"AlgoOrder {} still has {} orders working. Shutdown still in "
"progress",
key().value(), working_children_count());
}
}
void AlgoWrapperOrder::setup_transitions() {
// From INACTIVE
me->transition_actions[{Status::INACTIVE, Status::COMPLETED}] = [this]() {
_transition(Status::COMPLETED);
};
me->transition_actions[{Status::INACTIVE, Status::W_ATTACH}] = [this]() {
me->services->attach(me->attach_target, [this](auto result,
auto const &child_order,
auto const &child_def,
auto const &child_state) {
this->on_attach_complete(result, child_order, child_def, child_state);
});
_transition(Status::W_ATTACH);
};
me->transition_actions[{Status::INACTIVE, Status::WORKING}] = [this]() {
_transition(Status::WORKING);
me->algo->do_launch(*this);
};
// From W_ATTACH
me->transition_actions[{Status::W_ATTACH, Status::COMPLETED}] = [this]() {
_transition(Status::COMPLETED);
};
me->transition_actions[{Status::W_ATTACH, Status::WORKING}] = [this]() {
_transition(Status::WORKING);
auto &maybe_state = me->children[me->attach_target].state;
bts_assert(maybe_state.has_value());
// This is ugly but its needed to make the API as simple as possible but
// still be able to distinguish fills that were present at the attachment
// time from fills that came later. update_fill_state() will look at this
// boolean to decide how it should populate fills_at_attach_time
me->in_do_launch_attached = true;
me->algo->do_launch_attached(*this, me->attach_target,
maybe_state.value());
// Reset in_do_launch_attached back to false
me->in_do_launch_attached = false;
if (me->status == Status::WORKING && me->pending_update.has_value()) {
auto update = me->pending_update.value();
me->pending_update.reset();
me->algo->do_update(me->pending_update.value());
}
};
// From WORKING
me->transition_actions[{Status::WORKING, Status::COMPLETED}] = [this]() {
cleanup();
me->children.clear();
_transition(Status::COMPLETED);
};
me->transition_actions[{Status::WORKING, Status::SHUTTING_DOWN}] = [this]() {
cleanup();
_transition(Status::SHUTTING_DOWN);
};
// From SHUTTING_DOWN
me->transition_actions[{Status::SHUTTING_DOWN, Status::COMPLETED}] =
[this]() {
me->children.clear();
me->pending_terminate.reset();
_transition(Status::COMPLETED);
};
}
void AlgoWrapperOrder::check_invariants() {
bts_assert(me->security_db);
bts_assert(me->order_factory);
switch (me->status) {
case Status::INACTIVE:
bts_assert(false);
return;
case Status::W_ATTACH:
bts_assert(me->services);
bts_assert(me->security);
bts_assert(is_attaching());
bts_assert(me->external_status() == ORDER_STATUS_WORKING);
bts_assert(me->book_subs.empty());
bts_assert(me->settlement_subs.empty());
bts_assert(me->ticker_subs.empty());
bts_assert(me->children.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_terminate.has_value());
break;
case Status::WORKING:
bts_assert(me->services);
bts_assert(me->security);
bts_assert(me->external_status() == ORDER_STATUS_WORKING);
bts_assert(!me->pending_update.has_value());
bts_assert(!me->pending_terminate.has_value());
break;
case Status::SHUTTING_DOWN:
bts_assert(working_children_count());
bts_assert(me->services);
bts_assert(me->security);
bts_assert(me->external_status() == ORDER_STATUS_WORKING);
bts_assert(me->book_subs.empty());
bts_assert(me->settlement_subs.empty());
bts_assert(me->ticker_subs.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_update.has_value());
bts_assert(me->pending_terminate.has_value());
break;
case Status::COMPLETED:
bts_assert(me->children.empty());
bts_assert(!me->pending_update.has_value());
bts_assert(me->external_status() == ORDER_STATUS_CANCELED ||
me->external_status() == ORDER_STATUS_COMPLETED ||
me->external_status() == ORDER_STATUS_ERROR ||
me->external_status() == ORDER_STATUS_REJECTED_BY_SPARK);
bts_assert(me->book_subs.empty());
bts_assert(me->settlement_subs.empty());
bts_assert(me->ticker_subs.empty());
bts_assert(!me->has_timer_sub);
bts_assert(!me->pending_update.has_value());
bts_assert(!me->pending_terminate.has_value());
break;
}
}
void AlgoWrapperOrder::transition(Status new_status) {
if (auto it = me->transition_actions.find({me->status, new_status});
it != me->transition_actions.end()) {
it->second();
} else {
LOG(OrderMan, Fatal, "Illegal transition from {} to {}",
state_name(me->status), state_name(new_status));
bts_assert(false);
}
}
void AlgoWrapperOrder::_transition(Status st) {
LOG(OrderMan, Info, "Transitioninig AlgoOrder with key {} from {} to {}",
key().value(), state_name(me->status), state_name(st));
me->status = st;
check_invariants();
}
void AlgoWrapperOrder::terminate(api::orderman::OrderStatus st,
std::string const &error) {
me->set_external_status(st);
if (error.size())
me->set_last_msg(error);
transition(Status::COMPLETED);
}
void AlgoWrapperOrder::shutdown(api::orderman::OrderStatus st,
std::string const &error) {
bts_assert(!me->pending_terminate.has_value());
bts_assert(working_children_count());
me->pending_terminate = std::make_pair(st, error);
LOG(OrderMan, Info,
"AlgoOrder {} is shutting down. Waiting for {} child orders to complete "
"before terminating",
key().value(), working_children_count());
transition(Status::SHUTTING_DOWN);
}
void AlgoWrapperOrder::cleanup() {
for (auto const &s : me->book_subs)
me->services->unsubscribe_from_book(s.second);
me->book_subs.clear();
for (auto const &s : me->settlement_subs)
me->services->unsubscribe_from_settlements(s.second);
me->settlement_subs.clear();
for (auto const &s : me->ticker_subs)
me->services->unsubscribe_from_ticker(s.second);
me->ticker_subs.clear();
for (auto &c : me->children)
c.second.order.cancel();
if (me->has_timer_sub)
unsubscribe_timer();
me->pending_update.reset();
}
void AlgoWrapperOrder::update_child_record(
api::orderman::OrderState const &new_state, ChildRecord *child_record) {
if (!child_record->state.has_value())
child_record->state = ChildState{};
auto &old_state = child_record->state.value();
bts_assert(old_state.total_fills.value() <= new_state.filled_quantity());
child_record->state = ChildState{
Price(new_state.price()),
Quantity(new_state.quantity()),
Quantity(new_state.filled_quantity()),
Price(new_state.avg_price()),
Quantity(new_state.filled_quantity() - old_state.total_fills.value()),
Price(new_state.last_price()),
map_child_status(new_state.status()),
Quantity(new_state.filled_at_attach_time_quantity())};
}
OrderKey AlgoWrapperOrder::index_and_launch_child(ChildOrder &&child, Price p,
Quantity q, bool subscribe) {
child.activate(p, q);
auto k = child.key();
auto &cr = me->children[k];
cr = {std::move(child), {}, subscribe};
return k;
}
size_t AlgoWrapperOrder::working_children_count() const {
auto working_children_count = 0;
for (auto &c : me->children)
if (!c.second.state.has_value() ||
c.second.state.value().status == ChildStatus::WORKING) {
working_children_count++;
}
return working_children_count;
}
bool AlgoWrapperOrder::is_working() const {
return me->status == Status::WORKING;
}
log::CharPtrWrapper AlgoWrapperOrder::state_name(Status st) {
switch (st) {
case Status::COMPLETED:
return {"COMPLETED"};
case Status::W_ATTACH:
return {"W_ATTACH"};
case Status::INACTIVE:
return {"INACTIVE"};
case Status::WORKING:
return {"WORKING"};
case Status::SHUTTING_DOWN:
return {"SHUTTING_DOWN"};
}
bts_assert(false);
return {""};
}
ChildStatus AlgoWrapperOrder::map_child_status(api::orderman::OrderStatus st) {
switch (st) {
case ORDER_STATUS_COMPLETED:
return ChildStatus::COMPLETED;
case ORDER_STATUS_WORKING:
case ORDER_STATUS_PENDING_WORKING:
return ChildStatus::WORKING;
case ORDER_STATUS_CANCELED:
return ChildStatus::CANCELED;
default:
bts_assert(false);
return ChildStatus::CANCELED;
}
}
bool AlgoWrapperOrder::_is_attaching(
api::orderman::OrderDefinition const &def) const {
auto ak = OrderKey(def.attach_target_order_key());
return (ak != null_order_key() &&
!should_forward_attachment(def.custom_def()));
}
} // namespace orderman
} // namespace bts