From 6e5451e314dd4ae076202323f6f51c1cc4c38386 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Mon, 15 Apr 2019 12:11:53 -0400 Subject: [PATCH] Moved top order to use new AlgoOrder API. --- .../orderman/order_factory/OrderFactory.cpp | 4 +- .../orderman_utils/orderman_utils.cpp | 12 + src/lib/orderman/orders/algo/AlgoOrder.cpp | 284 +++++++++--------- src/lib/orderman/orders/algo/AlgoOrder.h | 48 +-- .../orderman/orders/book_algos/TopOrder.cpp | 280 ++++++++++------- src/lib/orderman/orders/book_algos/TopOrder.h | 43 +-- src/sdk/examples/order_plugin_example.cpp | 1 + 7 files changed, 396 insertions(+), 276 deletions(-) diff --git a/src/lib/orderman/order_factory/OrderFactory.cpp b/src/lib/orderman/order_factory/OrderFactory.cpp index 2e8533102..f49d87f89 100644 --- a/src/lib/orderman/order_factory/OrderFactory.cpp +++ b/src/lib/orderman/order_factory/OrderFactory.cpp @@ -16,7 +16,7 @@ #include "lib/orderman/orders/TriggerOrder.h" #include "lib/orderman/orders/book_algos/CoverOrder2.h" #include "lib/orderman/orders/book_algos/JoinOrder2.h" -#include "lib/orderman/orders/book_algos/TopOrder2.h" +#include "lib/orderman/orders/book_algos/TopOrder.h" #include "lib/orderman/orders/book_algos/LeanOrder2.h" #include "lib/orderman/orders/book_algos/OffsetOrder.h" #include "lib/orderman/orders/book_algos/OCOOrder.h" @@ -165,7 +165,7 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk, order_ptr.reset(new orderman::JoinOrder2()); break; case CustomOrderDefinition::kTop: - order_ptr.reset(new orderman::TopOrder2()); + order_ptr.reset(new orderman::TopOrder()); break; case CustomOrderDefinition::kTrigger: order_ptr.reset(new orderman::TriggerOrder()); diff --git a/src/lib/orderman/orderman_utils/orderman_utils.cpp b/src/lib/orderman/orderman_utils/orderman_utils.cpp index 43af5359b..8099a0b5a 100644 --- a/src/lib/orderman/orderman_utils/orderman_utils.cpp +++ b/src/lib/orderman/orderman_utils/orderman_utils.cpp @@ -32,6 +32,18 @@ bool should_forward_attachment( return cdef.join().has_child() && can_consume_attachment(cdef.join().child().custom_case()); + case CustomOrderDefinition::kTop: + return + cdef.top().has_child() && + can_consume_attachment(cdef.top().child().custom_case()); + case CustomOrderDefinition::kCover: + return + cdef.cover().has_child() && + can_consume_attachment(cdef.cover().child().custom_case()); + case CustomOrderDefinition::kLean: + return + cdef.lean().has_child() && + can_consume_attachment(cdef.lean().child().custom_case()); default: return false; } diff --git a/src/lib/orderman/orders/algo/AlgoOrder.cpp b/src/lib/orderman/orders/algo/AlgoOrder.cpp index 719874944..3a4578f58 100644 --- a/src/lib/orderman/orders/algo/AlgoOrder.cpp +++ b/src/lib/orderman/orders/algo/AlgoOrder.cpp @@ -1,10 +1,10 @@ #include "lib/orderman/orders/algo/AlgoOrder.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/utils/bts_assert.h" -#include "lib/orderman/actors/order_manager/OrderBuilder.h" #include #include @@ -90,15 +90,15 @@ struct AlgoOrder::PImpl { struct AlgoOrder::ReportStateGuard { ReportStateGuard(AlgoOrder &owner) : owner(owner) {} ~ReportStateGuard() { - if (owner.me->is_state_dirty) { - owner.me->is_state_dirty = false; - owner.me->services->report_state(owner.me->state()); + if (owner.self->is_state_dirty) { + owner.self->is_state_dirty = false; + owner.self->services->report_state(owner.self->state()); } } AlgoOrder &owner; }; -AlgoOrder::AlgoOrder() : me(new PImpl()) { setup_transitions(); } +AlgoOrder::AlgoOrder() : self(new PImpl()) { setup_transitions(); } AlgoOrder::~AlgoOrder() {} // -------------------------------------------------------------------------------- @@ -108,14 +108,24 @@ api::orderman::OrderDefinition const &AlgoOrder::definition() const { return *def(); } +OrderKey AlgoOrder::order_key() const { return key(); } + +OrderKey AlgoOrder::parent_order_key() const { return parent_key(); } + api::Security const *AlgoOrder::lookup_security(SecurityKey k) const { - return me->security_db->resolve(k); + return self->security_db->resolve(k); } -Price AlgoOrder::price() const { return Price(me->state().price()); } +Price AlgoOrder::price() const { return Price(self->state().price()); } Quantity AlgoOrder::quantity() const { - return Quantity(me->state().quantity()); + return Quantity(self->state().quantity()); +} + +bool AlgoOrder::is_attaching() const { + auto ak = OrderKey(self->definition.attach_target_order_key()); + return (ak != null_order_key() && + !should_forward_attachment(self->definition.custom_def())); } // -------------------------------------------------------------------------------- @@ -124,26 +134,28 @@ Quantity AlgoOrder::quantity() const { ChildTemplate & AlgoOrder::make_child_template(api::orderman::OrderDefinition const &child_def, size_t reserve) { - auto t = std::make_unique( - 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()); + auto t = std::make_unique(key(), child_def, + self->order_factory, reserve); + if (self->services) + t->builder.activate(*self->services); + self->child_templates.emplace_back(std::move(t)); + return *(self->child_templates.back()); } -OrderKey AlgoOrder::launch_child(ChildTemplate &t,Price p , Quantity q) -{ +OrderKey AlgoOrder::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); + return index_and_launch_child(t.builder.build(), p, q, subscribe_to_changes); } OrderKey AlgoOrder::launch_child(api::orderman::OrderDefinition const &def, - Price p, Quantity q) { + 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); + return index_and_launch_child(ChildOrder{def, *self->services}, p, q, + subscribe_to_changes); } void AlgoOrder::update_child(OrderKey child, @@ -151,8 +163,8 @@ void AlgoOrder::update_child(OrderKey child, if (!is_working()) return; - bts_assert(me->status == Status::WORKING); - if (auto it = me->children.find(child); it != me->children.end()) + bts_assert(self->status == Status::WORKING); + if (auto it = self->children.find(child); it != self->children.end()) it->second.order.update(update); else terminate_error(fmt::format("Algo {} tried to update unknown child: {}", @@ -163,8 +175,8 @@ void AlgoOrder::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()) + bts_assert(self->status == Status::WORKING); + if (auto it = self->children.find(child); it != self->children.end()) it->second.order.cancel(); else terminate_error(fmt::format("Algo {} tried to cancel unknown child: {}", @@ -175,7 +187,7 @@ void AlgoOrder::update_fill_state(Quantity q, Price p) { if (!is_working()) return; - auto previous_qty = me->state().filled_quantity(); + auto previous_qty = self->state().filled_quantity(); if (previous_qty > q.value()) { LOG(OrderMan, Error, "AlgoOrder {} is reporting a decrease in fill quantity " @@ -186,10 +198,10 @@ void AlgoOrder::update_fill_state(Quantity q, Price p) { auto new_avg_price = Price(0); if (q.value() > 0) new_avg_price.value() = - (me->state().filled_quantity() * me->state().avg_price() + + (self->state().filled_quantity() * self->state().avg_price() + (q.value() - previous_qty) * p.value()) / q.value(); - me->set_fill_quantities(q, p, new_avg_price); + self->set_fill_quantities(q, p, new_avg_price); } } @@ -202,7 +214,7 @@ void AlgoOrder::terminate_cancel(std::string const &msg) { void AlgoOrder::terminate_detach(std::string const &msg) { if (!is_working()) return; - me->children.clear(); + self->children.clear(); terminate(ORDER_STATUS_CANCELED, msg); } @@ -214,7 +226,7 @@ void AlgoOrder::terminate_error(std::string const &msg) { // cancel our child because that child might be a long running // order with a good queue position that we want to re-use. if (is_attaching()) - me->children.erase(OrderKey(definition().attach_target_order_key())); + self->children.erase(OrderKey(definition().attach_target_order_key())); terminate(ORDER_STATUS_ERROR, msg); } @@ -231,26 +243,26 @@ void AlgoOrder::terminate_complete() { void AlgoOrder::subscribe_book(SecurityKey k) { if (!is_working()) return; - bts_assert(me->book_subs.find(k) == me->book_subs.end()); + bts_assert(self->book_subs.find(k) == self->book_subs.end()); - me->book_subs[k] = me->services->subscribe_to_book( + self->book_subs[k] = self->services->subscribe_to_book( k, [this, k](auto const &ev) { on_book(k, ev.book); }); } void AlgoOrder::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); + bts_assert(self->book_subs.find(k) != self->book_subs.end()); + if (auto it = self->book_subs.find(k); it != self->book_subs.end()) + self->services->unsubscribe_from_book(it->second); } void AlgoOrder::subscribe_child_change(OrderKey k) { if (!is_working()) return; - auto it = me->children.find(k); - bts_assert(it != me->children.end()); + auto it = self->children.find(k); + bts_assert(it != self->children.end()); auto &child_record = it->second; bts_assert(!child_record.is_subscribing); child_record.is_subscribing = true; @@ -260,8 +272,8 @@ void AlgoOrder::unsubscribe_child_change(OrderKey k) { if (!is_working()) return; - auto it = me->children.find(k); - bts_assert(it != me->children.end()); + auto it = self->children.find(k); + bts_assert(it != self->children.end()); auto &child_record = it->second; bts_assert(child_record.is_subscribing); child_record.is_subscribing = false; @@ -273,13 +285,13 @@ void AlgoOrder::on_init_new(OrderDefinition const &def, 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; - + self->security_db = &serv.sec_db; + self->order_factory = &serv.order_factory; + // Save our order definition - me->definition = def; - me->security = serv.sec_db.resolve(SecurityKey(def.security_key())); - if (me->security == nullptr) + self->definition = def; + self->security = serv.sec_db.resolve(SecurityKey(def.security_key())); + if (self->security == nullptr) terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Unknown security"); auto result = do_before_launch(); @@ -290,13 +302,13 @@ void AlgoOrder::on_init_new(OrderDefinition const &def, void AlgoOrder::on_init_recovered(OrderRecord const &rec, const PreActivationOrderServices &serv) { auto const &def = rec.def(); - me->definition = def; - me->set_state(rec.state()); - me->security_db = &serv.sec_db; - me->order_factory = &serv.order_factory; - + self->definition = def; + self->set_state(rec.state()); + self->security_db = &serv.sec_db; + self->order_factory = &serv.order_factory; + // Infer internal status from persisted external status - switch (me->external_status()) { + switch (self->external_status()) { case ORDER_STATUS_WORKING: case ORDER_STATUS_PENDING_WORKING: @@ -325,21 +337,21 @@ OrderOpResult AlgoOrder::on_activate(Price p, Quantity q, OrderServices &services) { ReportStateGuard _(*this); - bts_assert(!me->services); - me->services = &services; - me->security_db = &services.sec_db(); - me->order_factory = &services.order_factory(); + bts_assert(!self->services); + self->services = &services; + self->security_db = &services.sec_db(); + self->order_factory = &services.order_factory(); - switch (me->status) { + switch (self->status) { case Status::INACTIVE: { - me->services->subscribe_to_child_updates([this](auto const &u) { + self->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); + self->set_external_status(ORDER_STATUS_WORKING); + self->set_price_quantity(p, q); + for (auto &ct : self->child_templates) + ct->builder.activate(*self->services); if (q.value() == 0) terminate(ORDER_STATUS_COMPLETED); else if (is_attaching()) @@ -363,18 +375,18 @@ OrderOpResult AlgoOrder::on_activate(Price p, Quantity q, OrderOpResult AlgoOrder::on_update(Update const &update) { ReportStateGuard _(*this); - switch (me->status) { + switch (self->status) { case Status::W_ATTACH: - me->pending_update = update; + self->pending_update = update; return {}; case Status::COMPLETED: return {}; case Status::WORKING: { - me->set_price_quantity(Price(update.price()), - Quantity(update.quantity())); + self->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); + *self->definition.mutable_custom_def() = update.custom(); + self->services->report_definition(self->definition); } do_update(update); return {}; @@ -402,10 +414,10 @@ orderman::OrderOpResult AlgoOrder::on_detach() { LOG(OrderMan, Info, "AlgoOrder order with key {} received detach", key().value()); - switch (me->status) { + switch (self->status) { case Status::W_ATTACH: case Status::WORKING: - me->children.clear(); + self->children.clear(); terminate(ORDER_STATUS_CANCELED); break; case Status::COMPLETED: @@ -420,7 +432,7 @@ orderman::OrderOpResult AlgoOrder::on_detach() { orderman::OrderOpResult AlgoOrder::on_cancel() { ReportStateGuard _(*this); - switch (me->status) { + switch (self->status) { case Status::W_ATTACH: case Status::WORKING: terminate(ORDER_STATUS_CANCELED); @@ -439,7 +451,7 @@ void AlgoOrder::on_attach_complete(OrderOpResult r, ChildOrder const &child, api::orderman::OrderState const &state) { ReportStateGuard _(*this); - switch (me->status) { + switch (self->status) { case Status::W_ATTACH: if (r.ok()) { bts_assert(state.status() == ORDER_STATUS_WORKING); @@ -449,7 +461,7 @@ void AlgoOrder::on_attach_complete(OrderOpResult r, ChildOrder const &child, key().value(), child.key().value()); // Store the order - auto &child_record = (me->children)[child.key()]; + auto &child_record = (self->children)[child.key()]; child_record.order = child; // This can cause a transition to error @@ -457,12 +469,12 @@ void AlgoOrder::on_attach_complete(OrderOpResult r, ChildOrder const &child, // If we did not change states (we could have if the attached child // as in an error state), we are ready to go - if (me->status == Status::W_ATTACH) + if (self->status == Status::W_ATTACH) transition(Status::WORKING); } else { terminate_error(fmt::format( "AlgoOrder order with key {} failed to attach to {}: {}", - key().value(), me->definition.attach_target_order_key(), + key().value(), self->definition.attach_target_order_key(), r.error_msg)); } break; @@ -479,9 +491,11 @@ void AlgoOrder::on_child_order_update( OrderKey child_key, api::orderman::OrderState const &new_child_state) { ReportStateGuard _(*this); - switch (me->status) { + switch (self->status) { case Status::WORKING: - if (auto it = me->children.find(child_key); it != me->children.end()) { + case Status::W_ATTACH: + if (auto it = self->children.find(child_key); + it != self->children.end()) { auto &child_record = it->second; switch (new_child_state.status()) { case ORDER_STATUS_COMPLETED: @@ -524,7 +538,6 @@ void AlgoOrder::on_child_order_update( case Status::COMPLETED: return; case Status::INACTIVE: - case Status::W_ATTACH: bts_assert(false); return; } @@ -533,118 +546,118 @@ void AlgoOrder::on_child_order_update( void AlgoOrder::setup_transitions() { // From INACTIVE - me->transition_actions[{Status::INACTIVE, Status::COMPLETED}] = [this]() { + self->transition_actions[{Status::INACTIVE, Status::COMPLETED}] = [this]() { _transition(Status::COMPLETED); }; - me->transition_actions[{Status::INACTIVE, Status::W_ATTACH}] = [this]() { - me->services->attach(OrderKey(me->definition.attach_target_order_key()), - [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); - }); + self->transition_actions[{Status::INACTIVE, Status::W_ATTACH}] = [this]() { + self->services->attach( + OrderKey(self->definition.attach_target_order_key()), + [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]() { + self->transition_actions[{Status::INACTIVE, Status::WORKING}] = [this]() { _transition(Status::WORKING); do_launch(); }; // From W_ATTACH - me->transition_actions[{Status::W_ATTACH, Status::COMPLETED}] = [this]() { + self->transition_actions[{Status::W_ATTACH, Status::COMPLETED}] = [this]() { _transition(Status::COMPLETED); }; - me->transition_actions[{Status::W_ATTACH, Status::WORKING}] = [this]() { + self->transition_actions[{Status::W_ATTACH, Status::WORKING}] = [this]() { _transition(Status::WORKING); auto attached_k = OrderKey(definition().attach_target_order_key()); - auto &maybe_state = me->children[attached_k].state; + auto &maybe_state = self->children[attached_k].state; bts_assert(maybe_state.has_value()); do_launch_attached(attached_k, maybe_state.value()); - if (me->status == Status::WORKING && me->pending_update.has_value()) { - auto update = me->pending_update.value(); - me->pending_update.reset(); - do_update(me->pending_update.value()); + if (self->status == Status::WORKING && self->pending_update.has_value()) { + auto update = self->pending_update.value(); + self->pending_update.reset(); + do_update(self->pending_update.value()); } }; // From WORKING - me->transition_actions[{Status::WORKING, Status::COMPLETED}] = [this]() { + self->transition_actions[{Status::WORKING, Status::COMPLETED}] = [this]() { cleanup(); _transition(Status::COMPLETED); }; } void AlgoOrder::check_invariants() { - bts_assert(me->security_db); - bts_assert(me->order_factory); - - switch (me->status) { + bts_assert(self->security_db); + bts_assert(self->order_factory); + + switch (self->status) { case Status::INACTIVE: bts_assert(false); return; case Status::W_ATTACH: - 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->children.empty()); + bts_assert(self->services); + bts_assert(self->security); + bts_assert(self->external_status() == ORDER_STATUS_WORKING); + bts_assert(self->book_subs.empty()); + bts_assert(self->children.empty()); 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(self->services); + bts_assert(self->security); + bts_assert(self->external_status() == ORDER_STATUS_WORKING); + bts_assert(!self->pending_update.has_value()); break; case Status::COMPLETED: - bts_assert(me->children.empty()); - 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->pending_update.has_value()); + bts_assert(self->children.empty()); + bts_assert(self->external_status() == ORDER_STATUS_CANCELED || + self->external_status() == ORDER_STATUS_COMPLETED || + self->external_status() == ORDER_STATUS_ERROR || + self->external_status() == ORDER_STATUS_REJECTED_BY_SPARK); + bts_assert(self->book_subs.empty()); + bts_assert(!self->pending_update.has_value()); break; } } void AlgoOrder::transition(Status new_status) { - if (auto it = me->transition_actions.find({me->status, new_status}); - it != me->transition_actions.end()) { + if (auto it = self->transition_actions.find({self->status, new_status}); + it != self->transition_actions.end()) { it->second(); } else { LOG(OrderMan, Fatal, "Illegal transition from {} to {}", - state_name(me->status), state_name(new_status)); + state_name(self->status), state_name(new_status)); bts_assert(false); } } void AlgoOrder::_transition(Status st) { LOG(OrderMan, Info, "Transitioninig AlgoOrder with key {} from {} to {}", - key().value(), state_name(me->status), state_name(st)); - me->status = st; + key().value(), state_name(self->status), state_name(st)); + self->status = st; check_invariants(); } void AlgoOrder::terminate(api::orderman::OrderStatus st, std::string const &error) { - me->set_external_status(st); + self->set_external_status(st); if (error.size()) - me->set_last_msg(error); + self->set_last_msg(error); transition(Status::COMPLETED); } void AlgoOrder::cleanup() { - for (auto const &s : me->book_subs) { - me->services->unsubscribe_from_book(s.second); - me->book_subs.clear(); + for (auto const &s : self->book_subs) { + self->services->unsubscribe_from_book(s.second); + self->book_subs.clear(); } - for (auto &c : me->children) { + for (auto &c : self->children) { c.second.order.cancel(); - me->children.clear(); + self->children.clear(); } } @@ -665,20 +678,16 @@ void AlgoOrder::update_child_record(api::orderman::OrderState const &new_state, map_child_status(new_state.status())}; } -OrderKey AlgoOrder::index_and_launch_child(ChildOrder &&child, Price p, Quantity q) { +OrderKey AlgoOrder::index_and_launch_child(ChildOrder &&child, Price p, + Quantity q, bool subscribe) { child.activate(p, q); - auto &cr = me->children[child.key()]; - cr = {std::move(child), {}, false}; - return child.key(); + auto k = child.key(); + auto &cr = self->children[k]; + cr = {std::move(child), {}, subscribe}; + return k; } -bool AlgoOrder::is_attaching() const { - auto ak = OrderKey(me->definition.attach_target_order_key()); - return (ak != null_order_key() && - !should_forward_attachment(me->definition.custom_def())); -} - -bool AlgoOrder::is_working() const { return me->status == Status::WORKING; } +bool AlgoOrder::is_working() const { return self->status == Status::WORKING; } log::CharPtrWrapper AlgoOrder::state_name(Status st) { switch (st) { @@ -704,7 +713,8 @@ ChildStatus AlgoOrder::map_child_status(api::orderman::OrderStatus st) { case ORDER_STATUS_CANCELED: return ChildStatus::CANCELED; default: - return ChildStatus::ERROR; + bts_assert(false); + return ChildStatus::CANCELED; } } diff --git a/src/lib/orderman/orders/algo/AlgoOrder.h b/src/lib/orderman/orders/algo/AlgoOrder.h index 512157453..67839eee3 100644 --- a/src/lib/orderman/orders/algo/AlgoOrder.h +++ b/src/lib/orderman/orders/algo/AlgoOrder.h @@ -6,7 +6,7 @@ namespace bts { namespace orderman { -enum class ChildStatus { WORKING, COMPLETED, CANCELED, ERROR }; +enum class ChildStatus { WORKING, COMPLETED, CANCELED }; struct ChildState { Price price; @@ -32,6 +32,10 @@ class AlgoOrder : private Order { // Returns the OrderDefinition for this order api::orderman::OrderDefinition const &definition() const; + // Returns the key of the order() + OrderKey order_key() const; + // Returns the parent key of the order() + OrderKey parent_order_key() const; // Resolves the security identified by k, returning nullptr if no // such security exists api::Security const *lookup_security(SecurityKey k) const; @@ -39,6 +43,8 @@ class AlgoOrder : private Order { Price price() const; // Returns the quantity for this order Quantity quantity() const; + // Returns wheter this order is attaching to an existing order + bool is_attaching() const; // -------------------------------------------------------------- // Commands @@ -56,12 +62,16 @@ class AlgoOrder : private Order { size_t reserve = 1); // Launch a new child order, based on a previously created template // at the specified price and quantity. This method can not be - // called from do_before_launch(). - OrderKey launch_child(ChildTemplate &, Price, Quantity); + // called from do_before_launch(). By default launching a child + // results in an automatic subscription to its state changes. + OrderKey launch_child(ChildTemplate &, Price, Quantity, + bool subscribe_to_changes = true); // Launch a new child order, using the speficied definition, price - // and quantity. This method cannot be called from do_before_launch(). + // and quantity. This method cannot be called from + // do_before_launch(). By default launching a child results in an + // automatic subscription to its state changes. OrderKey launch_child(api::orderman::OrderDefinition const &, Price, - Quantity); + Quantity, bool subscribe_to_changes = true); // Update previously launched child order. This method cannot be // called from do_before_launch(). void update_child(OrderKey child, api::orderman::Update const &); @@ -70,7 +80,7 @@ class AlgoOrder : private Order { void cancel_child(OrderKey child); // Update this order's filled quantity and last price. This method // cannot be called from do_before_launch(). - void update_fill_state(Quantity total_filled_quantity, Price last_price); + void update_fill_state(Quantity total_fills, Price last_price); // Cancel this order, optionally reporting an explanation. This // method cannot be called from do_before_launch(). void terminate_cancel(std::string const &msg = ""); @@ -100,7 +110,7 @@ class AlgoOrder : private Order { // Events // -------------------------------------------------------------- -// The child order specified by the order key has changed + // The child order specified by the order key has changed virtual void on_child_change(OrderKey, ChildState const &) {} // The book for the specified security has changed virtual void on_book(SecurityKey, Book const &) {} @@ -109,14 +119,15 @@ class AlgoOrder : private Order { // Hooks // -------------------------------------------------------------- - // Override this to setup an order prior to it being launched. This - // call occurs outside of the latency sensitive path so it can be - // used for any expensive initialization operations. However, note - // that at this point the order is not full initialized so only - // queries and child template creation can be done. Note as well - // that at this point it is not guaranteed the order will execute - // at all, since the order might simply have been created as part - // of a pool of orders used to speed up order launch. + // Override this to setup and validate an order prior to it being + // launched. This call occurs outside of the latency sensitive path + // so it can be used for any expensive initialization + // operations. However, note that at this point the order is not + // full initialized so only queries and child template creation can + // be done. Note as well that at this point it is not guaranteed + // the order will execute at all, since the order might simply have + // been created as part of a pool of orders used to speed up order + // launch. virtual OrderOpResult do_before_launch() { return {}; } // Implement this method to start your order virtual void do_launch() = 0; @@ -128,11 +139,12 @@ class AlgoOrder : private Order { virtual void do_update(api::orderman::Update const &) {} private: + friend class OrderFactory; struct ReportStateGuard; struct ChildRecord; enum class Status; struct PImpl; - std::unique_ptr me; + std::unique_ptr self; void on_init_new(api::orderman::OrderDefinition const &, const PreActivationOrderServices &) override; void on_init_recovered(api::orderman::OrderRecord const &, @@ -153,8 +165,8 @@ class AlgoOrder : private Order { void terminate(api::orderman::OrderStatus, std::string const &error = ""); void cleanup(); void update_child_record(api::orderman::OrderState const &, ChildRecord *); - OrderKey index_and_launch_child(ChildOrder &&child, Price p, Quantity q); - bool is_attaching() const; + OrderKey index_and_launch_child(ChildOrder &&child, Price p, Quantity q, + bool subscribe_child_change); bool is_working() const; log::CharPtrWrapper state_name(Status); ChildStatus map_child_status(api::orderman::OrderStatus); diff --git a/src/lib/orderman/orders/book_algos/TopOrder.cpp b/src/lib/orderman/orders/book_algos/TopOrder.cpp index 8fded05b5..ec7d8debc 100644 --- a/src/lib/orderman/orders/book_algos/TopOrder.cpp +++ b/src/lib/orderman/orders/book_algos/TopOrder.cpp @@ -1,10 +1,11 @@ -#include "TopOrder.h" +#include "lib/orderman/orders/book_algos/TopOrder.h" #include "lib/domain_model/Security.h" -#include "lib/orderman/actors/order_manager/OrderBuilder.h" +#include "lib/logging/logging.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orderman_utils/Book.h" #include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" #include "lib/utils/PBUtils.h" -#include namespace bts { namespace orderman { @@ -12,117 +13,194 @@ namespace orderman { using namespace api::orderman; struct TopOrder::PImpl { - PImpl() {} - - uint32_t watch_level_tick_offset; - spark::QuantityMeasure top_threshold; + spark::QuantityMeasure top_threshold_measure; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + Book last_book; }; TopOrder::TopOrder() : me(new PImpl()) {} - TopOrder::~TopOrder() {} -void TopOrder::setup_child(const api::orderman::OrderDefinition &this_def, - const PreActivationOrderServices &, - api::orderman::OrderState &initial_state, - api::orderman::OrderDefinition *out_child) { - initial_state.mutable_top(); - auto const &top_def = this_def.custom_def().top(); - *out_child->mutable_custom_def() = top_def.child(); +OrderOpResult TopOrder::do_before_launch() { + auto &def = definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_top()); - me->watch_level_tick_offset = top_def.watch_level_tick_offset(); - me->top_threshold = top_def.top_threshold(); + // Validate the top part of the definition + auto &top = def.custom_def().top(); + if (!top.has_child() && + OrderKey(def.attach_target_order_key()) == null_order_key()) { + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Top order must have either a child order definition or an " + "order to attach to"}; + } + + me->top_threshold_measure = top.top_threshold(); + + if (!is_attaching()) { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + api::orderman::OrderDefinition child_def = definition(); + *child_def.mutable_custom_def() = definition().custom_def().top().child(); + me->child_template = &(make_child_template(child_def)); + } + + return {}; } -void TopOrder::on_book_update(const bts::orderman::BookUpdateEvent &book) { - switch (this_state().status()) { - case ORDER_STATUS_WORKING: - switch (child_state().status()) { - case ORDER_STATUS_INACTIVE: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->top_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &same = book.book.side(api::Side::SIDE_BUY)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - transition(ORDER_STATUS_CANCELED); - report_state(); - return; - } - } - } else { - const auto &same = book.book.side(api::Side::SIDE_SELL)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - transition(ORDER_STATUS_CANCELED); - report_state(); - return; - } - } - } - activate_child(Price(this_state().price()), - Quantity(this_state().quantity())); - transition(ORDER_STATUS_WORKING); - report_state(); - } break; - case ORDER_STATUS_WORKING: { - Quantity thresh = SpreaderUtils::_quantity_threshold( - me->top_threshold, Quantity(this_state().quantity())); - if (definition().side() == api::SIDE_BUY) { - const auto &same = book.book.side(api::Side::SIDE_BUY)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - cancel_child(); - transition(ORDER_STATUS_CANCELED); - report_state(); - } - } - } else { - const auto &same = book.book.side(api::Side::SIDE_SELL)[0]; - if (securities::test_price_equality(this_state().price(), - same.price(), tick_size())) { - if (same.size() <= thresh.value()) { - cancel_child(); - transition(ORDER_STATUS_CANCELED); - report_state(); - } - } - } - } break; +void TopOrder::do_launch() { + subscribe_book(SecurityKey(definition().security_key())); +} - case ORDER_STATUS_PENDING_WORKING: - break; +void TopOrder::do_launch_attached(OrderKey k, ChildState st) { + me->child_key = k; + subscribe_book(SecurityKey(definition().security_key())); + subscribe_child_change(k); + on_child_change(k, st); +} - // child cannot be in any of these states if we are in the working state - case ORDER_STATUS_DISCONNECTED: - case ORDER_STATUS_ERROR: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; - } - break; +void TopOrder::do_update(api::orderman::Update const &update) { - case ORDER_STATUS_COMPLETED: - case ORDER_STATUS_CANCELED: - case ORDER_STATUS_ERROR: - break; + LOG(OrderMan, Diag, "Top order {} receiving update: {}", order_key().value(), + utils::pb::to_string(update)); - case ORDER_STATUS_INACTIVE: - case ORDER_STATUS_REJECTED_BY_SPARK: - case ORDER_STATUS_PENDING_WORKING: - case ORDER_STATUS_DISCONNECTED: - case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: - case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: - bts_assert(false); - break; + if (update.has_custom() && !update.custom().has_top()) { + terminate_error("Invalid update"); + return; } + + Update child_update; + child_update.set_price(update.price()); + child_update.set_quantity(update.quantity()); + + if (update.has_custom()) { + // process custom part of the udpate if any + auto &top_update = update.custom().top(); + *child_update.mutable_custom() = top_update.child(); + me->top_threshold_measure = top_update.top_threshold(); + + // if we have not yet launched our child we need to update + // our child template + if (!has_running_child()) { + bts_assert(me->child_template != nullptr); + api::orderman::OrderDefinition child_def = definition(); + *child_def.mutable_custom_def() = + definition().custom_def().top().child(); + me->child_template = &(make_child_template(child_def)); + } + } + update_child(me->child_key, child_update); +} + +void TopOrder::on_book(SecurityKey, Book const &b) { + me->last_book = b; + if (has_running_child()) + ensure_min_quantity(); + else { + // If we do not have a running child, because we had not yet + // received a book, we have to make sure its OK to launch it. + if (better_than_top()) { + terminate_cancel("Order would become BBO on inception"); + return; + } + + if (at_top_of_book() && top_of_book_quantity() < min_quantity_at_top()) { + terminate_cancel("Top of book is below threshold"); + return; + } + + // If we reached this point we are clear to launch our child + bts_assert(me->child_template); + me->child_key = launch_child(*me->child_template, price(), quantity()); + } +} + +void TopOrder::on_child_change(OrderKey, ChildState const &st) { + update_fill_state(st.total_fills, st.last_price); + + switch (st.status) { + case ChildStatus::WORKING: + return; + case ChildStatus::COMPLETED: + terminate_complete(); + return; + case ChildStatus::CANCELED: + terminate_cancel("Unexpected child cancel"); + return; + } +} + +bool TopOrder::ensure_min_quantity() { + LOG(OrderMan, Diag, + "Top order {} received book update. Current top of book: {}@{}", + order_key().value(), top_of_book_quantity().value(), + top_of_book_price().value()); + + if (better_than_top()) { + LOG(OrderMan, Diag, + "Top order {} became better than the top of the book, canceling", + order_key().value()); + terminate_cancel("Order would become BBO"); + return false; + } + + if (at_top_of_book()) { + auto total_min_quantity = + quantity().value() + min_quantity_at_top().value(); + LOG(OrderMan, Diag, + "Top order {} is now at the top of the book, min quantity for book " + "is: {}" + " book quantity is: {}", + order_key().value(), total_min_quantity, + top_of_book_quantity().value()); + if (top_of_book_quantity() < Quantity(total_min_quantity)) { + LOG(OrderMan, Diag, + "Top order {} is canceling because min quantiy is not met", + order_key().value()); + terminate_cancel("Top of book is below threshold"); + return false; + } + } else + LOG(OrderMan, Diag, + "Top order {} is not at the top of the book. Order: {} Book: {}", + order_key().value(), price().value(), top_of_book_price().value()); + + return true; +} + +bool TopOrder::at_top_of_book() const { + auto my_side = definition().side(); + auto &my_side_psz = me->last_book.side(my_side)[0]; + + return securities::is_same(price(), Price(my_side_psz.price())); +} + +bool TopOrder::better_than_top() const { + auto my_side = definition().side(); + return securities::is_better(my_side, price(), top_of_book_price()); +} + +Quantity TopOrder::min_quantity_at_top() const { + return SpreaderUtils::_quantity_threshold(me->top_threshold_measure, + quantity()); +} + +bool TopOrder::has_running_child() const { + return me->child_key != null_order_key(); +} + +Price TopOrder::top_of_book_price() const { + auto my_side = definition().side(); + auto &my_side_psz = me->last_book.side(my_side)[0]; + return Price(my_side_psz.price()); +} + +Quantity TopOrder::top_of_book_quantity() const { + auto my_side = definition().side(); + auto &my_side_psz = me->last_book.side(my_side)[0]; + return Quantity(my_side_psz.size()); } } // namespace orderman diff --git a/src/lib/orderman/orders/book_algos/TopOrder.h b/src/lib/orderman/orders/book_algos/TopOrder.h index 4736def75..42b5b884b 100644 --- a/src/lib/orderman/orders/book_algos/TopOrder.h +++ b/src/lib/orderman/orders/book_algos/TopOrder.h @@ -1,30 +1,37 @@ #pragma once -#include "lib/orderman/orders/book_algos/BookAlgo.h" +#include "lib/orderman/orders/algo/AlgoOrder.h" namespace bts { namespace orderman { -class OrderStateUpdateEvent; -class BookUpdateEvent; +// If TopOrder becomes the top of book, it cancels if there is less +// than some threshold of size joined with it. -//If TopOrder becomes the top of book, it cancels if there is less than some threshold of size joined with it. -//Fills optionally trigger hedge orders to the opposite side of the market, n ticks away. - -class TopOrder : public BookAlgo -{ -public: +class TopOrder : public AlgoOrder { + public: TopOrder(); - virtual ~TopOrder(); - -protected: - void setup_child(const api::orderman::OrderDefinition& this_def, const PreActivationOrderServices&, - api::orderman::OrderState&, api::orderman::OrderDefinition*) override; - void on_book_update(const bts::orderman::BookUpdateEvent&) override; - -private: + ~TopOrder(); + + OrderOpResult do_before_launch() override; + void do_launch() override; + void do_launch_attached(OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_book(SecurityKey, Book const &) override; + void on_child_change(OrderKey, ChildState const &) override; + + private: struct PImpl; std::unique_ptr me; + + bool at_top_of_book() const; + bool better_than_top() const; + Quantity min_quantity_at_top() const; + bool ensure_min_quantity(); + bool has_running_child() const; + Price top_of_book_price() const; + Quantity top_of_book_quantity() const; }; -}} +} // namespace orderman +} // namespace bts diff --git a/src/sdk/examples/order_plugin_example.cpp b/src/sdk/examples/order_plugin_example.cpp index 4989c9b99..035c7e7c7 100644 --- a/src/sdk/examples/order_plugin_example.cpp +++ b/src/sdk/examples/order_plugin_example.cpp @@ -6,6 +6,7 @@ #include "spark/lib/orderman/orders/DynamicOrder.h" #include "spark/lib/plugin/SparkServices.h" #include "spark/lib/utils/PBUtils.h" +#include "spark/lib/orderman/orders/PreActivationOrderServices.h" using namespace bts::api::orderman; using namespace bts::orderman;