From 5135a21dc24a470415053210ce7c350804a6e92a Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Thu, 23 May 2019 15:27:41 -0400 Subject: [PATCH 01/27] ProRata and Scratch Algos --- src/lib/api/services/OrderService.proto | 18 ++ .../orderman/events/OrderStateUpdateEvent.h | 6 + .../orderman/order_factory/OrderFactory.cpp | 10 + .../orders/algo/algo_orders/ProRataAlgo.cpp | 218 ++++++++++++++++++ .../orders/algo/algo_orders/ProRataAlgo.h | 37 +++ .../orders/algo/algo_orders/ScratchAlgo.cpp | 210 +++++++++++++++++ .../orders/algo/algo_orders/ScratchAlgo.h | 36 +++ 7 files changed, 535 insertions(+) create mode 100644 src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp create mode 100644 src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h create mode 100644 src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp create mode 100644 src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index b16c4d584..9e4ffa534 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -100,6 +100,8 @@ message CustomOrderDefinition OCOOrderDefinition oco = 25; PricerOrderDefinition pricer = 26; CompositeOrderDefinition composite = 27; + ScratchOrderDefinition scratch = 28; + ProRataOrderDefinition prorata = 29; DynamicOrderDefinition dynamic = 1000; } @@ -197,6 +199,18 @@ message CompositeOrderDefinition { uint32 algo_template_key = 1; CustomOrderDefinition definition = 2; } +message ScratchOrderDefinition { + spark.QuantityMeasure scratch_threshold = 1; + CustomOrderDefinition child = 10; +} +message ProRataOrderDefinition { + spark.QuantityMeasure fill_limit = 1; + spark.QuantityMeasure scratch_threshold = 2; + spark.QuantityMeasure stay_in_threshold = 3; + bool enable_scratch_on_overfill = 4; + bool enable_stay_in = 5; + CustomOrderDefinition child = 10; +} message DynamicOrderDefinition { string dynamic_order_type = 1; map order_params = 2; @@ -249,6 +263,8 @@ message OrderState { QueueHolderState queue_holder = 30; OCOOrderState oco = 25; PricerOrderState pricer = 26; + ScratchOrderState scratch = 27; + ProRataOrderState prorata = 28; DynamicOrderState dynamic = 255; // do not use anything bigger than 255, or things will break } @@ -324,6 +340,8 @@ message CoverOrderState {} message OffsetOrderState {} message OCOOrderState {} message PricerOrderState {} +message ScratchOrderState {} +message ProRataOrderState {} message DynamicOrderState {} message QueueHolderState {} diff --git a/src/lib/orderman/events/OrderStateUpdateEvent.h b/src/lib/orderman/events/OrderStateUpdateEvent.h index 7556ce6b4..af86ddf3a 100644 --- a/src/lib/orderman/events/OrderStateUpdateEvent.h +++ b/src/lib/orderman/events/OrderStateUpdateEvent.h @@ -146,6 +146,12 @@ class OrderStateUpdateEvent : public mercury::Event { case api::orderman::OrderState::kPricer: result.mutable_pricer(); break; + case api::orderman::OrderState::kScratch: + result.mutable_scratch(); + break; + case api::orderman::OrderState::kProrata: + result.mutable_prorata(); + break; case api::orderman::OrderState::kDynamic: result.mutable_dynamic(); break; diff --git a/src/lib/orderman/order_factory/OrderFactory.cpp b/src/lib/orderman/order_factory/OrderFactory.cpp index 2cbac4d4b..b83c35e57 100644 --- a/src/lib/orderman/order_factory/OrderFactory.cpp +++ b/src/lib/orderman/order_factory/OrderFactory.cpp @@ -19,6 +19,8 @@ #include "lib/orderman/orders/algo/algo_orders/TopAlgo.h" #include "lib/orderman/orders/algo/algo_orders/IcebergAlgo.h" #include "lib/orderman/orders/algo/algo_orders/LeanAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/ScratchAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/ProRataAlgo.h" #include "lib/orderman/orders/book_algos/OCOOrder.h" #include "lib/orderman/orders/book_algos/OffsetOrder.h" #include "lib/orderman/orders/book_algos/PricerOrder.h" @@ -193,6 +195,14 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk, case CustomOrderDefinition::kPricer: order_ptr.reset(new orderman::PricerOrder()); break; + case CustomOrderDefinition::kScratch: + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); + break; + case CustomOrderDefinition::kProrata: + order_ptr.reset( + new orderman::AlgoWrapperOrder(std::make_unique())); + break; case CustomOrderDefinition::kDynamic: { order_ptr = me->dynamic_order_registry.build( def.custom_def().dynamic().dynamic_order_type()); diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp new file mode 100644 index 000000000..14666bcbf --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -0,0 +1,218 @@ +#include "lib/orderman/orders/algo/algo_orders/ProRataAlgo.h" + +#include "lib/domain_model/Security.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class ProRataAlgo::Status { WORKING, WAITING_FOR_HEDGES, DONE }; +const char *ProRataAlgo::status_name(Status st) { + switch (st) { + case Status::WORKING: + return "WORKING"; + case Status::WAITING_FOR_HEDGES: + return "WAITING_FOR_HEDGES"; + case Status::DONE: + return "Done"; + } + return nullptr; +} +struct ProRataAlgo::PImpl { + IAlgoServices *algo; + OrderKey child_key = null_order_key(); + Price price_improvement_delta; + ChildTemplate *child_template = nullptr; + ChildTemplate *hedge_template = nullptr; + Quantity hedged_fills = Quantity(0); + Status status = Status::WORKING; + std::vector hedges; +}; + +ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} +ProRataAlgo::~ProRataAlgo() {} +IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } + +OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_cover()); + + // Validate the cover part of the definition + auto &cover = def.custom_def().cover(); + if (!cover.has_child() && + OrderKey(def.attach_target_order_key()) == null_order_key()) { + return OrderOpResult{ + ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Cover order must have either a child order definition or an " + "order to attach to"}; + } + + if (!cover.has_hedge()) + return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Cover order must have a hedge order definition"}; + if (!serv.is_attaching()) { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().cover().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + + init_hedge_template(serv, cover.hedge()); + set_price_improvement_delta(serv, cover); + return {}; +} + +void ProRataAlgo::do_launch(IAlgoServices &algo) { + me->algo = &algo; + LOG(OrderMan, Diag, "Starting ProRataAlgo {}, {} {}@{}. Will cover {} ticks", + algo.order_key().value(), + securities::side_name(algo.definition().side()), algo.quantity().value(), + algo.price().value(), + algo.definition().custom_def().cover().hedge_ticks()); + + LOG(OrderMan, Diag, "ProRataAlgo {} launching child", + algo.order_key().value()); + me->child_key = + algo.launch_child(*me->child_template, algo.price(), algo.quantity()); +} + +void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, + ChildState st) { + me->algo = &algo; + me->child_key = k; + me->hedged_fills = st.total_fills; + on_child_change(k, st); +} + +void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) { + if (k == me->child_key) { + if (st.total_fills.value() > me->hedged_fills.value()) { + auto hedge_qty = + Quantity(st.total_fills.value() - me->hedged_fills.value()); + auto hedge_price = securities::improve_price( + algo().definition().side(), st.last_price, + me->price_improvement_delta); + + auto hedge = + algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); + me->hedges.push_back(hedge); + + me->hedged_fills = + Quantity(hedge_qty.value() + me->hedged_fills.value()); + LOG(OrderMan, Diag, + "ProRataAlgo {}, launched new hedge in response to child fill. " + "Hedge: " + "{} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); + } + algo().update_fill_state(st.total_fills, st.last_price); + switch (st.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::COMPLETED: + LOG(OrderMan, Info, + "ProRataAlgo {}. Child is completed, waiting for hedges ", + algo().order_key().value()); + me->status = Status::WAITING_FOR_HEDGES; + break; + case ChildStatus::CANCELED: + LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, terminating", + algo().order_key().value()); + me->status = Status::DONE; + algo().terminate_error("Unexpected child cancel"); + break; + } + } else { + switch (st.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::COMPLETED: + if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); + it != me->hedges.end()) + me->hedges.erase(it); + break; + case ChildStatus::CANCELED: + LOG(OrderMan, Info, "ProRataAlgo {}. Hedge was canceled, terminating", + algo().order_key().value()); + me->status = Status::DONE; + algo().terminate_error("Unexpected child cancel"); + break; + } + } + check_terminate(); +} + +void ProRataAlgo::do_update(api::orderman::Update const &update) { + if (me->status == Status::WORKING) { + LOG(OrderMan, Diag, "ProRataAlgo order {} receiving update: {}", + algo().order_key().value(), utils::pb::to_string(update)); + + if (update.has_custom() && !update.custom().has_cover()) { + algo().terminate_error("Invalid update"); + return; + } + + Update child_update; + child_update.set_price(update.price()); + child_update.set_quantity(update.quantity()); + + // process custom part of the udpate if any + if (update.has_custom()) { + auto &cover_update = update.custom().cover(); + set_price_improvement_delta(algo(), cover_update); + if (cover_update.has_child()) { + *child_update.mutable_custom() = cover_update.child(); + } + if (cover_update.has_hedge()) + init_hedge_template(algo(), cover_update.hedge()); + } + algo().update_child(me->child_key, child_update); + } else { + LOG(OrderMan, Info, + "ProRataAlgo {}. Received update after child has completed. Ignoring " + "it.", + algo().order_key().value()); + } +} + +void orderman::ProRataAlgo::init_hedge_template( + IBeforeLaunchAlgoServices &algo, + api::orderman::CustomOrderDefinition const &hedge_cdef) { + auto hedge_def = algo.definition(); + hedge_def.set_side(securities::other_side(algo.definition().side())); + hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); + hedge_def.clear_attach_target_order_key(); + *hedge_def.mutable_custom_def() = hedge_cdef; + me->hedge_template = &(algo.make_child_template(hedge_def)); +} + +void ProRataAlgo::set_price_improvement_delta( + IBeforeLaunchAlgoServices &serv, + api::orderman::CoverOrderDefinition const &cover) { + me->price_improvement_delta = Price( + securities::tick_size(serv.security()).value() * cover.hedge_ticks()); +} + +void ProRataAlgo::check_terminate() { + LOG(OrderMan, Diag, + "ProRataAlgo {} check_terminate. State: {} Hedge count: {}", + algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, + me->hedges.size()); + + if (me->status == Status::WAITING_FOR_HEDGES && me->hedges.empty()) { + LOG(OrderMan, Info, "ProRataAlgo {}. Last hedge completed, terminating", + algo().order_key().value()); + algo().complete(); + } +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h new file mode 100644 index 000000000..71b68b465 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -0,0 +1,37 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// Cover initializes the child order as normal. Fills trigger hedge +// orders to the opposite side of the market, n ticks away. + +class ProRataAlgo : public IAlgoOrder { +public: + ProRataAlgo(); + ~ProRataAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; + void do_update(api::orderman::Update const &) override; + void on_child_change(OrderKey, ChildState const &) override; + +private: + struct PImpl; + enum class Status; + std::unique_ptr me; + IAlgoServices &algo() const; + void + set_price_improvement_delta(IBeforeLaunchAlgoServices &, + api::orderman::CoverOrderDefinition const &); + void init_hedge_template(IBeforeLaunchAlgoServices &, + api::orderman::CustomOrderDefinition const &); + void check_terminate(); + const char *status_name(Status st); +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp new file mode 100644 index 000000000..8d3936a08 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -0,0 +1,210 @@ +#include "lib/orderman/orders/algo/algo_orders/ScratchAlgo.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" + +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" + +namespace bts { +namespace orderman { + +using namespace api::orderman; + +enum class ScratchAlgo::Status { WAITING_FOR_MD, WAITING_TO_SCRATCH, SCRATCHED }; + +struct ScratchAlgo::PImpl +{ + IAlgoServices *algo; + Quantity scratch_threshold; + Status status = Status::WAITING_FOR_MD; + OrderKey child_key = null_order_key(); + ChildTemplate *child_template = nullptr; + Book last_book; + Price scratch_price=Price(os::nan()); +}; + +ScratchAlgo::ScratchAlgo() : me(new PImpl()) {} +ScratchAlgo::~ScratchAlgo() {} +IAlgoServices &ScratchAlgo::algo() const { return *me->algo; } + +OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) +{ + auto &def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_scratch()); + + // Validate the scratch part of the definition + auto &scratch = def.custom_def().scratch(); + if (!scratch.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) + { + return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, + "Scratch order must have either a child order definition or an order to attach to"}; + } + if (!serv.is_attaching()) + { + // if we are not attaching create a child template so we can + // quickly launch our child when the time comes. + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().scratch().child(); + me->child_template = &(serv.make_child_template(child_def)); + } + return {}; +} + +void ScratchAlgo::do_launch(IAlgoServices &algo) +{ + me->algo = &algo; + update_scratch_threshold(); + bts_assert(me->child_template); + me->child_key = algo.launch_child(*me->child_template, algo.price(), algo.quantity()); + algo.subscribe_book(SecurityKey(algo.security().id())); +} + +void ScratchAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st) +{ + me->algo = &algo; + update_scratch_threshold(); + me->child_key = k; + algo.subscribe_book(SecurityKey(algo.security().id())); + on_child_change(k, st); +} + +void ScratchAlgo::do_update(api::orderman::Update const &update) +{ + LOG(OrderMan, Diag, "ScratchOrder order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); + if (update.has_custom() && !update.custom().has_scratch()) + { + algo().terminate_error("Invalid update"); + return; + } + + Update child_update; + Price price_to_pass = get_price_to_pass(Price(update.price())); + child_update.set_price(price_to_pass.value()); + child_update.set_quantity(update.quantity()); + if (update.has_custom()) + { + update_scratch_threshold(); + auto &scratch_update = update.custom().scratch(); + *child_update.mutable_custom() = scratch_update.child(); + } + algo().update_child(me->child_key, child_update); + + // If we were not yet scratched it is possible we now can, since we + // could have changed the scratch_threshold + if (me->status == Status::WAITING_TO_SCRATCH) + try_to_scratch(); +} + +void ScratchAlgo::on_book(SecurityKey, Book const &b) +{ + me->last_book = b; + + LOG(OrderMan, Diag, "ScratchOrder order {} on book. BID: {}@{} ASK: {}@{}", + algo().order_key().value(), b.side(api::SIDE_BUY)[0].size(), + b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(), + b.side(api::SIDE_SELL)[0].price()); + + switch (me->status) + { + case Status::WAITING_FOR_MD: + { + auto other_side = securities::other_side(algo().definition().side()); + auto &other_side_top = me->last_book.side(other_side)[0]; + + if (other_side_top.size() > 0) + { + me->status = Status::WAITING_TO_SCRATCH; + LOG(OrderMan, Diag, + "ScratchOrder order {} receiving first book: {} Target: {}", + algo().order_key().value(), me->scratch_threshold.value(), + other_side_top.price()); + try_to_scratch(); + } + } break; + case Status::SCRATCHED: + break; + case Status::WAITING_TO_SCRATCH: + try_to_scratch(); + break; + } +} + +void ScratchAlgo::try_to_scratch() +{ + bts_assert(me->status == Status::WAITING_TO_SCRATCH); + auto my_side = algo().definition().side(); + auto other_side = securities::other_side(my_side); + + Quantity my_quan; + bool found = SpreaderUtils::find_qty_upto_price_level(me->last_book, my_side, algo().price(), /*unused*/ 0.0, my_quan); + auto &my_side_psz = me->last_book.side(my_side)[0]; + if (found && my_quan.value() <= me->scratch_threshold.value()) + { + Price scratch_price; + Quantity scratch_quan; + SpreaderUtils::traverse_depth_for_quantity(me->last_book, other_side, algo().quantity(), scratch_price, scratch_quan); + LOG(OrderMan, Diag, "ScratchOrder order {} scratching: {}@{} {}", + algo().order_key().value(), algo().quantity().value(), scratch_price, scratch_quan); + + // Time to scratch + Update child_update; + me->scratch_price = scratch_price; + child_update.set_price(scratch_price.value()); + //we still want to try to scratch all of it + child_update.set_quantity(algo().quantity().value()); + algo().update_child(me->child_key, child_update); + me->status = Status::SCRATCHED; + } + else + { + LOG(OrderMan, Diag, + "ScratchOrder order {} still waiting to scratch. Order: {}@{} " + "My side: {}@{}" + "Thresh : {}@{}", + algo().order_key().value(), algo().quantity().value(), algo().price().value(), + my_side_psz.size(), my_side_psz.price(), + me->scratch_threshold.value(), my_quan); + } +} + +Price ScratchAlgo::get_price_to_pass (Price price) const +{ + Price rv; + switch (me->status) { + case Status::WAITING_FOR_MD: + case Status::WAITING_TO_SCRATCH: + rv = price; + break; + case Status::SCRATCHED: + rv = me->scratch_price; + break; + } + return rv; +} + +void ScratchAlgo::update_scratch_threshold() +{ + me->scratch_threshold = SpreaderUtils::_quantity_threshold( + algo().definition().custom_def().scratch().scratch_threshold(), algo().quantity()); +} + +void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) +{ + algo().update_fill_state(st.total_fills, st.last_price); + switch (st.status) + { + case ChildStatus::WORKING: + return; + case ChildStatus::COMPLETED: + algo().complete(); + return; + case ChildStatus::CANCELED: + algo().cancel("Unexpected child cancel"); + return; + } +} + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h new file mode 100644 index 000000000..d86487366 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h @@ -0,0 +1,36 @@ +#pragma once + +#include "lib/orderman/orders/algo/IAlgoOrder.h" + +namespace bts { +namespace orderman { + +// Scratch monitors the cumulative size on the same side of the market of it's child +// if that size falls below the threshold it will cross the market, paying through enough levels to do all of it's size + +class ScratchAlgo : public IAlgoOrder +{ +public: + ScratchAlgo(); + ~ScratchAlgo(); + + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices&) override; + void do_launch(IAlgoServices &) override; + void do_launch_attached(IAlgoServices&,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: + enum class Status; + struct PImpl; + std::unique_ptr me; + + IAlgoServices &algo() const ; + void update_scratch_threshold(); + bool has_running_child() const; + void try_to_scratch(); + Price get_price_to_pass (Price price) const; +}; + +}} From 91bc135c61f50f34a3d31069680aa0a8e489aff3 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 23 May 2019 15:49:12 -0400 Subject: [PATCH 02/27] Fix web ui build --- src/web/ui/src/Accounts/View.fs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/web/ui/src/Accounts/View.fs b/src/web/ui/src/Accounts/View.fs index be6133fbf..f931c6de0 100644 --- a/src/web/ui/src/Accounts/View.fs +++ b/src/web/ui/src/Accounts/View.fs @@ -28,7 +28,7 @@ let isDirty model = account <> model.scratch | None -> false -let saveButton model dispatch = +let saveButton (model:Model) dispatch = let isNew = isNewAccount model.scratch let buttonText = if isNew then "Create" else "Save" let dirty = isDirty model || isNew @@ -50,7 +50,7 @@ let accountControls model (dispatch:Msg->unit) = // // General // -let generalView model dispatch = +let generalView (model:Model) dispatch = let account = model.scratch @@ -549,7 +549,7 @@ let lazyProductLimitsView model dispatch = productLimits model dispatch -let securityLimitsView model dispatch = +let securityLimitsView (model:Model) dispatch = let headerRow:TableControl.row = { cells = @@ -737,7 +737,7 @@ let ConnectionsView (model:Accounts.Types.Model) dispatch = let creditLimitsView model dispatch = div [] [str "lorem ipsum"] -let exchangeSettings model dispatch = +let exchangeSettings (model:Model) dispatch = let cme = model.scratch.exchangeAccountData.cmeAccountData let sim = model.scratch.exchangeAccountData.simAccountData let send = UpdateCME>>dispatch @@ -760,7 +760,7 @@ let exchangeSettings model dispatch = accountControls model dispatch ] -let tabContent model dispatch = +let tabContent (model:Model) dispatch = div [Key (string model.scratch.id); ClassName "is-tab-content"] [ // (match model.tab with (match model.tab, (accountIsSelected model.scratch Access.Accounts.empty) with From 3a516df5931a1c39fb9b2337791e85db1b74fbfc Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Thu, 23 May 2019 18:16:20 -0400 Subject: [PATCH 03/27] more prorata --- src/lib/api/services/OrderService.proto | 14 +- .../orders/algo/algo_orders/ProRataAlgo.cpp | 264 +++++++++++------- .../orders/algo/algo_orders/ProRataAlgo.h | 14 +- .../orders/algo/algo_orders/ScratchAlgo.cpp | 7 +- 4 files changed, 191 insertions(+), 108 deletions(-) diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 9e4ffa534..75ed9f7b6 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -204,12 +204,16 @@ message ScratchOrderDefinition { CustomOrderDefinition child = 10; } message ProRataOrderDefinition { - spark.QuantityMeasure fill_limit = 1; - spark.QuantityMeasure scratch_threshold = 2; - spark.QuantityMeasure stay_in_threshold = 3; - bool enable_scratch_on_overfill = 4; - bool enable_stay_in = 5; + uint32 hedge_ticks = 1; + spark.QuantityMeasure fill_limit = 2; + spark.QuantityMeasure scratch_threshold = 3; + spark.QuantityMeasure stay_in_threshold = 4; + bool enable_scratch_on_overfill = 5; + bool enable_stay_in = 6; + CustomOrderDefinition child = 10; + CustomOrderDefinition hedge = 20; + CustomOrderDefinition overfill_hedge = 30; } message DynamicOrderDefinition { string dynamic_order_type = 1; diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 14666bcbf..731002886 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -3,6 +3,7 @@ #include "lib/domain_model/Security.h" #include "lib/orderman/order_factory/IOrderFactory.h" #include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" #include "lib/utils/PBUtils.h" namespace bts { @@ -10,152 +11,224 @@ namespace orderman { using namespace api::orderman; -enum class ProRataAlgo::Status { WORKING, WAITING_FOR_HEDGES, DONE }; -const char *ProRataAlgo::status_name(Status st) { - switch (st) { - case Status::WORKING: - return "WORKING"; - case Status::WAITING_FOR_HEDGES: - return "WAITING_FOR_HEDGES"; +enum class ProRataAlgo::Status { WAITING_FOR_MD, UNDERFILLED, OVERFILLED, DONE }; +const char *ProRataAlgo::status_name(Status st) +{ + switch (st) + { + case Status::WAITING_FOR_MD: + return "WAITING_FOR_MD"; + case Status::UNDERFILLED: + return "UNDERFILLED"; + case Status::OVERFILLED: + return "OVERFILLED"; case Status::DONE: - return "Done"; + return "DONE"; } return nullptr; } -struct ProRataAlgo::PImpl { +struct ProRataAlgo::PImpl +{ IAlgoServices *algo; OrderKey child_key = null_order_key(); - Price price_improvement_delta; + Quantity fill_limit; + Quantity scratch_threshold; + Quantity stay_in_threshold; ChildTemplate *child_template = nullptr; + + Price hedge_ticks; ChildTemplate *hedge_template = nullptr; + ChildTemplate *overfill_hedge_template = nullptr; + Quantity hedged_fills = Quantity(0); - Status status = Status::WORKING; + Status status = Status::WAITING_FOR_MD; std::vector hedges; + std::vector overfill_hedges; + + Book last_book; + Book book_at_inception; }; ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} ProRataAlgo::~ProRataAlgo() {} IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } -OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { +OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) +{ auto &def = serv.definition(); bts_assert(def.has_custom_def()); - bts_assert(def.custom_def().has_cover()); + bts_assert(def.custom_def().has_prorata()); - // Validate the cover part of the definition - auto &cover = def.custom_def().cover(); - if (!cover.has_child() && - OrderKey(def.attach_target_order_key()) == null_order_key()) { - return OrderOpResult{ - ORDER_ERROR_INVALID_ORDER_DEFINITON, - "Cover order must have either a child order definition or an " - "order to attach to"}; + // Validate the prorata part of the definition + auto &prorata = def.custom_def().prorata(); + if (!prorata.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) + { + return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, + "ProRata order must have either a child order definition or an order to attach to"}; } - if (!cover.has_hedge()) + if (!prorata.has_hedge()) return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, - "Cover order must have a hedge order definition"}; - if (!serv.is_attaching()) { + "ProRata order must have a hedge order definition"}; + if (!serv.is_attaching()) + { // if we are not attaching create a child template so we can // quickly launch our child when the time comes. auto child_def = def; - *child_def.mutable_custom_def() = def.custom_def().cover().child(); + *child_def.mutable_custom_def() = def.custom_def().prorata().child(); me->child_template = &(serv.make_child_template(child_def)); } - init_hedge_template(serv, cover.hedge()); - set_price_improvement_delta(serv, cover); + init_hedge_template(serv, prorata.hedge()); + init_hedge_template(serv, prorata.overfill_hedge()); + set_hedge_ticks(serv, prorata); return {}; } -void ProRataAlgo::do_launch(IAlgoServices &algo) { +void ProRataAlgo::do_launch(IAlgoServices &algo) +{ me->algo = &algo; LOG(OrderMan, Diag, "Starting ProRataAlgo {}, {} {}@{}. Will cover {} ticks", algo.order_key().value(), securities::side_name(algo.definition().side()), algo.quantity().value(), algo.price().value(), - algo.definition().custom_def().cover().hedge_ticks()); + algo.definition().custom_def().prorata().hedge_ticks()); - LOG(OrderMan, Diag, "ProRataAlgo {} launching child", - algo.order_key().value()); - me->child_key = - algo.launch_child(*me->child_template, algo.price(), algo.quantity()); + LOG(OrderMan, Diag, "ProRataAlgo {} launching child", algo.order_key().value()); + me->child_key = algo.launch_child(*me->child_template, algo.price(), algo.quantity()); + algo.subscribe_book(SecurityKey(algo.security().id())); } -void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, - ChildState st) { +void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st) +{ me->algo = &algo; me->child_key = k; me->hedged_fills = st.total_fills; + algo.subscribe_book(SecurityKey(algo.security().id())); on_child_change(k, st); } -void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) { - if (k == me->child_key) { - if (st.total_fills.value() > me->hedged_fills.value()) { - auto hedge_qty = - Quantity(st.total_fills.value() - me->hedged_fills.value()); - auto hedge_price = securities::improve_price( - algo().definition().side(), st.last_price, - me->price_improvement_delta); - auto hedge = - algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); - me->hedges.push_back(hedge); +void ProRataAlgo::on_book(SecurityKey, Book const &b) +{ + me->last_book = b; + + LOG(OrderMan, Diag, "ProRataAlgo order {} on book. BID: {}@{} ASK: {}@{}", + algo().order_key().value(), b.side(api::SIDE_BUY)[0].size(), + b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(), + b.side(api::SIDE_SELL)[0].price()); - me->hedged_fills = - Quantity(hedge_qty.value() + me->hedged_fills.value()); + switch (me->status) + { + case Status::WAITING_FOR_MD: + { + auto other_side = securities::other_side(algo().definition().side()); + auto &other_side_top = me->last_book.side(other_side)[0]; + + if (other_side_top.size() > 0) + { + me->status = Status::UNDERFILLED; + me->book_at_inception = b; LOG(OrderMan, Diag, - "ProRataAlgo {}, launched new hedge in response to child fill. " - "Hedge: " - "{} {}@{}", - algo().order_key().value(), - securities::side_name(algo().definition().side()), - hedge_qty.value(), hedge_price.value()); + "ProRataAlgo order {} receiving first book: {} Target: {}", + algo().order_key().value(), me->scratch_threshold.value(), + other_side_top.price()); + } + } break; + case Status::UNDERFILLED: + break; + case Status::OVERFILLED: + //TODO bail.... + break; + case Status::DONE: + break; + } +} + +void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) +{ + if (k == me->child_key) + { + if (st.total_fills.value() > me->hedged_fills.value()) + { + auto hedge_qty = Quantity(st.total_fills.value() - me->hedged_fills.value()); + me->hedged_fills = Quantity(hedge_qty.value() + me->hedged_fills.value()); + auto hedge_price = securities::improve_price(algo().definition().side(), st.last_price, me->hedge_ticks); + if(me->hedged_fills < me->fill_limit) + { + auto hedge = algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); + me->hedges.push_back(hedge); + LOG(OrderMan, Diag, + "ProRataAlgo {}, launched new hedge in response to child fill. " + "Hedge: " + "{} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); + } + else + { + auto hedge = algo().launch_child(*me->overfill_hedge_template, hedge_price, hedge_qty); + me->overfill_hedges.push_back(hedge); + LOG(OrderMan, Diag, + "ProRataAlgo {}, launched new OVERFILL hedge in response to child fill. " + "Hedge: " + "{} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); + me->status = Status::OVERFILLED; + } } algo().update_fill_state(st.total_fills, st.last_price); - switch (st.status) { + switch (st.status) + { case ChildStatus::WORKING: break; case ChildStatus::COMPLETED: LOG(OrderMan, Info, - "ProRataAlgo {}. Child is completed, waiting for hedges ", - algo().order_key().value()); - me->status = Status::WAITING_FOR_HEDGES; + "ProRataAlgo {}. Child is completed, waiting for hedges ", algo().order_key().value()); break; case ChildStatus::CANCELED: - LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, terminating", - algo().order_key().value()); + LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, terminating", algo().order_key().value()); me->status = Status::DONE; algo().terminate_error("Unexpected child cancel"); break; } - } else { - switch (st.status) { + } + else //it's a hedge + { + switch (st.status) + { case ChildStatus::WORKING: break; case ChildStatus::COMPLETED: - if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); - it != me->hedges.end()) + if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); it != me->hedges.end()) me->hedges.erase(it); + if (auto oit = std::find(me->overfill_hedges.begin(), me->overfill_hedges.end(), k); oit != me->overfill_hedges.end()) + me->overfill_hedges.erase(oit); break; case ChildStatus::CANCELED: - LOG(OrderMan, Info, "ProRataAlgo {}. Hedge was canceled, terminating", - algo().order_key().value()); - me->status = Status::DONE; - algo().terminate_error("Unexpected child cancel"); + LOG(OrderMan, Info, "ProRataAlgo {}. Hedge was canceled, removing", algo().order_key().value()); + if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); it != me->hedges.end()) + me->hedges.erase(it); + if (auto oit = std::find(me->overfill_hedges.begin(), me->overfill_hedges.end(), k); oit != me->overfill_hedges.end()) + me->overfill_hedges.erase(oit); break; } } check_terminate(); } -void ProRataAlgo::do_update(api::orderman::Update const &update) { - if (me->status == Status::WORKING) { +void ProRataAlgo::do_update(api::orderman::Update const &update) +{ + if (me->status != Status::DONE) + { LOG(OrderMan, Diag, "ProRataAlgo order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); - if (update.has_custom() && !update.custom().has_cover()) { + if (update.has_custom() && !update.custom().has_prorata()) + { algo().terminate_error("Invalid update"); return; } @@ -165,27 +238,31 @@ void ProRataAlgo::do_update(api::orderman::Update const &update) { child_update.set_quantity(update.quantity()); // process custom part of the udpate if any - if (update.has_custom()) { - auto &cover_update = update.custom().cover(); - set_price_improvement_delta(algo(), cover_update); - if (cover_update.has_child()) { - *child_update.mutable_custom() = cover_update.child(); - } - if (cover_update.has_hedge()) - init_hedge_template(algo(), cover_update.hedge()); + if (update.has_custom()) + { + //TODO MORE + auto &prorata_update = update.custom().prorata(); + set_hedge_ticks(algo(), prorata_update); + if (prorata_update.has_child()) + *child_update.mutable_custom() = prorata_update.child(); + if (prorata_update.has_hedge()) + init_hedge_template(algo(), prorata_update.hedge()); + if (prorata_update.has_overfill_hedge()) + init_hedge_template(algo(), prorata_update.overfill_hedge()); } algo().update_child(me->child_key, child_update); - } else { + } + else + { LOG(OrderMan, Info, - "ProRataAlgo {}. Received update after child has completed. Ignoring " - "it.", + "ProRataAlgo {}. Received update after child has completed. Ignoring it.", algo().order_key().value()); } } -void orderman::ProRataAlgo::init_hedge_template( - IBeforeLaunchAlgoServices &algo, - api::orderman::CustomOrderDefinition const &hedge_cdef) { +void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, + api::orderman::CustomOrderDefinition const &hedge_cdef) +{ auto hedge_def = algo.definition(); hedge_def.set_side(securities::other_side(algo.definition().side())); hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); @@ -194,22 +271,21 @@ void orderman::ProRataAlgo::init_hedge_template( me->hedge_template = &(algo.make_child_template(hedge_def)); } -void ProRataAlgo::set_price_improvement_delta( - IBeforeLaunchAlgoServices &serv, - api::orderman::CoverOrderDefinition const &cover) { - me->price_improvement_delta = Price( - securities::tick_size(serv.security()).value() * cover.hedge_ticks()); +void ProRataAlgo::set_hedge_ticks(IBeforeLaunchAlgoServices &serv, api::orderman::CoverOrderDefinition const &cover) +{ + me->hedge_ticks = Price(securities::tick_size(serv.security()).value() * cover.hedge_ticks()); } -void ProRataAlgo::check_terminate() { +void ProRataAlgo::check_terminate() +{ LOG(OrderMan, Diag, "ProRataAlgo {} check_terminate. State: {} Hedge count: {}", algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, me->hedges.size()); - if (me->status == Status::WAITING_FOR_HEDGES && me->hedges.empty()) { - LOG(OrderMan, Info, "ProRataAlgo {}. Last hedge completed, terminating", - algo().order_key().value()); + if (me->status != Status::DONE && me->hedges.empty() && me->overfill_hedges.empty()) + { + LOG(OrderMan, Info, "ProRataAlgo {}. Last hedge completed, terminating", algo().order_key().value()); algo().complete(); } } diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index 71b68b465..497fa4531 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -5,10 +5,11 @@ namespace bts { namespace orderman { -// Cover initializes the child order as normal. Fills trigger hedge -// orders to the opposite side of the market, n ticks away. +// ProRata initializes the child order as normal. Fills trigger one type of hedge, overfills (fills > limit) trigger another +// type of hedge. Overfills also optionally trigger overfill_hedge scratching and cancelling children dependent on book state -class ProRataAlgo : public IAlgoOrder { +class ProRataAlgo : public IAlgoOrder +{ public: ProRataAlgo(); ~ProRataAlgo(); @@ -24,11 +25,8 @@ private: enum class Status; std::unique_ptr me; IAlgoServices &algo() const; - void - set_price_improvement_delta(IBeforeLaunchAlgoServices &, - api::orderman::CoverOrderDefinition const &); - void init_hedge_template(IBeforeLaunchAlgoServices &, - api::orderman::CustomOrderDefinition const &); + void set_hedge_ticks(IBeforeLaunchAlgoServices &, api::orderman::CoverOrderDefinition const &); + void init_hedge_template(IBeforeLaunchAlgoServices &, api::orderman::CustomOrderDefinition const &); void check_terminate(); const char *status_name(Status st); }; diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 8d3936a08..766b37d31 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -21,6 +21,7 @@ struct ScratchAlgo::PImpl OrderKey child_key = null_order_key(); ChildTemplate *child_template = nullptr; Book last_book; + Book book_at_inception; Price scratch_price=Price(os::nan()); }; @@ -116,6 +117,7 @@ void ScratchAlgo::on_book(SecurityKey, Book const &b) if (other_side_top.size() > 0) { me->status = Status::WAITING_TO_SCRATCH; + me->book_at_inception = b; LOG(OrderMan, Diag, "ScratchOrder order {} receiving first book: {} Target: {}", algo().order_key().value(), me->scratch_threshold.value(), @@ -140,7 +142,10 @@ void ScratchAlgo::try_to_scratch() Quantity my_quan; bool found = SpreaderUtils::find_qty_upto_price_level(me->last_book, my_side, algo().price(), /*unused*/ 0.0, my_quan); auto &my_side_psz = me->last_book.side(my_side)[0]; - if (found && my_quan.value() <= me->scratch_threshold.value()) + auto &other_side_psz = me->last_book.side(other_side)[0]; + bool market_moved = other_side_psz.price() != my_side_psz.price(); + + if (market_moved || found && my_quan.value() <= me->scratch_threshold.value()) { Price scratch_price; Quantity scratch_quan; From e1f590127eef4640ed5da527a63760464bf80f95 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Thu, 23 May 2019 23:55:26 -0400 Subject: [PATCH 04/27] ready to test --- src/lib/api/services/OrderService.proto | 1 - .../orders/algo/algo_orders/ProRataAlgo.cpp | 140 +++++++++++------- .../orders/algo/algo_orders/ProRataAlgo.h | 11 +- .../orders/algo/algo_orders/ScratchAlgo.cpp | 2 +- 4 files changed, 95 insertions(+), 59 deletions(-) diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 75ed9f7b6..d2bc605bc 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -206,7 +206,6 @@ message ScratchOrderDefinition { message ProRataOrderDefinition { uint32 hedge_ticks = 1; spark.QuantityMeasure fill_limit = 2; - spark.QuantityMeasure scratch_threshold = 3; spark.QuantityMeasure stay_in_threshold = 4; bool enable_scratch_on_overfill = 5; bool enable_stay_in = 6; diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 731002886..2bdd18e55 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -11,17 +11,15 @@ namespace orderman { using namespace api::orderman; -enum class ProRataAlgo::Status { WAITING_FOR_MD, UNDERFILLED, OVERFILLED, DONE }; +enum class ProRataAlgo::Status { WAITING_FOR_MD, WORKING, DONE }; //this is for the child const char *ProRataAlgo::status_name(Status st) { switch (st) { case Status::WAITING_FOR_MD: return "WAITING_FOR_MD"; - case Status::UNDERFILLED: - return "UNDERFILLED"; - case Status::OVERFILLED: - return "OVERFILLED"; + case Status::WORKING: + return "WORKING"; case Status::DONE: return "DONE"; } @@ -29,14 +27,20 @@ const char *ProRataAlgo::status_name(Status st) } struct ProRataAlgo::PImpl { + PImpl() : + is_overfilled(false) + { + } IAlgoServices *algo; OrderKey child_key = null_order_key(); + + Price hedge_price_diff; Quantity fill_limit; - Quantity scratch_threshold; Quantity stay_in_threshold; - ChildTemplate *child_template = nullptr; + bool enable_scratch_on_overfill; + bool enable_stay_in; - Price hedge_ticks; + ChildTemplate *child_template = nullptr; ChildTemplate *hedge_template = nullptr; ChildTemplate *overfill_hedge_template = nullptr; @@ -47,6 +51,7 @@ struct ProRataAlgo::PImpl Book last_book; Book book_at_inception; + bool is_overfilled; }; ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} @@ -68,8 +73,7 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) } if (!prorata.has_hedge()) - return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, - "ProRata order must have a hedge order definition"}; + return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, "ProRata order must have a hedge order definition"}; if (!serv.is_attaching()) { // if we are not attaching create a child template so we can @@ -81,7 +85,7 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) init_hedge_template(serv, prorata.hedge()); init_hedge_template(serv, prorata.overfill_hedge()); - set_hedge_ticks(serv, prorata); + set_parameters(serv, prorata); return {}; } @@ -109,7 +113,7 @@ void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState } -void ProRataAlgo::on_book(SecurityKey, Book const &b) +void ProRataAlgo::on_book(SecurityKey, const Book& b) { me->last_book = b; @@ -127,25 +131,58 @@ void ProRataAlgo::on_book(SecurityKey, Book const &b) if (other_side_top.size() > 0) { - me->status = Status::UNDERFILLED; + me->status = Status::WORKING; me->book_at_inception = b; LOG(OrderMan, Diag, "ProRataAlgo order {} receiving first book: {} Target: {}", - algo().order_key().value(), me->scratch_threshold.value(), + algo().order_key().value(), me->fill_limit.value(), other_side_top.price()); } - } break; - case Status::UNDERFILLED: - break; - case Status::OVERFILLED: - //TODO bail.... + } + break; + case Status::WORKING: + check_overfill(); break; case Status::DONE: + check_overfill(); break; } } -void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) +void ProRataAlgo::check_overfill() +{ + if(me->is_overfilled) + { + if(me->enable_stay_in) + { + auto my_side = algo().definition().side(); + auto other_side = securities::other_side(my_side); + + Quantity my_quan; + bool found = SpreaderUtils::find_qty_upto_price_level(me->last_book, my_side, algo().price(), /*unused*/ 0.0, my_quan); + auto &my_side_psz = me->last_book.side(my_side)[0]; + auto &other_side_psz = me->last_book.side(other_side)[0]; + bool market_moved = other_side_psz.price() != my_side_psz.price(); + + if (market_moved || !found || (found && my_quan.value() <= me->stay_in_threshold.value()) ) + get_out(); + } + else + get_out(); + } +} + +void ProRataAlgo::get_out() +{ + if(me->enable_scratch_on_overfill) + { + //scratch all my overs TODO + me->enable_scratch_on_overfill = false; + } + algo().cancel_child(me->child_key); +} + +void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) { if (k == me->child_key) { @@ -153,31 +190,30 @@ void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) { auto hedge_qty = Quantity(st.total_fills.value() - me->hedged_fills.value()); me->hedged_fills = Quantity(hedge_qty.value() + me->hedged_fills.value()); - auto hedge_price = securities::improve_price(algo().definition().side(), st.last_price, me->hedge_ticks); + auto hedge_price = securities::improve_price(algo().definition().side(), st.last_price, me->hedge_price_diff); if(me->hedged_fills < me->fill_limit) { auto hedge = algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); me->hedges.push_back(hedge); LOG(OrderMan, Diag, "ProRataAlgo {}, launched new hedge in response to child fill. " - "Hedge: " - "{} {}@{}", + "Hedge: {} {}@{}", algo().order_key().value(), securities::side_name(algo().definition().side()), hedge_qty.value(), hedge_price.value()); } else - { + { auto hedge = algo().launch_child(*me->overfill_hedge_template, hedge_price, hedge_qty); me->overfill_hedges.push_back(hedge); LOG(OrderMan, Diag, "ProRataAlgo {}, launched new OVERFILL hedge in response to child fill. " - "Hedge: " - "{} {}@{}", + "Hedge: {} {}@{}", algo().order_key().value(), securities::side_name(algo().definition().side()), - hedge_qty.value(), hedge_price.value()); - me->status = Status::OVERFILLED; + hedge_qty.value(), hedge_price.value()); + me->is_overfilled = true; + check_overfill(); } } algo().update_fill_state(st.total_fills, st.last_price); @@ -186,13 +222,12 @@ void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) case ChildStatus::WORKING: break; case ChildStatus::COMPLETED: - LOG(OrderMan, Info, - "ProRataAlgo {}. Child is completed, waiting for hedges ", algo().order_key().value()); + LOG(OrderMan, Info, "ProRataAlgo {}. Child is completed, waiting for hedges ", algo().order_key().value()); + me->status = Status::DONE; break; case ChildStatus::CANCELED: - LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, terminating", algo().order_key().value()); - me->status = Status::DONE; - algo().terminate_error("Unexpected child cancel"); + LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, waiting on hedges", algo().order_key().value()); + me->status = Status::DONE; break; } } @@ -201,15 +236,9 @@ void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) switch (st.status) { case ChildStatus::WORKING: - break; - case ChildStatus::COMPLETED: - if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); it != me->hedges.end()) - me->hedges.erase(it); - if (auto oit = std::find(me->overfill_hedges.begin(), me->overfill_hedges.end(), k); oit != me->overfill_hedges.end()) - me->overfill_hedges.erase(oit); - break; + break; case ChildStatus::CANCELED: - LOG(OrderMan, Info, "ProRataAlgo {}. Hedge was canceled, removing", algo().order_key().value()); + case ChildStatus::COMPLETED: if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); it != me->hedges.end()) me->hedges.erase(it); if (auto oit = std::find(me->overfill_hedges.begin(), me->overfill_hedges.end(), k); oit != me->overfill_hedges.end()) @@ -220,7 +249,7 @@ void ProRataAlgo::on_child_change(OrderKey k, ChildState const &st) check_terminate(); } -void ProRataAlgo::do_update(api::orderman::Update const &update) +void ProRataAlgo::do_update(const api::orderman::Update& update) { if (me->status != Status::DONE) { @@ -240,14 +269,14 @@ void ProRataAlgo::do_update(api::orderman::Update const &update) // process custom part of the udpate if any if (update.has_custom()) { - //TODO MORE auto &prorata_update = update.custom().prorata(); - set_hedge_ticks(algo(), prorata_update); - if (prorata_update.has_child()) + set_parameters(algo(), prorata_update); + + if(prorata_update.has_child()) *child_update.mutable_custom() = prorata_update.child(); - if (prorata_update.has_hedge()) + if(prorata_update.has_hedge()) init_hedge_template(algo(), prorata_update.hedge()); - if (prorata_update.has_overfill_hedge()) + if(prorata_update.has_overfill_hedge()) init_hedge_template(algo(), prorata_update.overfill_hedge()); } algo().update_child(me->child_key, child_update); @@ -261,7 +290,7 @@ void ProRataAlgo::do_update(api::orderman::Update const &update) } void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, - api::orderman::CustomOrderDefinition const &hedge_cdef) + const api::orderman::CustomOrderDefinition& hedge_cdef) { auto hedge_def = algo.definition(); hedge_def.set_side(securities::other_side(algo.definition().side())); @@ -271,19 +300,24 @@ void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, me->hedge_template = &(algo.make_child_template(hedge_def)); } -void ProRataAlgo::set_hedge_ticks(IBeforeLaunchAlgoServices &serv, api::orderman::CoverOrderDefinition const &cover) +void ProRataAlgo::set_parameters(IBeforeLaunchAlgoServices &serv, const api::orderman::ProRataOrderDefinition& prorata) { - me->hedge_ticks = Price(securities::tick_size(serv.security()).value() * cover.hedge_ticks()); + me->hedge_price_diff = Price(securities::tick_size(serv.security()).value() * prorata.hedge_ticks()); + if(prorata.has_fill_limit()) + me->fill_limit = SpreaderUtils::_quantity_threshold(prorata.fill_limit(), algo().quantity()); + if(prorata.has_stay_in_threshold()) + me->stay_in_threshold = SpreaderUtils::_quantity_threshold(prorata.stay_in_threshold(), algo().quantity()); + me->enable_scratch_on_overfill = prorata.enable_scratch_on_overfill(); + me->enable_stay_in = prorata.enable_stay_in(); } void ProRataAlgo::check_terminate() { LOG(OrderMan, Diag, "ProRataAlgo {} check_terminate. State: {} Hedge count: {}", - algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, - me->hedges.size()); + algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, me->hedges.size()); - if (me->status != Status::DONE && me->hedges.empty() && me->overfill_hedges.empty()) + if (me->status == Status::DONE && me->hedges.empty() && me->overfill_hedges.empty()) { LOG(OrderMan, Info, "ProRataAlgo {}. Last hedge completed, terminating", algo().order_key().value()); algo().complete(); diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index 497fa4531..9ed33bdea 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -17,16 +17,19 @@ public: OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; void do_launch(IAlgoServices &) override; void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override; - void do_update(api::orderman::Update const &) override; - void on_child_change(OrderKey, ChildState const &) override; + void do_update(const api::orderman::Update&) override; + void on_book(SecurityKey, const Book&) override; + void on_child_change(OrderKey, const ChildState&) override; private: struct PImpl; enum class Status; std::unique_ptr me; IAlgoServices &algo() const; - void set_hedge_ticks(IBeforeLaunchAlgoServices &, api::orderman::CoverOrderDefinition const &); - void init_hedge_template(IBeforeLaunchAlgoServices &, api::orderman::CustomOrderDefinition const &); + void set_parameters(IBeforeLaunchAlgoServices &, const api::orderman::ProRataOrderDefinition&); + void init_hedge_template(IBeforeLaunchAlgoServices &, const api::orderman::CustomOrderDefinition&); + void get_out(); + void check_overfill(); void check_terminate(); const char *status_name(Status st); }; diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 766b37d31..443b200a2 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -145,7 +145,7 @@ void ScratchAlgo::try_to_scratch() auto &other_side_psz = me->last_book.side(other_side)[0]; bool market_moved = other_side_psz.price() != my_side_psz.price(); - if (market_moved || found && my_quan.value() <= me->scratch_threshold.value()) + if (market_moved || !found || (found && my_quan.value() <= me->scratch_threshold.value()) ) { Price scratch_price; Quantity scratch_quan; From c8c6aea1882e508d5eee6df07b4e2f1b30130795 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Fri, 24 May 2019 15:50:46 -0400 Subject: [PATCH 05/27] gui for haris orders --- .../Orders/OrderTypeVMs/DynamicOrderHelper.cs | 17 ++++++ .../OrderTypeVMs/DynamicOrderParamVM.cs | 38 +++++++++++++ .../Orders/OrderTypeVMs/DynamicOrderVM.cs | 6 ++ src/lib/api/services/OrderService.proto | 2 + .../orders/algo/algo_orders/ProRataAlgo.cpp | 25 +++++++++ .../orders/algo/algo_orders/ProRataAlgo.h | 1 + .../orders/algo/algo_orders/ScratchAlgo.cpp | 19 ++++++- .../orders/algo/algo_orders/ScratchAlgo.h | 4 +- src/server/sparkd/cmds/Run.cpp | 55 +++++++++++++++++++ 9 files changed, 163 insertions(+), 4 deletions(-) diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs index 8587e9e92..f08137c66 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs @@ -71,6 +71,7 @@ namespace mbts.spark { case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef: param.AsOrderDef = new CustomOrderDefinition(); break; case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: param.AsString = string.Empty; break; case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: param.AsUint32 = 0u; break; + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: param.AsQuantity = new bts.spark.QuantityMeasure(); break; } break; case DynamicOrderTypeDescriptor.DescriptorOneofCase.Structure: param.AsStruct = new DynamicOrderStruct(); break; @@ -87,5 +88,21 @@ namespace mbts.spark { } param.AsEnumerated.EnumValue = value ?? string.Empty; } + + internal static bts.spark.QuantityMeasureImmutable? get_quantity_value(DynamicOrderParam param) + { + return new bts.spark.QuantityMeasureImmutable(param?.AsQuantity); + } + internal static void set_quantity_value(DynamicOrderParam param, bts.spark.QuantityMeasureImmutable? value) + { + if (param == null) + { + return; + } + else if (param.ValueCase != DynamicOrderParam.ValueOneofCase.AsQuantity) + { + param.AsQuantity = value?.CloneToMutable(); + } + } } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs index 9cf2c4962..def02cd07 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs @@ -1,6 +1,7 @@ using bts.api.orderman; using Google.Protobuf.Reflection; using mbts.ui.shell; +using bts.spark; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -116,4 +117,41 @@ namespace mbts.spark { void _sync_elements() => elements.sync_with(_get_elements(descriptor)); } + + + class DynamicOrderQuantityVM : DynamicOrderParamVM, IDynamicOrderParamVM + { + static readonly FieldDescriptor _field_desc = DynamicOrderParam.Descriptor.FindFieldByNumber(DynamicOrderParam.AsQuantityFieldNumber); + QuantityMeasureImmutable? _value; + public DynamicOrderQuantityVM(DynamicOrderParamDescriptor descriptor) + : base(descriptor) + { + } + + public QuantityMeasureImmutable? value + { + get => _value; + set + { + _value = value; + _field_desc.Accessor.SetValue(param, _value?.CloneToMutable()); + RaisePropertyChanged(); + } + } + + public IObservable subscribe_value() => + Observable.Create(o => + { + PropertyChanged += on_prop_changed; + return Disposable.Create(() => PropertyChanged -= on_prop_changed); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => + o.OnNext(value); + }); + + protected override void on_param_changed() + { + _value = new QuantityMeasureImmutable( (QuantityMeasure) _field_desc.Accessor.GetValue(param)); + RaisePropertyChanged(nameof(value)); + } + } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs index c54208b68..848602c12 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs @@ -5,6 +5,7 @@ using mbts.collections; using mbts.spark.utilities; using mbts.ui.utility; using mbts.utils; +using bts.spark; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -73,6 +74,11 @@ namespace mbts.spark { case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return mk(DynamicOrderParam.AsInt32FieldNumber, v => v, v => v.GetValueOrDefault()); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return mk(DynamicOrderParam.AsUint32FieldNumber, v => v, v => v.GetValueOrDefault()); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return mk(DynamicOrderParam.AsStringFieldNumber, v => v, v => v); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: + { + var qm = new DynamicOrderQuantityVM(descriptor); + return attached(qm, DynamicOrderHelper.get_quantity_value, DynamicOrderHelper.set_quantity_value, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 })); + } default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.Primitive, nameof(descriptor)); } case DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated: diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index d2bc605bc..f90925449 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -563,6 +563,7 @@ enum DynamicOrderPrimitiveDescriptor { DYNAMIC_ORDER_PRIMITIVE_STRING = 3; DYNAMIC_ORDER_PRIMITIVE_BOOL = 4; DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF = 5; + DYNAMIC_ORDER_PRIMITIVE_QUANTITY = 6; } message DynamicOrderTypeDescriptor { @@ -611,6 +612,7 @@ message DynamicOrderParam { DynamicOrderArray as_array = 7; DynamicOrderStruct as_struct = 8; DynamicOrderEnumerated as_enumerated = 9; + spark.QuantityMeasure as_quantity = 10; } } diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 2bdd18e55..5ad8dfc96 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -58,6 +58,31 @@ ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} ProRataAlgo::~ProRataAlgo() {} IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } +void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) +{ + if (def.has_custom_def() && def.custom_def().has_dynamic()) + { + auto& dprorata = def.custom_def().dynamic(); + auto& mutable_def = const_cast(def); //TODO Terrible hack + auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); + + if(dprorata.order_params().count("hedge_ticks") > 0) + prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); + if(dprorata.order_params().count("fill_limit") > 0) + *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); + if(dprorata.order_params().count("stay_in_threshold") > 0) + *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); + if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) + prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); + if(dprorata.order_params().count("enable_stay_in") > 0) + prorata.set_enable_stay_in(dprorata.order_params().at("enable_stay_in").as_bool()); + + *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); + *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); + *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); + } +} + OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { auto &def = serv.definition(); diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index 9ed33bdea..f4c19960a 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -32,6 +32,7 @@ private: void check_overfill(); void check_terminate(); const char *status_name(Status st); + void check_dynamic(const api::orderman::OrderDefinition&); }; } // namespace orderman diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 443b200a2..ea3ad3744 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -29,12 +29,27 @@ ScratchAlgo::ScratchAlgo() : me(new PImpl()) {} ScratchAlgo::~ScratchAlgo() {} IAlgoServices &ScratchAlgo::algo() const { return *me->algo; } +void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) +{ + if (def.has_custom_def() && def.custom_def().has_dynamic()) + { + auto& dscratch = def.custom_def().dynamic(); + auto& mutable_def = const_cast(def); //TODO Terrible hack + auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); + + if(dscratch.order_params().count("scratch_threshold") > 0) + *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); + + *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); + } +} + OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - auto &def = serv.definition(); + const api::orderman::OrderDefinition& def = serv.definition(); + check_dynamic(def); bts_assert(def.has_custom_def()); bts_assert(def.custom_def().has_scratch()); - // Validate the scratch part of the definition auto &scratch = def.custom_def().scratch(); if (!scratch.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h index d86487366..76c220a80 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h @@ -27,10 +27,10 @@ private: std::unique_ptr me; IAlgoServices &algo() const ; - void update_scratch_threshold(); - bool has_running_child() const; + void update_scratch_threshold(); void try_to_scratch(); Price get_price_to_pass (Price price) const; + void check_dynamic(const api::orderman::OrderDefinition&); }; }} diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 3c9b1ec1c..14b2faaf6 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -34,6 +34,10 @@ #include "server/sparkd/user/AdminServiceServer.h" #include "server/sparkd/user/AuthServiceServer.h" #include "server/sparkd/algo/AlgoDefinitionServiceServer.h" + +#include "lib/orderman/orders/algo/algo_orders/ScratchAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/ProRataAlgo.h" + #include namespace bts { @@ -76,6 +80,57 @@ int Run::execute(std::vector const &) { SparkServices plugin_services(dyn_order_registry); plugin::init_plugins(plugin_services); // finished initializing order plugins + + //TODO these will go away once Haris approves algo + using namespace api::orderman; + { + DynamicOrderDescriptor desc; + desc.set_dynamic_order_type("Scratch"); + auto param = desc.add_param_desc(); + param->set_param_name("scratch_threshold"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); + + param = desc.add_param_desc(); + param->set_param_name("child"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); + plugin_services.register_dynamic_algo_order( + desc, []() { return std::make_unique(); }); + } + + { + DynamicOrderDescriptor desc; + desc.set_dynamic_order_type("ProRata"); + auto param = desc.add_param_desc(); + param->set_param_name("hedge_ticks"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); + param = desc.add_param_desc(); + param->set_param_name("fill_limit"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); + + param = desc.add_param_desc(); + param->set_param_name("stay_in_threshold"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); + param = desc.add_param_desc(); + param->set_param_name("enable_scratch_on_overfill"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_BOOL); + param = desc.add_param_desc(); + param->set_param_name("enable_stay_in"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_BOOL); + + param = desc.add_param_desc(); + param->set_param_name("child"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); + param = desc.add_param_desc(); + param->set_param_name("hedge"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); + param = desc.add_param_desc(); + param->set_param_name("overfill_hedge"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); + + + plugin_services.register_dynamic_algo_order( + desc, []() { return std::make_unique(); }); + } orderman::OrderServiceServer order_service_server( sc, mdclient, dyn_order_registry, stats, perf_log); From 117e1071162c8bfa23ff5a0155a8e4b97c122cca Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Fri, 24 May 2019 22:50:12 -0400 Subject: [PATCH 06/27] dynamics work again --- .../DynamicOrderTemplateSelector.cs | 2 ++ .../Orders/OrderTypeVMs/DynamicOrderVM.cs | 7 +++++-- .../Order/AlgoContentTemplateSelector.xaml | 21 +++++++++++++++++++ .../orders/algo/algo_orders/ScratchAlgo.cpp | 5 ++++- 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderTemplateSelector.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderTemplateSelector.cs index e09a3acab..cdf5a4906 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderTemplateSelector.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderTemplateSelector.cs @@ -19,6 +19,7 @@ namespace mbts.ui.spark public DataTemplate UIntTemplate { get; set; } public DataTemplate StringTemplate { get; set; } public DataTemplate OrderDefTemplate { get; set; } + public DataTemplate QuantityMeasureTemplate { get; set; } public DataTemplate EnumTemplate { get; set; } @@ -39,6 +40,7 @@ namespace mbts.ui.spark case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return UIntTemplate; case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return StringTemplate; case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef: return OrderDefTemplate; + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: return QuantityMeasureTemplate; default: return null; } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs index 848602c12..892e07fa0 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs @@ -47,10 +47,13 @@ namespace mbts.spark { protected override void on_model_internal() => _sync_dynamic_params(); - protected override IEnumerable get_selector_datum() => - OrderDataHelper.get_child_algo_data(new CustomOrderDefinition { + protected override IEnumerable get_selector_datum() + { + var data = OrderDataHelper.get_child_algo_data(new CustomOrderDefinition { Dynamic = model?.dynamic_helper?.create_def(dyn_type) ?? new DynamicOrderDefinition() }); + return data; + } void _sync_dynamic_params() { if (model != null) { diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index 6706baf48..96db2855a 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1094,6 +1094,27 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index ea3ad3744..fb6c7dc03 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -40,7 +40,10 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dscratch.order_params().count("scratch_threshold") > 0) *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); - *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); + if(dscratch.order_params().count("child") > 0) + *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); + else + scratch.mutable_child()->mutable_limit(); } } From 5f125790cf74164322dc31e6ce239e7c0c827bd2 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Sat, 25 May 2019 10:50:27 -0400 Subject: [PATCH 07/27] dynamics can now have QuantityMeasure --- .../Orders/OrderTypeVMs/DynamicOrderHelper.cs | 7 +---- .../OrderTypeVMs/DynamicOrderParamVM.cs | 28 ++++++++++--------- .../Orders/OrderTypeVMs/DynamicOrderVM.cs | 2 +- .../Order/AlgoContentTemplateSelector.xaml | 7 +++-- .../orders/algo/algo_orders/ProRataAlgo.cpp | 10 +++++-- .../orders/algo/algo_orders/ScratchAlgo.cpp | 7 ++++- 6 files changed, 36 insertions(+), 25 deletions(-) diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs index f08137c66..9bae979d3 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderHelper.cs @@ -96,13 +96,8 @@ namespace mbts.spark { internal static void set_quantity_value(DynamicOrderParam param, bts.spark.QuantityMeasureImmutable? value) { if (param == null) - { return; - } - else if (param.ValueCase != DynamicOrderParam.ValueOneofCase.AsQuantity) - { - param.AsQuantity = value?.CloneToMutable(); - } + param.AsQuantity = value?.CloneToMutable(); } } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs index def02cd07..80e0c6edb 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs @@ -122,36 +122,38 @@ namespace mbts.spark { class DynamicOrderQuantityVM : DynamicOrderParamVM, IDynamicOrderParamVM { static readonly FieldDescriptor _field_desc = DynamicOrderParam.Descriptor.FindFieldByNumber(DynamicOrderParam.AsQuantityFieldNumber); - QuantityMeasureImmutable? _value; public DynamicOrderQuantityVM(DynamicOrderParamDescriptor descriptor) : base(descriptor) { } - public QuantityMeasureImmutable? value + QuantityMeasureImmutable? IDynamicOrderParamVM.value { get => quantity; set => quantity= value; } + public QuantityMeasureImmutable? quantity { - get => _value; - set + get => DynamicOrderHelper.get_quantity_value(param); + set { - _value = value; - _field_desc.Accessor.SetValue(param, _value?.CloneToMutable()); - RaisePropertyChanged(); + var orig = quantity; + DynamicOrderHelper.set_quantity_value(param, value); + if (quantity != orig) + RaisePropertyChanged(); } - } + } - public IObservable subscribe_value() => - Observable.Create(o => + public IObservable subscribe_value() + { + return Observable.Create(o => { PropertyChanged += on_prop_changed; return Disposable.Create(() => PropertyChanged -= on_prop_changed); void on_prop_changed(object sender, PropertyChangedEventArgs e) => - o.OnNext(value); + o.OnNext(quantity); }); + } protected override void on_param_changed() { - _value = new QuantityMeasureImmutable( (QuantityMeasure) _field_desc.Accessor.GetValue(param)); - RaisePropertyChanged(nameof(value)); + RaisePropertyChanged(nameof(quantity)); } } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs index 892e07fa0..76af9879d 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs @@ -80,7 +80,7 @@ namespace mbts.spark { case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: { var qm = new DynamicOrderQuantityVM(descriptor); - return attached(qm, DynamicOrderHelper.get_quantity_value, DynamicOrderHelper.set_quantity_value, new QuantityMeasureImmutable(new QuantityMeasure { Ratio = 1.0, Absolute = 1 })); + return attached(qm, DynamicOrderHelper.get_quantity_value, DynamicOrderHelper.set_quantity_value, new QuantityMeasure { Ratio = 1.0, Absolute = 1 }); } default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.Primitive, nameof(descriptor)); } diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index 96db2855a..dc159595c 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1102,8 +1102,11 @@ - - + + diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 5ad8dfc96..49f973079 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -65,7 +65,12 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) auto& dprorata = def.custom_def().dynamic(); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); - + + std::string keys; + for(auto& pair : dprorata.order_params()) + { + keys += pair.first; + } if(dprorata.order_params().count("hedge_ticks") > 0) prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); if(dprorata.order_params().count("fill_limit") > 0) @@ -85,7 +90,8 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - auto &def = serv.definition(); + const api::orderman::OrderDefinition& def = serv.definition(); + check_dynamic(def); bts_assert(def.has_custom_def()); bts_assert(def.custom_def().has_prorata()); diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index fb6c7dc03..9adaaf79c 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -36,7 +36,12 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) auto& dscratch = def.custom_def().dynamic(); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); - + + std::string keys; + for(auto& pair : dscratch.order_params()) + { + keys += pair.first; + } if(dscratch.order_params().count("scratch_threshold") > 0) *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); From 6fc3c0b6016c2c862c6626fb992f6d7dbc22154a Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Sat, 25 May 2019 17:48:54 -0400 Subject: [PATCH 08/27] the bug turned out to be in my brain --- .../OrderTypeVMs/DynamicOrderParamVM.cs | 4 +--- .../orderman/orders/algo/AlgoWrapperOrder.cpp | 3 ++- .../orders/algo/algo_orders/ProRataAlgo.cpp | 20 +++++++++++++++---- .../orders/algo/algo_orders/ScratchAlgo.cpp | 5 +++-- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs index 80e0c6edb..d80ae2413 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs @@ -123,9 +123,7 @@ namespace mbts.spark { { static readonly FieldDescriptor _field_desc = DynamicOrderParam.Descriptor.FindFieldByNumber(DynamicOrderParam.AsQuantityFieldNumber); public DynamicOrderQuantityVM(DynamicOrderParamDescriptor descriptor) - : base(descriptor) - { - } + : base(descriptor) { } QuantityMeasureImmutable? IDynamicOrderParamVM.value { get => quantity; set => quantity= value; } public QuantityMeasureImmutable? quantity diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp index b14e7c7ef..f1c7dc58e 100644 --- a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp +++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp @@ -306,7 +306,8 @@ orderman::OrderOpResult AlgoWrapperOrder::on_cancel() { // IBeforeLaunchAlgoServices // -------------------------------------------------------------------------------- api::orderman::OrderDefinition const &AlgoWrapperOrder::definition() const { - return *def(); + //return *def(); + return me->definition; } api::Security const &AlgoWrapperOrder::security() const { diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 49f973079..6670084b0 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -62,7 +62,8 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) { if (def.has_custom_def() && def.custom_def().has_dynamic()) { - auto& dprorata = def.custom_def().dynamic(); + //copy + api::orderman::DynamicOrderDefinition dprorata = def.custom_def().dynamic(); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); @@ -82,9 +83,20 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dprorata.order_params().count("enable_stay_in") > 0) prorata.set_enable_stay_in(dprorata.order_params().at("enable_stay_in").as_bool()); - *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); - *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); - *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); + if(dprorata.order_params().count("child") > 0) + *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); + else + prorata.mutable_child()->mutable_limit(); + + if(dprorata.order_params().count("hedge") > 0) + *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); + else + prorata.mutable_hedge()->mutable_limit(); + + if(dprorata.order_params().count("overfill_hedge") > 0) + *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); + else + prorata.mutable_overfill_hedge()->mutable_limit(); } } diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 9adaaf79c..c3ab411c0 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -33,7 +33,8 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) { if (def.has_custom_def() && def.custom_def().has_dynamic()) { - auto& dscratch = def.custom_def().dynamic(); + //copy + api::orderman::DynamicOrderDefinition dscratch = def.custom_def().dynamic(); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); @@ -54,7 +55,7 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - const api::orderman::OrderDefinition& def = serv.definition(); + auto& def = serv.definition(); check_dynamic(def); bts_assert(def.has_custom_def()); bts_assert(def.custom_def().has_scratch()); From ea232fbaf1a637bb3bae645e85f0f1059dc44bcc Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Sat, 25 May 2019 23:27:54 -0400 Subject: [PATCH 09/27] ScratchAlgo works --- src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp | 3 +-- .../orders/algo/algo_orders/ProRataAlgo.cpp | 15 +++++++-------- .../orders/algo/algo_orders/ScratchAlgo.cpp | 15 +++++++++------ 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp index f1c7dc58e..b14e7c7ef 100644 --- a/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp +++ b/src/lib/orderman/orders/algo/AlgoWrapperOrder.cpp @@ -306,8 +306,7 @@ orderman::OrderOpResult AlgoWrapperOrder::on_cancel() { // IBeforeLaunchAlgoServices // -------------------------------------------------------------------------------- api::orderman::OrderDefinition const &AlgoWrapperOrder::definition() const { - //return *def(); - return me->definition; + return *def(); } api::Security const &AlgoWrapperOrder::security() const { diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 6670084b0..c72a97ff0 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -63,7 +63,8 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if (def.has_custom_def() && def.custom_def().has_dynamic()) { //copy - api::orderman::DynamicOrderDefinition dprorata = def.custom_def().dynamic(); + api::orderman::DynamicOrderDefinition dprorata; + dprorata.CopyFrom(def.custom_def().dynamic()); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); @@ -200,14 +201,12 @@ void ProRataAlgo::check_overfill() { auto my_side = algo().definition().side(); auto other_side = securities::other_side(my_side); - - Quantity my_quan; - bool found = SpreaderUtils::find_qty_upto_price_level(me->last_book, my_side, algo().price(), /*unused*/ 0.0, my_quan); - auto &my_side_psz = me->last_book.side(my_side)[0]; + + auto &my_side_psz = me->last_book.side(my_side)[0]; auto &other_side_psz = me->last_book.side(other_side)[0]; - bool market_moved = other_side_psz.price() != my_side_psz.price(); - - if (market_moved || !found || (found && my_quan.value() <= me->stay_in_threshold.value()) ) + bool market_moved = !securities::is_same(Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); + bool on_market = securities::is_same(Price(my_side_psz.price()), Price(algo().price())); + if (market_moved || (on_market && my_side_psz.size() <= me->stay_in_threshold.value()) ) get_out(); } else diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index c3ab411c0..1e015968d 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -22,6 +22,7 @@ struct ScratchAlgo::PImpl ChildTemplate *child_template = nullptr; Book last_book; Book book_at_inception; + Quantity total_fills = Quantity(0); Price scratch_price=Price(os::nan()); }; @@ -33,8 +34,10 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) { if (def.has_custom_def() && def.custom_def().has_dynamic()) { + //copy - api::orderman::DynamicOrderDefinition dscratch = def.custom_def().dynamic(); + api::orderman::DynamicOrderDefinition dscratch; + dscratch.CopyFrom(def.custom_def().dynamic()); auto& mutable_def = const_cast(def); //TODO Terrible hack auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); @@ -164,12 +167,11 @@ void ScratchAlgo::try_to_scratch() auto other_side = securities::other_side(my_side); Quantity my_quan; - bool found = SpreaderUtils::find_qty_upto_price_level(me->last_book, my_side, algo().price(), /*unused*/ 0.0, my_quan); auto &my_side_psz = me->last_book.side(my_side)[0]; auto &other_side_psz = me->last_book.side(other_side)[0]; - bool market_moved = other_side_psz.price() != my_side_psz.price(); - - if (market_moved || !found || (found && my_quan.value() <= me->scratch_threshold.value()) ) + bool market_moved = !securities::is_same(Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); + bool on_market = securities::is_same(Price(my_side_psz.price()), Price(algo().price())); + if (market_moved || (on_market && my_side_psz.size() <= me->scratch_threshold.value()) ) { Price scratch_price; Quantity scratch_quan; @@ -182,7 +184,7 @@ void ScratchAlgo::try_to_scratch() me->scratch_price = scratch_price; child_update.set_price(scratch_price.value()); //we still want to try to scratch all of it - child_update.set_quantity(algo().quantity().value()); + child_update.set_quantity(algo().quantity().value() - me->total_fills.value()); algo().update_child(me->child_key, child_update); me->status = Status::SCRATCHED; } @@ -222,6 +224,7 @@ void ScratchAlgo::update_scratch_threshold() void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) { algo().update_fill_state(st.total_fills, st.last_price); + me->total_fills = st.total_fills; switch (st.status) { case ChildStatus::WORKING: From e19bb7c6218f9132dd8b27b9ef18b4297b77dd43 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Sat, 25 May 2019 23:45:17 -0400 Subject: [PATCH 10/27] chase if worse --- src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 1e015968d..86d064979 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -169,7 +169,8 @@ void ScratchAlgo::try_to_scratch() Quantity my_quan; auto &my_side_psz = me->last_book.side(my_side)[0]; auto &other_side_psz = me->last_book.side(other_side)[0]; - bool market_moved = !securities::is_same(Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); + bool market_moved = !securities::is_equal_or_better(other_side, + Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); bool on_market = securities::is_same(Price(my_side_psz.price()), Price(algo().price())); if (market_moved || (on_market && my_side_psz.size() <= me->scratch_threshold.value()) ) { From 729986d53d710932acec8c86f465d5619f4d79de Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Sun, 26 May 2019 23:30:55 -0400 Subject: [PATCH 11/27] need to test get_out function --- .../orders/algo/algo_orders/ProRataAlgo.cpp | 149 +++++++++++------- .../orders/algo/algo_orders/ProRataAlgo.h | 5 +- .../orders/algo/algo_orders/ScratchAlgo.cpp | 9 +- 3 files changed, 100 insertions(+), 63 deletions(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index c72a97ff0..20d489edc 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -11,7 +11,7 @@ namespace orderman { using namespace api::orderman; -enum class ProRataAlgo::Status { WAITING_FOR_MD, WORKING, DONE }; //this is for the child +enum class ProRataAlgo::Status { WAITING_FOR_MD, WORKING, DONE_WORKING, GETTING_OUT }; //this is for the child const char *ProRataAlgo::status_name(Status st) { switch (st) @@ -20,8 +20,10 @@ const char *ProRataAlgo::status_name(Status st) return "WAITING_FOR_MD"; case Status::WORKING: return "WORKING"; - case Status::DONE: - return "DONE"; + case Status::DONE_WORKING: + return "DONE_WORKING"; + case Status::GETTING_OUT: + return "GETTING_OUT"; } return nullptr; } @@ -47,7 +49,7 @@ struct ProRataAlgo::PImpl Quantity hedged_fills = Quantity(0); Status status = Status::WAITING_FOR_MD; std::vector hedges; - std::vector overfill_hedges; + std::map overfill_hedges; Book last_book; Book book_at_inception; @@ -68,11 +70,6 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) auto& mutable_def = const_cast(def); //TODO Terrible hack auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); - std::string keys; - for(auto& pair : dprorata.order_params()) - { - keys += pair.first; - } if(dprorata.order_params().count("hedge_ticks") > 0) prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); if(dprorata.order_params().count("fill_limit") > 0) @@ -127,15 +124,15 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) me->child_template = &(serv.make_child_template(child_def)); } - init_hedge_template(serv, prorata.hedge()); - init_hedge_template(serv, prorata.overfill_hedge()); - set_parameters(serv, prorata); + init_hedge_template(serv, prorata.hedge(), false); + init_hedge_template(serv, prorata.overfill_hedge(), true); return {}; } void ProRataAlgo::do_launch(IAlgoServices &algo) { me->algo = &algo; + set_parameters(algo, algo.definition().custom_def().prorata()); LOG(OrderMan, Diag, "Starting ProRataAlgo {}, {} {}@{}. Will cover {} ticks", algo.order_key().value(), securities::side_name(algo.definition().side()), algo.quantity().value(), @@ -150,6 +147,7 @@ void ProRataAlgo::do_launch(IAlgoServices &algo) void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st) { me->algo = &algo; + set_parameters(algo, algo.definition().custom_def().prorata()); me->child_key = k; me->hedged_fills = st.total_fills; algo.subscribe_book(SecurityKey(algo.security().id())); @@ -187,15 +185,17 @@ void ProRataAlgo::on_book(SecurityKey, const Book& b) case Status::WORKING: check_overfill(); break; - case Status::DONE: + case Status::DONE_WORKING: check_overfill(); break; + case Status::GETTING_OUT: + break; } } void ProRataAlgo::check_overfill() { - if(me->is_overfilled) + if(me->is_overfilled && me->status != Status::GETTING_OUT) { if(me->enable_stay_in) { @@ -204,8 +204,10 @@ void ProRataAlgo::check_overfill() auto &my_side_psz = me->last_book.side(my_side)[0]; auto &other_side_psz = me->last_book.side(other_side)[0]; - bool market_moved = !securities::is_same(Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); + bool market_moved = !securities::is_equal_or_better(other_side, + Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); bool on_market = securities::is_same(Price(my_side_psz.price()), Price(algo().price())); + if (market_moved || (on_market && my_side_psz.size() <= me->stay_in_threshold.value()) ) get_out(); } @@ -214,14 +216,59 @@ void ProRataAlgo::check_overfill() } } +void ProRataAlgo::scratch(std::pair kk) +{ + auto other_side = securities::other_side(algo().definition().side()); + Price scratch_price; + Quantity scratch_quan; + SpreaderUtils::traverse_depth_for_quantity(me->last_book, other_side, kk.second, scratch_price, scratch_quan); + + Update update; + update.set_price(scratch_price.value()); + //we still want to try to scratch all of it + update.set_quantity(kk.second.value()); + algo().update_child(kk.first, update); +} + void ProRataAlgo::get_out() { - if(me->enable_scratch_on_overfill) - { - //scratch all my overs TODO - me->enable_scratch_on_overfill = false; + if(me->status != Status::GETTING_OUT) + { + me->status = Status::GETTING_OUT; + if(me->enable_scratch_on_overfill) + { + for(auto& h : me->overfill_hedges) + scratch(h); + } + algo().cancel_child(me->child_key); + check_terminate(); } - algo().cancel_child(me->child_key); +} + +void ProRataAlgo::standard_hedge(Price hedge_price, Quantity hedge_qty) +{ + auto hedge = algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); + me->hedges.push_back(hedge); + LOG(OrderMan, Diag, + "ProRataAlgo {}, launched new hedge in response to child fill. " + "Hedge: {} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); +} + +void ProRataAlgo::overfill_hedge(Price hedge_price, Quantity hedge_qty) +{ + auto hedge = algo().launch_child(*me->overfill_hedge_template, hedge_price, hedge_qty); + me->overfill_hedges[hedge] = hedge_qty; + LOG(OrderMan, Diag, + "ProRataAlgo {}, launched new OVERFILL hedge in response to child fill. " + "Hedge: {} {}@{}", + algo().order_key().value(), + securities::side_name(algo().definition().side()), + hedge_qty.value(), hedge_price.value()); + me->is_overfilled = true; + check_overfill(); } void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) @@ -230,33 +277,22 @@ void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) { if (st.total_fills.value() > me->hedged_fills.value()) { - auto hedge_qty = Quantity(st.total_fills.value() - me->hedged_fills.value()); - me->hedged_fills = Quantity(hedge_qty.value() + me->hedged_fills.value()); + auto hedge_qty = Quantity(st.total_fills.value() - me->hedged_fills.value()); auto hedge_price = securities::improve_price(algo().definition().side(), st.last_price, me->hedge_price_diff); - if(me->hedged_fills < me->fill_limit) - { - auto hedge = algo().launch_child(*me->hedge_template, hedge_price, hedge_qty); - me->hedges.push_back(hedge); - LOG(OrderMan, Diag, - "ProRataAlgo {}, launched new hedge in response to child fill. " - "Hedge: {} {}@{}", - algo().order_key().value(), - securities::side_name(algo().definition().side()), - hedge_qty.value(), hedge_price.value()); - } + if( me->hedged_fills.value() + hedge_qty.value() <= me->fill_limit.value() ) + standard_hedge(hedge_price, hedge_qty); else { - auto hedge = algo().launch_child(*me->overfill_hedge_template, hedge_price, hedge_qty); - me->overfill_hedges.push_back(hedge); - LOG(OrderMan, Diag, - "ProRataAlgo {}, launched new OVERFILL hedge in response to child fill. " - "Hedge: {} {}@{}", - algo().order_key().value(), - securities::side_name(algo().definition().side()), - hedge_qty.value(), hedge_price.value()); - me->is_overfilled = true; - check_overfill(); + auto over = me->hedged_fills.value() + hedge_qty.value() - me->fill_limit.value(); + if(over < hedge_qty.value()) + { + standard_hedge(hedge_price, Quantity(hedge_qty.value() - over)); + overfill_hedge(hedge_price, Quantity(over)); + } + else + overfill_hedge(hedge_price, hedge_qty); } + me->hedged_fills = Quantity(hedge_qty.value() + me->hedged_fills.value()); } algo().update_fill_state(st.total_fills, st.last_price); switch (st.status) @@ -265,11 +301,11 @@ void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) break; case ChildStatus::COMPLETED: LOG(OrderMan, Info, "ProRataAlgo {}. Child is completed, waiting for hedges ", algo().order_key().value()); - me->status = Status::DONE; + me->status = Status::DONE_WORKING; break; case ChildStatus::CANCELED: LOG(OrderMan, Info, "ProRataAlgo {}. Child was canceled, waiting on hedges", algo().order_key().value()); - me->status = Status::DONE; + me->status = Status::DONE_WORKING; break; } } @@ -283,8 +319,8 @@ void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) case ChildStatus::COMPLETED: if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k); it != me->hedges.end()) me->hedges.erase(it); - if (auto oit = std::find(me->overfill_hedges.begin(), me->overfill_hedges.end(), k); oit != me->overfill_hedges.end()) - me->overfill_hedges.erase(oit); + if(me->overfill_hedges.find(k) != me->overfill_hedges.end()) + me->overfill_hedges.erase(k); break; } } @@ -293,7 +329,7 @@ void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) void ProRataAlgo::do_update(const api::orderman::Update& update) { - if (me->status != Status::DONE) + if (me->status != Status::DONE_WORKING) { LOG(OrderMan, Diag, "ProRataAlgo order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); @@ -317,9 +353,9 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) if(prorata_update.has_child()) *child_update.mutable_custom() = prorata_update.child(); if(prorata_update.has_hedge()) - init_hedge_template(algo(), prorata_update.hedge()); + init_hedge_template(algo(), prorata_update.hedge(), false); if(prorata_update.has_overfill_hedge()) - init_hedge_template(algo(), prorata_update.overfill_hedge()); + init_hedge_template(algo(), prorata_update.overfill_hedge(), true); } algo().update_child(me->child_key, child_update); } @@ -332,14 +368,19 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) } void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, - const api::orderman::CustomOrderDefinition& hedge_cdef) + const api::orderman::CustomOrderDefinition& hedge_cdef, bool overfill) { - auto hedge_def = algo.definition(); + api::orderman::OrderDefinition hedge_def; + hedge_def.CopyFrom(algo.definition()); + hedge_def.set_side(securities::other_side(algo.definition().side())); hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); hedge_def.clear_attach_target_order_key(); *hedge_def.mutable_custom_def() = hedge_cdef; - me->hedge_template = &(algo.make_child_template(hedge_def)); + if(!overfill) + me->hedge_template = &(algo.make_child_template(hedge_def)); + else + me->overfill_hedge_template = &(algo.make_child_template(hedge_def)); } void ProRataAlgo::set_parameters(IBeforeLaunchAlgoServices &serv, const api::orderman::ProRataOrderDefinition& prorata) @@ -359,7 +400,7 @@ void ProRataAlgo::check_terminate() "ProRataAlgo {} check_terminate. State: {} Hedge count: {}", algo().order_key(), log::CharPtrWrapper{status_name(me->status)}, me->hedges.size()); - if (me->status == Status::DONE && me->hedges.empty() && me->overfill_hedges.empty()) + if (me->status == Status::DONE_WORKING && me->hedges.empty() && me->overfill_hedges.empty()) { LOG(OrderMan, Info, "ProRataAlgo {}. Last hedge completed, terminating", algo().order_key().value()); algo().complete(); diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index f4c19960a..07ffc294c 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -27,8 +27,11 @@ private: std::unique_ptr me; IAlgoServices &algo() const; void set_parameters(IBeforeLaunchAlgoServices &, const api::orderman::ProRataOrderDefinition&); - void init_hedge_template(IBeforeLaunchAlgoServices &, const api::orderman::CustomOrderDefinition&); + void init_hedge_template(IBeforeLaunchAlgoServices &, const api::orderman::CustomOrderDefinition&, bool); + void scratch(std::pair kk); void get_out(); + void standard_hedge(Price hedge_price, Quantity hedge_qty); + void overfill_hedge(Price hedge_price, Quantity hedge_qty); void check_overfill(); void check_terminate(); const char *status_name(Status st); diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 86d064979..e63254a9f 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -22,7 +22,6 @@ struct ScratchAlgo::PImpl ChildTemplate *child_template = nullptr; Book last_book; Book book_at_inception; - Quantity total_fills = Quantity(0); Price scratch_price=Price(os::nan()); }; @@ -41,11 +40,6 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) auto& mutable_def = const_cast(def); //TODO Terrible hack auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); - std::string keys; - for(auto& pair : dscratch.order_params()) - { - keys += pair.first; - } if(dscratch.order_params().count("scratch_threshold") > 0) *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); @@ -185,7 +179,7 @@ void ScratchAlgo::try_to_scratch() me->scratch_price = scratch_price; child_update.set_price(scratch_price.value()); //we still want to try to scratch all of it - child_update.set_quantity(algo().quantity().value() - me->total_fills.value()); + child_update.set_quantity(algo().quantity().value()); algo().update_child(me->child_key, child_update); me->status = Status::SCRATCHED; } @@ -225,7 +219,6 @@ void ScratchAlgo::update_scratch_threshold() void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) { algo().update_fill_state(st.total_fills, st.last_price); - me->total_fills = st.total_fills; switch (st.status) { case ChildStatus::WORKING: From 0a33fb37b90e1ca72ca38d471bf319714eeb8994 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Mon, 27 May 2019 22:53:56 -0400 Subject: [PATCH 12/27] rata looking good --- src/lib/api/services/OrderService.proto | 10 ++++++---- .../orders/algo/algo_orders/ProRataAlgo.cpp | 20 ++++++++++++------- .../orders/algo/algo_orders/ScratchAlgo.cpp | 5 +++++ src/server/sparkd/cmds/Run.cpp | 7 +++++++ 4 files changed, 31 insertions(+), 11 deletions(-) diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index f90925449..35d385b16 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -201,14 +201,16 @@ message CompositeOrderDefinition { } message ScratchOrderDefinition { spark.QuantityMeasure scratch_threshold = 1; + uint32 chase_ticks = 2; CustomOrderDefinition child = 10; } message ProRataOrderDefinition { uint32 hedge_ticks = 1; - spark.QuantityMeasure fill_limit = 2; - spark.QuantityMeasure stay_in_threshold = 4; - bool enable_scratch_on_overfill = 5; - bool enable_stay_in = 6; + uint32 chase_ticks = 2; + spark.QuantityMeasure fill_limit = 5; + spark.QuantityMeasure stay_in_threshold = 6; + bool enable_scratch_on_overfill = 7; + bool enable_stay_in = 8; CustomOrderDefinition child = 10; CustomOrderDefinition hedge = 20; diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 20d489edc..6e109135b 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -37,10 +37,11 @@ struct ProRataAlgo::PImpl OrderKey child_key = null_order_key(); Price hedge_price_diff; + Price chase_diff; Quantity fill_limit; Quantity stay_in_threshold; bool enable_scratch_on_overfill; - bool enable_stay_in; + bool enable_stay_in; ChildTemplate *child_template = nullptr; ChildTemplate *hedge_template = nullptr; @@ -72,6 +73,10 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dprorata.order_params().count("hedge_ticks") > 0) prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); + prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); + if(dprorata.order_params().count("chase_ticks") > 0) + prorata.set_chase_ticks(dprorata.order_params().at("chase_ticks").as_uint32()); + if(dprorata.order_params().count("fill_limit") > 0) *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); if(dprorata.order_params().count("stay_in_threshold") > 0) @@ -218,14 +223,14 @@ void ProRataAlgo::check_overfill() void ProRataAlgo::scratch(std::pair kk) { - auto other_side = securities::other_side(algo().definition().side()); + auto cross_side = algo().definition().side(); Price scratch_price; Quantity scratch_quan; - SpreaderUtils::traverse_depth_for_quantity(me->last_book, other_side, kk.second, scratch_price, scratch_quan); + SpreaderUtils::traverse_depth_for_quantity(me->last_book, cross_side, kk.second, scratch_price, scratch_quan); + scratch_price = securities::worsen_price(cross_side, scratch_price, me->chase_diff); Update update; update.set_price(scratch_price.value()); - //we still want to try to scratch all of it update.set_quantity(kk.second.value()); algo().update_child(kk.first, update); } @@ -235,12 +240,12 @@ void ProRataAlgo::get_out() if(me->status != Status::GETTING_OUT) { me->status = Status::GETTING_OUT; + algo().cancel_child(me->child_key); if(me->enable_scratch_on_overfill) { for(auto& h : me->overfill_hedges) scratch(h); - } - algo().cancel_child(me->child_key); + } check_terminate(); } } @@ -275,7 +280,7 @@ void ProRataAlgo::on_child_change(OrderKey k, const ChildState& st) { if (k == me->child_key) { - if (st.total_fills.value() > me->hedged_fills.value()) + if (st.total_fills.value() > me->hedged_fills.value() && me->status == Status::WORKING) { auto hedge_qty = Quantity(st.total_fills.value() - me->hedged_fills.value()); auto hedge_price = securities::improve_price(algo().definition().side(), st.last_price, me->hedge_price_diff); @@ -386,6 +391,7 @@ void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, void ProRataAlgo::set_parameters(IBeforeLaunchAlgoServices &serv, const api::orderman::ProRataOrderDefinition& prorata) { me->hedge_price_diff = Price(securities::tick_size(serv.security()).value() * prorata.hedge_ticks()); + me->chase_diff = Price(securities::tick_size(serv.security()).value() * prorata.chase_ticks()); if(prorata.has_fill_limit()) me->fill_limit = SpreaderUtils::_quantity_threshold(prorata.fill_limit(), algo().quantity()); if(prorata.has_stay_in_threshold()) diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index e63254a9f..5cd57bf4a 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -17,6 +17,7 @@ struct ScratchAlgo::PImpl { IAlgoServices *algo; Quantity scratch_threshold; + Price chase_diff; Status status = Status::WAITING_FOR_MD; OrderKey child_key = null_order_key(); ChildTemplate *child_template = nullptr; @@ -42,6 +43,8 @@ void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dscratch.order_params().count("scratch_threshold") > 0) *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); + if(dscratch.order_params().count("chase_ticks") > 0) + scratch.set_chase_ticks(dscratch.order_params().at("chase_ticks").as_uint32()); if(dscratch.order_params().count("child") > 0) *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); @@ -214,6 +217,8 @@ void ScratchAlgo::update_scratch_threshold() { me->scratch_threshold = SpreaderUtils::_quantity_threshold( algo().definition().custom_def().scratch().scratch_threshold(), algo().quantity()); + me->chase_diff = Price(securities::tick_size( + algo().security()).value() * algo().definition().custom_def().scratch().chase_ticks()); } void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 14b2faaf6..299e53901 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -89,6 +89,9 @@ int Run::execute(std::vector const &) { auto param = desc.add_param_desc(); param->set_param_name("scratch_threshold"); param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); + param = desc.add_param_desc(); + param->set_param_name("chase_ticks"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); param = desc.add_param_desc(); param->set_param_name("child"); @@ -103,6 +106,10 @@ int Run::execute(std::vector const &) { auto param = desc.add_param_desc(); param->set_param_name("hedge_ticks"); param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); + param = desc.add_param_desc(); + param->set_param_name("chase_ticks"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); + param = desc.add_param_desc(); param->set_param_name("fill_limit"); param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); From 91989e6bafcede628b0ef3da821c6bff5ef3931b Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 10:19:31 -0400 Subject: [PATCH 13/27] Quantity measure validation --- .../orders/algo/algo_orders/ProRataAlgo.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 6e109135b..b177fd227 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -73,14 +73,25 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dprorata.order_params().count("hedge_ticks") > 0) prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); - prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); + prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); + if(dprorata.order_params().count("chase_ticks") > 0) prorata.set_chase_ticks(dprorata.order_params().at("chase_ticks").as_uint32()); if(dprorata.order_params().count("fill_limit") > 0) *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); + if(!prorata.has_fill_limit() || + prorata.fill_limit().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + prorata.mutable_fill_limit()->set_absolute(1u); + + if(dprorata.order_params().count("stay_in_threshold") > 0) - *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); + *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); + if(!prorata.has_stay_in_threshold() || + prorata.stay_in_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + prorata.mutable_stay_in_threshold()->set_absolute(1u); + + if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); if(dprorata.order_params().count("enable_stay_in") > 0) @@ -131,6 +142,7 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) init_hedge_template(serv, prorata.hedge(), false); init_hedge_template(serv, prorata.overfill_hedge(), true); + return {}; } From e8bc07360db095887ad89f2b77e72780b7310a00 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 13:52:18 -0400 Subject: [PATCH 14/27] got the dynamism and updates working --- src/lib/orderman/orders/algo/DynamicHelpers.h | 40 ++++++++++++ .../orders/algo/algo_orders/ScratchAlgo.cpp | 65 +++++++++++-------- .../orders/algo/algo_orders/ScratchAlgo.h | 7 +- 3 files changed, 83 insertions(+), 29 deletions(-) create mode 100644 src/lib/orderman/orders/algo/DynamicHelpers.h diff --git a/src/lib/orderman/orders/algo/DynamicHelpers.h b/src/lib/orderman/orders/algo/DynamicHelpers.h new file mode 100644 index 000000000..99261d06d --- /dev/null +++ b/src/lib/orderman/orders/algo/DynamicHelpers.h @@ -0,0 +1,40 @@ +#pragma once + +#include "lib/api/services/OrderService.pb.h" + +namespace bts { +namespace orderman { + +template +bool has_custom(const T& orig) +{ + return orig.has_custom_def(); +} +template<> +bool has_custom(const api::orderman::Update& orig) +{ + return orig.has_custom(); +} +template +const api::orderman::CustomOrderDefinition& custom(const T& orig) +{ + return orig.custom_def(); +} +template<> +const api::orderman::CustomOrderDefinition& custom(const api::orderman::Update& orig) +{ + return orig.custom(); +} +template +api::orderman::CustomOrderDefinition& mutable_custom(T& orig) +{ + return *orig.mutable_custom_def(); +} +template<> +api::orderman::CustomOrderDefinition& mutable_custom(api::orderman::Update& orig) +{ + return *orig.mutable_custom(); +} + + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 5cd57bf4a..49a4e61b3 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -1,5 +1,6 @@ #include "lib/orderman/orders/algo/algo_orders/ScratchAlgo.h" #include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/algo/DynamicHelpers.h" #include "lib/orderman/order_factory/IOrderFactory.h" #include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" @@ -16,6 +17,8 @@ enum class ScratchAlgo::Status { WAITING_FOR_MD, WAITING_TO_SCRATCH, SCRATCHED } struct ScratchAlgo::PImpl { IAlgoServices *algo; + OrderDefinition definition; + Quantity scratch_threshold; Price chase_diff; Status status = Status::WAITING_FOR_MD; @@ -29,39 +32,40 @@ struct ScratchAlgo::PImpl ScratchAlgo::ScratchAlgo() : me(new PImpl()) {} ScratchAlgo::~ScratchAlgo() {} IAlgoServices &ScratchAlgo::algo() const { return *me->algo; } +const OrderDefinition& ScratchAlgo::definition() const { return me->definition; } -void ScratchAlgo::check_dynamic(const api::orderman::OrderDefinition& def) +template +T convert_from_dynamic(const T& orig) { - if (def.has_custom_def() && def.custom_def().has_dynamic()) - { - - //copy - api::orderman::DynamicOrderDefinition dscratch; - dscratch.CopyFrom(def.custom_def().dynamic()); - auto& mutable_def = const_cast(def); //TODO Terrible hack - auto& scratch = *mutable_def.mutable_custom_def()->mutable_scratch(); + T newt = orig; + if ( has_custom(orig) && custom(orig).has_dynamic()) + { + const DynamicOrderDefinition& dscratch = custom(orig).dynamic(); + auto& scratch = *mutable_custom(newt).mutable_scratch(); if(dscratch.order_params().count("scratch_threshold") > 0) *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); + if(dscratch.order_params().count("chase_ticks") > 0) scratch.set_chase_ticks(dscratch.order_params().at("chase_ticks").as_uint32()); if(dscratch.order_params().count("child") > 0) *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); else - scratch.mutable_child()->mutable_limit(); - } + scratch.mutable_child()->mutable_limit(); + } + return newt; } OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - auto& def = serv.definition(); - check_dynamic(def); - bts_assert(def.has_custom_def()); - bts_assert(def.custom_def().has_scratch()); + me->definition = convert_from_dynamic(serv.definition()); + + bts_assert(definition().has_custom_def()); + bts_assert(definition().custom_def().has_scratch()); // Validate the scratch part of the definition - auto &scratch = def.custom_def().scratch(); - if (!scratch.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) + auto &scratch = definition().custom_def().scratch(); + if (!scratch.has_child() && OrderKey(definition().attach_target_order_key()) == null_order_key()) { return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, "Scratch order must have either a child order definition or an order to attach to"}; @@ -70,8 +74,8 @@ OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { // if we are not attaching create a child template so we can // quickly launch our child when the time comes. - auto child_def = def; - *child_def.mutable_custom_def() = def.custom_def().scratch().child(); + auto child_def = definition(); + *child_def.mutable_custom_def() = definition().custom_def().scratch().child(); me->child_template = &(serv.make_child_template(child_def)); } return {}; @@ -96,9 +100,13 @@ void ScratchAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState } void ScratchAlgo::do_update(api::orderman::Update const &update) -{ +{ LOG(OrderMan, Diag, "ScratchOrder order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); - if (update.has_custom() && !update.custom().has_scratch()) + + Update converted_update = convert_from_dynamic(update); + me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); + + if (update.has_custom() && !converted_update.custom().has_scratch()) { algo().terminate_error("Invalid update"); return; @@ -111,7 +119,7 @@ void ScratchAlgo::do_update(api::orderman::Update const &update) if (update.has_custom()) { update_scratch_threshold(); - auto &scratch_update = update.custom().scratch(); + auto &scratch_update = converted_update.custom().scratch(); *child_update.mutable_custom() = scratch_update.child(); } algo().update_child(me->child_key, child_update); @@ -135,7 +143,7 @@ void ScratchAlgo::on_book(SecurityKey, Book const &b) { case Status::WAITING_FOR_MD: { - auto other_side = securities::other_side(algo().definition().side()); + auto other_side = securities::other_side(definition().side()); auto &other_side_top = me->last_book.side(other_side)[0]; if (other_side_top.size() > 0) @@ -160,7 +168,7 @@ void ScratchAlgo::on_book(SecurityKey, Book const &b) void ScratchAlgo::try_to_scratch() { bts_assert(me->status == Status::WAITING_TO_SCRATCH); - auto my_side = algo().definition().side(); + auto my_side = definition().side(); auto other_side = securities::other_side(my_side); Quantity my_quan; @@ -215,10 +223,15 @@ Price ScratchAlgo::get_price_to_pass (Price price) const void ScratchAlgo::update_scratch_threshold() { + if (definition().custom_def().scratch().scratch_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + { + algo().terminate_error("Invalid quantity, terminating"); + return; + } me->scratch_threshold = SpreaderUtils::_quantity_threshold( - algo().definition().custom_def().scratch().scratch_threshold(), algo().quantity()); + definition().custom_def().scratch().scratch_threshold(), algo().quantity()); me->chase_diff = Price(securities::tick_size( - algo().security()).value() * algo().definition().custom_def().scratch().chase_ticks()); + algo().security()).value() * definition().custom_def().scratch().chase_ticks()); } void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h index 76c220a80..11640bdca 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h @@ -25,12 +25,13 @@ private: enum class Status; struct PImpl; std::unique_ptr me; - - IAlgoServices &algo() const ; + + const api::orderman::OrderDefinition& definition() const; + IAlgoServices& algo() const; + void update_scratch_threshold(); void try_to_scratch(); Price get_price_to_pass (Price price) const; - void check_dynamic(const api::orderman::OrderDefinition&); }; }} From 938a572a54f54a571535a764f89fd2f78e7b9e8a Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 14:14:16 -0400 Subject: [PATCH 15/27] rethinking the dynamictype -> native type for sake of gui going to make a new type of DefaultOrderVM that uses reflection instead of converting dynamic -> native in the orderman --- .../orderman/orders/algo/DynamicHelpers.cpp | 25 ++++++++ src/lib/orderman/orders/algo/DynamicHelpers.h | 17 ++---- .../orders/algo/algo_orders/ProRataAlgo.cpp | 60 ++++++++++--------- .../orders/algo/algo_orders/ProRataAlgo.h | 2 +- .../orders/algo/algo_orders/ScratchAlgo.cpp | 3 +- 5 files changed, 64 insertions(+), 43 deletions(-) create mode 100644 src/lib/orderman/orders/algo/DynamicHelpers.cpp diff --git a/src/lib/orderman/orders/algo/DynamicHelpers.cpp b/src/lib/orderman/orders/algo/DynamicHelpers.cpp new file mode 100644 index 000000000..6d347c867 --- /dev/null +++ b/src/lib/orderman/orders/algo/DynamicHelpers.cpp @@ -0,0 +1,25 @@ +#include "DynamicHelpers.h" + +namespace bts { +namespace orderman { + +template<> +bool has_custom(const api::orderman::Update& orig) +{ + return orig.has_custom(); +} + +template<> +const api::orderman::CustomOrderDefinition& custom(const api::orderman::Update& orig) +{ + return orig.custom(); +} + +template<> +api::orderman::CustomOrderDefinition& mutable_custom(api::orderman::Update& orig) +{ + return *orig.mutable_custom(); +} + + +}} \ No newline at end of file diff --git a/src/lib/orderman/orders/algo/DynamicHelpers.h b/src/lib/orderman/orders/algo/DynamicHelpers.h index 99261d06d..53488ba33 100644 --- a/src/lib/orderman/orders/algo/DynamicHelpers.h +++ b/src/lib/orderman/orders/algo/DynamicHelpers.h @@ -11,30 +11,23 @@ bool has_custom(const T& orig) return orig.has_custom_def(); } template<> -bool has_custom(const api::orderman::Update& orig) -{ - return orig.has_custom(); -} +bool has_custom(const api::orderman::Update& orig); + template const api::orderman::CustomOrderDefinition& custom(const T& orig) { return orig.custom_def(); } template<> -const api::orderman::CustomOrderDefinition& custom(const api::orderman::Update& orig) -{ - return orig.custom(); -} +const api::orderman::CustomOrderDefinition& custom(const api::orderman::Update& orig); + template api::orderman::CustomOrderDefinition& mutable_custom(T& orig) { return *orig.mutable_custom_def(); } template<> -api::orderman::CustomOrderDefinition& mutable_custom(api::orderman::Update& orig) -{ - return *orig.mutable_custom(); -} +api::orderman::CustomOrderDefinition& mutable_custom(api::orderman::Update& orig); }} \ No newline at end of file diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index b177fd227..f9a30826a 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -3,6 +3,8 @@ #include "lib/domain_model/Security.h" #include "lib/orderman/order_factory/IOrderFactory.h" #include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/algo/DynamicHelpers.h" + #include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" #include "lib/utils/PBUtils.h" @@ -34,6 +36,8 @@ struct ProRataAlgo::PImpl { } IAlgoServices *algo; + OrderDefinition definition; + OrderKey child_key = null_order_key(); Price hedge_price_diff; @@ -60,16 +64,16 @@ struct ProRataAlgo::PImpl ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} ProRataAlgo::~ProRataAlgo() {} IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } +const OrderDefinition& ProRataAlgo::definition() const { return me->definition; } -void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) +template +T convert_from_dynamic(const T& orig) { - if (def.has_custom_def() && def.custom_def().has_dynamic()) - { - //copy - api::orderman::DynamicOrderDefinition dprorata; - dprorata.CopyFrom(def.custom_def().dynamic()); - auto& mutable_def = const_cast(def); //TODO Terrible hack - auto& prorata = *mutable_def.mutable_custom_def()->mutable_prorata(); + T newt = orig; + if(has_custom(orig) && custom(orig).has_dynamic()) + { + const DynamicOrderDefinition& dprorata = custom(orig).dynamic(); + auto& prorata = *mutable_custom(newt).mutable_prorata(); if(dprorata.order_params().count("hedge_ticks") > 0) prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); @@ -83,14 +87,12 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(!prorata.has_fill_limit() || prorata.fill_limit().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) prorata.mutable_fill_limit()->set_absolute(1u); - - + if(dprorata.order_params().count("stay_in_threshold") > 0) *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); if(!prorata.has_stay_in_threshold() || prorata.stay_in_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) prorata.mutable_stay_in_threshold()->set_absolute(1u); - if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); @@ -110,19 +112,20 @@ void ProRataAlgo::check_dynamic(const api::orderman::OrderDefinition& def) if(dprorata.order_params().count("overfill_hedge") > 0) *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); else - prorata.mutable_overfill_hedge()->mutable_limit(); - } + prorata.mutable_overfill_hedge()->mutable_limit(); + } + return newt; } OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { const api::orderman::OrderDefinition& def = serv.definition(); - check_dynamic(def); - bts_assert(def.has_custom_def()); - bts_assert(def.custom_def().has_prorata()); + me->definition = convert_from_dynamic(serv.definition()); + bts_assert(definition().has_custom_def()); + bts_assert(definition().custom_def().has_prorata()); // Validate the prorata part of the definition - auto &prorata = def.custom_def().prorata(); + auto &prorata = definition().custom_def().prorata(); if (!prorata.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) { return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, @@ -135,8 +138,8 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { // if we are not attaching create a child template so we can // quickly launch our child when the time comes. - auto child_def = def; - *child_def.mutable_custom_def() = def.custom_def().prorata().child(); + auto child_def = definition(); + *child_def.mutable_custom_def() = definition().custom_def().prorata().child(); me->child_template = &(serv.make_child_template(child_def)); } @@ -149,12 +152,12 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) void ProRataAlgo::do_launch(IAlgoServices &algo) { me->algo = &algo; - set_parameters(algo, algo.definition().custom_def().prorata()); + set_parameters(algo, definition().custom_def().prorata()); LOG(OrderMan, Diag, "Starting ProRataAlgo {}, {} {}@{}. Will cover {} ticks", algo.order_key().value(), - securities::side_name(algo.definition().side()), algo.quantity().value(), + securities::side_name(definition().side()), algo.quantity().value(), algo.price().value(), - algo.definition().custom_def().prorata().hedge_ticks()); + definition().custom_def().prorata().hedge_ticks()); LOG(OrderMan, Diag, "ProRataAlgo {} launching child", algo.order_key().value()); me->child_key = algo.launch_child(*me->child_template, algo.price(), algo.quantity()); @@ -164,14 +167,13 @@ void ProRataAlgo::do_launch(IAlgoServices &algo) void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st) { me->algo = &algo; - set_parameters(algo, algo.definition().custom_def().prorata()); + set_parameters(algo, definition().custom_def().prorata()); me->child_key = k; me->hedged_fills = st.total_fills; algo.subscribe_book(SecurityKey(algo.security().id())); on_child_change(k, st); } - void ProRataAlgo::on_book(SecurityKey, const Book& b) { me->last_book = b; @@ -351,7 +353,9 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) LOG(OrderMan, Diag, "ProRataAlgo order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); - if (update.has_custom() && !update.custom().has_prorata()) + Update converted_update = convert_from_dynamic(update); + me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); + if (update.has_custom() && !converted_update.custom().has_prorata()) { algo().terminate_error("Invalid update"); return; @@ -364,7 +368,7 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) // process custom part of the udpate if any if (update.has_custom()) { - auto &prorata_update = update.custom().prorata(); + auto &prorata_update = converted_update.custom().prorata(); set_parameters(algo(), prorata_update); if(prorata_update.has_child()) @@ -388,9 +392,9 @@ void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, const api::orderman::CustomOrderDefinition& hedge_cdef, bool overfill) { api::orderman::OrderDefinition hedge_def; - hedge_def.CopyFrom(algo.definition()); + hedge_def.CopyFrom(definition()); - hedge_def.set_side(securities::other_side(algo.definition().side())); + hedge_def.set_side(securities::other_side(definition().side())); hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); hedge_def.clear_attach_target_order_key(); *hedge_def.mutable_custom_def() = hedge_cdef; diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index 07ffc294c..05ae354b3 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -35,7 +35,7 @@ private: void check_overfill(); void check_terminate(); const char *status_name(Status st); - void check_dynamic(const api::orderman::OrderDefinition&); + const api::orderman::OrderDefinition& definition() const; }; } // namespace orderman diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 49a4e61b3..745cc72cb 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -104,8 +104,7 @@ void ScratchAlgo::do_update(api::orderman::Update const &update) LOG(OrderMan, Diag, "ScratchOrder order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); Update converted_update = convert_from_dynamic(update); - me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); - + me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); if (update.has_custom() && !converted_update.custom().has_scratch()) { algo().terminate_error("Invalid update"); From 1567ca475d62e529b60c7c731ca9b15960ef8eaf Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 14:29:01 -0400 Subject: [PATCH 16/27] now moving to gui --- .../orders/algo/algo_orders/ProRataAlgo.cpp | 136 +++++++++--------- .../orders/algo/algo_orders/ProRataAlgo.h | 1 - .../orders/algo/algo_orders/ScratchAlgo.cpp | 71 +++++---- .../orders/algo/algo_orders/ScratchAlgo.h | 4 +- 4 files changed, 106 insertions(+), 106 deletions(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index f9a30826a..96b7aa52e 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -36,8 +36,6 @@ struct ProRataAlgo::PImpl { } IAlgoServices *algo; - OrderDefinition definition; - OrderKey child_key = null_order_key(); Price hedge_price_diff; @@ -64,68 +62,66 @@ struct ProRataAlgo::PImpl ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} ProRataAlgo::~ProRataAlgo() {} IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } -const OrderDefinition& ProRataAlgo::definition() const { return me->definition; } -template -T convert_from_dynamic(const T& orig) -{ - T newt = orig; - if(has_custom(orig) && custom(orig).has_dynamic()) - { - const DynamicOrderDefinition& dprorata = custom(orig).dynamic(); - auto& prorata = *mutable_custom(newt).mutable_prorata(); +// template +// T convert_from_dynamic(const T& orig) +// { +// T newt = orig; +// if(has_custom(orig) && custom(orig).has_dynamic()) +// { +// const DynamicOrderDefinition& dprorata = custom(orig).dynamic(); +// auto& prorata = *mutable_custom(newt).mutable_prorata(); - if(dprorata.order_params().count("hedge_ticks") > 0) - prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); - prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); +// if(dprorata.order_params().count("hedge_ticks") > 0) +// prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); +// prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); - if(dprorata.order_params().count("chase_ticks") > 0) - prorata.set_chase_ticks(dprorata.order_params().at("chase_ticks").as_uint32()); +// if(dprorata.order_params().count("chase_ticks") > 0) +// prorata.set_chase_ticks(dprorata.order_params().at("chase_ticks").as_uint32()); - if(dprorata.order_params().count("fill_limit") > 0) - *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); - if(!prorata.has_fill_limit() || - prorata.fill_limit().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) - prorata.mutable_fill_limit()->set_absolute(1u); +// if(dprorata.order_params().count("fill_limit") > 0) +// *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); +// if(!prorata.has_fill_limit() || +// prorata.fill_limit().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) +// prorata.mutable_fill_limit()->set_absolute(1u); - if(dprorata.order_params().count("stay_in_threshold") > 0) - *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); - if(!prorata.has_stay_in_threshold() || - prorata.stay_in_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) - prorata.mutable_stay_in_threshold()->set_absolute(1u); +// if(dprorata.order_params().count("stay_in_threshold") > 0) +// *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); +// if(!prorata.has_stay_in_threshold() || +// prorata.stay_in_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) +// prorata.mutable_stay_in_threshold()->set_absolute(1u); - if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) - prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); - if(dprorata.order_params().count("enable_stay_in") > 0) - prorata.set_enable_stay_in(dprorata.order_params().at("enable_stay_in").as_bool()); +// if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) +// prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); +// if(dprorata.order_params().count("enable_stay_in") > 0) +// prorata.set_enable_stay_in(dprorata.order_params().at("enable_stay_in").as_bool()); - if(dprorata.order_params().count("child") > 0) - *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); - else - prorata.mutable_child()->mutable_limit(); +// if(dprorata.order_params().count("child") > 0) +// *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); +// else +// prorata.mutable_child()->mutable_limit(); - if(dprorata.order_params().count("hedge") > 0) - *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); - else - prorata.mutable_hedge()->mutable_limit(); +// if(dprorata.order_params().count("hedge") > 0) +// *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); +// else +// prorata.mutable_hedge()->mutable_limit(); - if(dprorata.order_params().count("overfill_hedge") > 0) - *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); - else - prorata.mutable_overfill_hedge()->mutable_limit(); - } - return newt; -} +// if(dprorata.order_params().count("overfill_hedge") > 0) +// *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); +// else +// prorata.mutable_overfill_hedge()->mutable_limit(); +// } +// return newt; +// } OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { const api::orderman::OrderDefinition& def = serv.definition(); - me->definition = convert_from_dynamic(serv.definition()); - bts_assert(definition().has_custom_def()); - bts_assert(definition().custom_def().has_prorata()); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_prorata()); // Validate the prorata part of the definition - auto &prorata = definition().custom_def().prorata(); + auto &prorata = def.custom_def().prorata(); if (!prorata.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) { return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, @@ -138,8 +134,8 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { // if we are not attaching create a child template so we can // quickly launch our child when the time comes. - auto child_def = definition(); - *child_def.mutable_custom_def() = definition().custom_def().prorata().child(); + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().prorata().child(); me->child_template = &(serv.make_child_template(child_def)); } @@ -152,12 +148,12 @@ OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) void ProRataAlgo::do_launch(IAlgoServices &algo) { me->algo = &algo; - set_parameters(algo, definition().custom_def().prorata()); + set_parameters(algo, algo.definition().custom_def().prorata()); LOG(OrderMan, Diag, "Starting ProRataAlgo {}, {} {}@{}. Will cover {} ticks", algo.order_key().value(), - securities::side_name(definition().side()), algo.quantity().value(), + securities::side_name(algo.definition().side()), algo.quantity().value(), algo.price().value(), - definition().custom_def().prorata().hedge_ticks()); + algo.definition().custom_def().prorata().hedge_ticks()); LOG(OrderMan, Diag, "ProRataAlgo {} launching child", algo.order_key().value()); me->child_key = algo.launch_child(*me->child_template, algo.price(), algo.quantity()); @@ -167,7 +163,7 @@ void ProRataAlgo::do_launch(IAlgoServices &algo) void ProRataAlgo::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st) { me->algo = &algo; - set_parameters(algo, definition().custom_def().prorata()); + set_parameters(algo, algo.definition().custom_def().prorata()); me->child_key = k; me->hedged_fills = st.total_fills; algo.subscribe_book(SecurityKey(algo.security().id())); @@ -353,9 +349,7 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) LOG(OrderMan, Diag, "ProRataAlgo order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); - Update converted_update = convert_from_dynamic(update); - me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); - if (update.has_custom() && !converted_update.custom().has_prorata()) + if (update.has_custom() && !update.custom().has_prorata()) { algo().terminate_error("Invalid update"); return; @@ -368,7 +362,7 @@ void ProRataAlgo::do_update(const api::orderman::Update& update) // process custom part of the udpate if any if (update.has_custom()) { - auto &prorata_update = converted_update.custom().prorata(); + auto &prorata_update = update.custom().prorata(); set_parameters(algo(), prorata_update); if(prorata_update.has_child()) @@ -392,9 +386,9 @@ void orderman::ProRataAlgo::init_hedge_template(IBeforeLaunchAlgoServices &algo, const api::orderman::CustomOrderDefinition& hedge_cdef, bool overfill) { api::orderman::OrderDefinition hedge_def; - hedge_def.CopyFrom(definition()); + hedge_def.CopyFrom(algo.definition()); - hedge_def.set_side(securities::other_side(definition().side())); + hedge_def.set_side(securities::other_side(algo.definition().side())); hedge_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG); hedge_def.clear_attach_target_order_key(); *hedge_def.mutable_custom_def() = hedge_cdef; @@ -408,10 +402,22 @@ void ProRataAlgo::set_parameters(IBeforeLaunchAlgoServices &serv, const api::ord { me->hedge_price_diff = Price(securities::tick_size(serv.security()).value() * prorata.hedge_ticks()); me->chase_diff = Price(securities::tick_size(serv.security()).value() * prorata.chase_ticks()); - if(prorata.has_fill_limit()) - me->fill_limit = SpreaderUtils::_quantity_threshold(prorata.fill_limit(), algo().quantity()); - if(prorata.has_stay_in_threshold()) - me->stay_in_threshold = SpreaderUtils::_quantity_threshold(prorata.stay_in_threshold(), algo().quantity()); + + if (!prorata.has_fill_limit() || prorata.fill_limit().quantity_case() == + bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + { + algo().terminate_error("Invalid fill limit quantity, terminating"); + return; + } + me->fill_limit = SpreaderUtils::_quantity_threshold(prorata.fill_limit(), algo().quantity()); + + if (!prorata.has_stay_in_threshold() || prorata.stay_in_threshold().quantity_case() == + bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + { + algo().terminate_error("Invalid stay_in_threshold quantity, terminating"); + return; + } + me->stay_in_threshold = SpreaderUtils::_quantity_threshold(prorata.stay_in_threshold(), algo().quantity()); me->enable_scratch_on_overfill = prorata.enable_scratch_on_overfill(); me->enable_stay_in = prorata.enable_stay_in(); } diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h index 05ae354b3..502cbf520 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.h @@ -35,7 +35,6 @@ private: void check_overfill(); void check_terminate(); const char *status_name(Status st); - const api::orderman::OrderDefinition& definition() const; }; } // namespace orderman diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 745cc72cb..2bb3b56ad 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -32,40 +32,38 @@ struct ScratchAlgo::PImpl ScratchAlgo::ScratchAlgo() : me(new PImpl()) {} ScratchAlgo::~ScratchAlgo() {} IAlgoServices &ScratchAlgo::algo() const { return *me->algo; } -const OrderDefinition& ScratchAlgo::definition() const { return me->definition; } -template -T convert_from_dynamic(const T& orig) -{ - T newt = orig; - if ( has_custom(orig) && custom(orig).has_dynamic()) - { - const DynamicOrderDefinition& dscratch = custom(orig).dynamic(); - auto& scratch = *mutable_custom(newt).mutable_scratch(); +// template +// T convert_from_dynamic(const T& orig) +// { +// T newt = orig; +// if ( has_custom(orig) && custom(orig).has_dynamic()) +// { +// const DynamicOrderDefinition& dscratch = custom(orig).dynamic(); +// auto& scratch = *mutable_custom(newt).mutable_scratch(); - if(dscratch.order_params().count("scratch_threshold") > 0) - *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); +// if(dscratch.order_params().count("scratch_threshold") > 0) +// *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); - if(dscratch.order_params().count("chase_ticks") > 0) - scratch.set_chase_ticks(dscratch.order_params().at("chase_ticks").as_uint32()); +// if(dscratch.order_params().count("chase_ticks") > 0) +// scratch.set_chase_ticks(dscratch.order_params().at("chase_ticks").as_uint32()); - if(dscratch.order_params().count("child") > 0) - *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); - else - scratch.mutable_child()->mutable_limit(); - } - return newt; -} +// if(dscratch.order_params().count("child") > 0) +// *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); +// else +// scratch.mutable_child()->mutable_limit(); +// } +// return newt; +// } OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - me->definition = convert_from_dynamic(serv.definition()); - - bts_assert(definition().has_custom_def()); - bts_assert(definition().custom_def().has_scratch()); + const auto& def = serv.definition(); + bts_assert(def.has_custom_def()); + bts_assert(def.custom_def().has_scratch()); // Validate the scratch part of the definition - auto &scratch = definition().custom_def().scratch(); - if (!scratch.has_child() && OrderKey(definition().attach_target_order_key()) == null_order_key()) + auto &scratch = def.custom_def().scratch(); + if (!scratch.has_child() && OrderKey(def.attach_target_order_key()) == null_order_key()) { return OrderOpResult{ ORDER_ERROR_INVALID_ORDER_DEFINITON, "Scratch order must have either a child order definition or an order to attach to"}; @@ -74,8 +72,8 @@ OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { // if we are not attaching create a child template so we can // quickly launch our child when the time comes. - auto child_def = definition(); - *child_def.mutable_custom_def() = definition().custom_def().scratch().child(); + auto child_def = def; + *child_def.mutable_custom_def() = def.custom_def().scratch().child(); me->child_template = &(serv.make_child_template(child_def)); } return {}; @@ -103,9 +101,7 @@ void ScratchAlgo::do_update(api::orderman::Update const &update) { LOG(OrderMan, Diag, "ScratchOrder order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update)); - Update converted_update = convert_from_dynamic(update); - me->definition.mutable_custom_def()->CopyFrom(custom(converted_update)); - if (update.has_custom() && !converted_update.custom().has_scratch()) + if (update.has_custom() && !update.custom().has_scratch()) { algo().terminate_error("Invalid update"); return; @@ -118,7 +114,7 @@ void ScratchAlgo::do_update(api::orderman::Update const &update) if (update.has_custom()) { update_scratch_threshold(); - auto &scratch_update = converted_update.custom().scratch(); + auto &scratch_update = update.custom().scratch(); *child_update.mutable_custom() = scratch_update.child(); } algo().update_child(me->child_key, child_update); @@ -142,7 +138,7 @@ void ScratchAlgo::on_book(SecurityKey, Book const &b) { case Status::WAITING_FOR_MD: { - auto other_side = securities::other_side(definition().side()); + auto other_side = securities::other_side(algo().definition().side()); auto &other_side_top = me->last_book.side(other_side)[0]; if (other_side_top.size() > 0) @@ -167,7 +163,7 @@ void ScratchAlgo::on_book(SecurityKey, Book const &b) void ScratchAlgo::try_to_scratch() { bts_assert(me->status == Status::WAITING_TO_SCRATCH); - auto my_side = definition().side(); + auto my_side = algo().definition().side(); auto other_side = securities::other_side(my_side); Quantity my_quan; @@ -222,15 +218,16 @@ Price ScratchAlgo::get_price_to_pass (Price price) const void ScratchAlgo::update_scratch_threshold() { - if (definition().custom_def().scratch().scratch_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) + if (algo().definition().custom_def().scratch().scratch_threshold().quantity_case() == + bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) { algo().terminate_error("Invalid quantity, terminating"); return; } me->scratch_threshold = SpreaderUtils::_quantity_threshold( - definition().custom_def().scratch().scratch_threshold(), algo().quantity()); + algo().definition().custom_def().scratch().scratch_threshold(), algo().quantity()); me->chase_diff = Price(securities::tick_size( - algo().security()).value() * definition().custom_def().scratch().chase_ticks()); + algo().security()).value() * algo().definition().custom_def().scratch().chase_ticks()); } void ScratchAlgo::on_child_change(OrderKey, ChildState const &st) diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h index 11640bdca..ca6fada14 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.h @@ -24,9 +24,7 @@ public: private: enum class Status; struct PImpl; - std::unique_ptr me; - - const api::orderman::OrderDefinition& definition() const; + std::unique_ptr me; IAlgoServices& algo() const; void update_scratch_threshold(); From b1e19294e6f4de47401076fe351a2d40153818cc Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 17:50:35 -0400 Subject: [PATCH 17/27] making some headway on generic order ui --- src/client/spark/Orders/OrderDataHelper.cs | 12 ++ .../Orders/OrderTypeVMs/GenericOrderHelper.cs | 52 +++++ .../OrderTypeVMs/GenericOrderParamVM.cs | 178 ++++++++++++++++++ .../GenericOrderTemplateSelector.cs | 63 +++++++ .../Orders/OrderTypeVMs/GenericOrderVM.cs | 152 +++++++++++++++ .../Orders/OrderTypeVMs/OrderTypeVMFactory.cs | 3 +- .../Order/AlgoContentTemplateSelector.xaml | 170 +++++++++++++++++ .../Order/AlgoContentTemplateSelector.xaml.cs | 2 + src/lib/api/services/OrderService.proto | 8 + 9 files changed, 639 insertions(+), 1 deletion(-) create mode 100644 src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs create mode 100644 src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs create mode 100644 src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs create mode 100644 src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs diff --git a/src/client/spark/Orders/OrderDataHelper.cs b/src/client/spark/Orders/OrderDataHelper.cs index e31fface7..c3c9a8c96 100644 --- a/src/client/spark/Orders/OrderDataHelper.cs +++ b/src/client/spark/Orders/OrderDataHelper.cs @@ -213,6 +213,8 @@ namespace mbts.spark.utilities { public OffsetOrderDefinition offset_order() => OrderDataHelper.Defaults.OffsetOrderDefinition(); public TriggerOrderDefinition trigger_order() => OrderDataHelper.Defaults.TriggerOrderDefinition(); public DynamicOrderDefinition dynamic_order() => OrderDataHelper.Defaults.DynamicOrderDefinition(); + public GenericOrderDefinition generic_order(CustomOrderDefinition.CustomOneofCase order_type) => + OrderDataHelper.Defaults.GenericOrderDefinition(order_type); public SpreaderOrderDefinition spreader_order() => OrderDataHelper.Defaults.SpreaderOrderDefinition(); public SpreaderOrderDefinition spreader_order(SecurityImmutable security, ExecutionStrategyImmutable strategy) => new SpreaderOrderDefinition { @@ -245,6 +247,9 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = spreader_order(); break; case CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = dynamic_order(); break; //case CustomOrderDefinition.CustomOneofCase.QueueHolder: rv.QueueHolder = queue_holder_order(); break; + default: + rv.Generic = generic_order(order_type); + break; } return rv; } @@ -270,6 +275,7 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order }; case CustomOrderDefinition.CustomOneofCase.Spreader: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order }; case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; + case CustomOrderDefinition.CustomOneofCase.Generic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; case CustomOrderDefinition.CustomOneofCase.None: goto default; //case CustomOrderDefinition.CustomOneofCase.QueueHolder: return new OrderMetadata { KeyBinding = "Q", Color = BTSColors.purple.rgb_color() }; default: return _default_order_metadata; @@ -431,6 +437,7 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order }; case CustomOrderDefinition.CustomOneofCase.Spreader: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order }; case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; + case CustomOrderDefinition.CustomOneofCase.Generic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; case CustomOrderDefinition.CustomOneofCase.None: default: return _default_order_metadata; } @@ -993,6 +1000,9 @@ namespace mbts.spark.utilities { case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Trigger: rv.Trigger = TriggerOrderDefinition(); break; case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = SpreaderOrderDefinition(); break; case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = DynamicOrderDefinition(); break; + default: + rv.Generic = GenericOrderDefinition(order_type); + break; } return rv; } @@ -1016,7 +1026,9 @@ namespace mbts.spark.utilities { public static OffsetOrderDefinition OffsetOrderDefinition() => new OffsetOrderDefinition { Child = CustomOrderDefinition(), }; public static TriggerOrderDefinition TriggerOrderDefinition() => new TriggerOrderDefinition { Child = CustomOrderDefinition(), TriggerCondition = new TriggerCondition(), TriggerAction = new TriggerAction(), }; public static DynamicOrderDefinition DynamicOrderDefinition() => new DynamicOrderDefinition(); + public static GenericOrderDefinition GenericOrderDefinition(CustomOrderDefinition.CustomOneofCase order_type) => new GenericOrderDefinition { knownType = order_type.ToString() } ; public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() }; } } + } diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs new file mode 100644 index 000000000..e6a261364 --- /dev/null +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs @@ -0,0 +1,52 @@ + +using bts.api; +using bts.api.orderman; +using bts.utils; +using Google.Protobuf; +using Google.Protobuf.Reflection; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Reactive.Linq; + +namespace mbts.spark +{ + [Export] + class GenericOrderHelper + { + [ImportingConstructor] + private GenericOrderHelper(OrderService order_service) + { + } + + internal static string get_enumerated_value(IMessage message, FieldDescriptor fd) + { + var ev = fd.Accessor.GetValue(message); + return ev.ToString(); + } + internal static void set_enumerated_value(IMessage message, FieldDescriptor fd, string value) + { + if (message == null) + { + return; + } + var ev = fd.EnumType.Values.First(x => x.Name == value)?.Number; + if(ev.HasValue) + fd.Accessor.SetValue(message, ev.Value); + } + + internal static bts.spark.QuantityMeasureImmutable? get_quantity_value(IMessage message, FieldDescriptor fd) + { + return (bts.spark.QuantityMeasureImmutable)fd.Accessor.GetValue(message); + } + internal static void set_quantity_value(IMessage message, FieldDescriptor fd, bts.spark.QuantityMeasureImmutable? value) + { + if (message == null) + return; + fd.Accessor.SetValue(message, value?.CloneToMutable()); + } + } +} diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs new file mode 100644 index 000000000..606c83641 --- /dev/null +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs @@ -0,0 +1,178 @@ +using bts.api.orderman; +using Google.Protobuf.Reflection; +using mbts.ui.shell; +using bts.spark; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using Google.Protobuf.Reflection; + +namespace mbts.spark +{ + interface IGenericOrderParamVM + { + FieldDescriptor descriptor { get; } + Google.Protobuf.IMessage message { get; set; } + } + + interface IGenericOrderParamVM : IGenericOrderParamVM + { + T value { get; set; } + IObservable subscribe_value(); + } + + abstract class GenericOrderParamVM : DisposableViewModelBase, IGenericOrderParamVM + { + Google.Protobuf.IMessage _message; + protected GenericOrderParamVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) + { + _message = message; + this.descriptor = descriptor; + } + + public FieldDescriptor descriptor { get; set; } + public Google.Protobuf.IMessage message + { + get => _message; + set + { + _message = value; + on_param_changed(); + } + } + + protected abstract void on_param_changed(); + } + + class GenericOrderParamVM : GenericOrderParamVM, IGenericOrderParamVM + { + readonly Func _convert; + readonly Func _convert_back; + TView _value; + + public GenericOrderParamVM(Google.Protobuf.IMessage message, FieldDescriptor field_descriptor, Func convert, Func convert_back) : + base(message, field_descriptor) + { + _convert = convert; + _convert_back = convert_back; + } + + public TView value + { + get => _value; + set + { + this.descriptor.Accessor.SetValue(this.message, _convert_back(_value = value)); + RaisePropertyChanged(); + } + } + + public IObservable subscribe_value() => + Observable.Create(o => + { + PropertyChanged += on_prop_changed; + return Disposable.Create(() => PropertyChanged -= on_prop_changed); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => + o.OnNext(value); + }); + + protected override void on_param_changed() + { + _value = _convert(ConvertUtils.try_convert(this.descriptor.Accessor.GetValue(this.message))); + RaisePropertyChanged(nameof(value)); + } + } + + class GenericOrderEnumeratedVM : GenericOrderParamVM, IGenericOrderParamVM + { + public GenericOrderEnumeratedVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) + : base(message, descriptor) + { + elements = new ObservableCollection(_get_elements(descriptor)); + } + + public ObservableCollection elements { get; } + + public string selected_element + { + get => GenericOrderHelper.get_enumerated_value(message, descriptor); + set + { + var orig = selected_element; + GenericOrderHelper.set_enumerated_value(message, descriptor, value); + if (selected_element != orig) + RaisePropertyChanged(); + } + } + string IGenericOrderParamVM.value { get => selected_element; set => selected_element = value; } + + IObservable IGenericOrderParamVM.subscribe_value() => + Observable.Create(o => + { + PropertyChanged += on_prop_changed; + return Disposable.Create(() => PropertyChanged -= on_prop_changed); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => + o.OnNext(selected_element); + }); + + protected override void on_param_changed() + { + _sync_elements(); + RaisePropertyChanged(nameof(selected_element)); + } + + static IEnumerable _get_elements(FieldDescriptor descriptor) + { + if(descriptor.FieldType == Google.Protobuf.Reflection.FieldType.Enum) + { + return descriptor.EnumType.Values.Select(x => x.Name); + } + else + return Enumerable.Empty(); + } + + void _sync_elements() + { + elements.sync_with(_get_elements(descriptor)); + } + } + + + class GenericOrderQuantityVM : GenericOrderParamVM, IGenericOrderParamVM + { + public GenericOrderQuantityVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) + : base(message, descriptor) { } + + QuantityMeasureImmutable? IGenericOrderParamVM.value { get => quantity; set => quantity= value; } + public QuantityMeasureImmutable? quantity + { + get => GenericOrderHelper.get_quantity_value(message, descriptor); + set + { + var orig = quantity; + GenericOrderHelper.set_quantity_value(message, descriptor, value); + if (quantity != orig) + RaisePropertyChanged(); + } + } + + public IObservable subscribe_value() + { + return Observable.Create(o => + { + PropertyChanged += on_prop_changed; + return Disposable.Create(() => PropertyChanged -= on_prop_changed); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => + o.OnNext(quantity); + }); + } + + protected override void on_param_changed() + { + RaisePropertyChanged(nameof(quantity)); + } + } +} diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs new file mode 100644 index 000000000..8d29d0271 --- /dev/null +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs @@ -0,0 +1,63 @@ + +using bts.api.orderman; +using mbts.spark; +using mbts.ui.converters; +using mbts.ui.utilities; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace mbts.ui.spark +{ + class GenericOrderTemplateSelector : DataTemplateSelector + { + public DataTemplate BoolTemplate { get; set; } + public DataTemplate DoubleTemplate { get; set; } + public DataTemplate IntTemplate { get; set; } + public DataTemplate UIntTemplate { get; set; } + public DataTemplate StringTemplate { get; set; } + public DataTemplate OrderDefTemplate { get; set; } + public DataTemplate QuantityMeasureTemplate { get; set; } + + public DataTemplate EnumTemplate { get; set; } + + public override DataTemplate SelectTemplate(object item, DependencyObject container) + { + var vm = item as GenericOrderParamVM; + if (vm != null) + { + switch (vm.descriptor.FieldType) + { + case Google.Protobuf.Reflection.FieldType.Bool: + return BoolTemplate; + case Google.Protobuf.Reflection.FieldType.Float: + case Google.Protobuf.Reflection.FieldType.Double: + return DoubleTemplate; + case Google.Protobuf.Reflection.FieldType.Int32: + case Google.Protobuf.Reflection.FieldType.Int64: + return IntTemplate; + case Google.Protobuf.Reflection.FieldType.UInt32: + case Google.Protobuf.Reflection.FieldType.UInt64: + return UIntTemplate; + case Google.Protobuf.Reflection.FieldType.String: + return StringTemplate; + case Google.Protobuf.Reflection.FieldType.Enum: + return EnumTemplate; + case Google.Protobuf.Reflection.FieldType.Message: + { + if(vm.descriptor.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName) + return QuantityMeasureTemplate; + else if (vm.descriptor.MessageType.FullName == typeof(bts.api.orderman.CustomOrderDefinition).FullName) + return OrderDefTemplate; + } + break; + default: return null; + } + } + return null; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs new file mode 100644 index 000000000..6c5bbf74f --- /dev/null +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs @@ -0,0 +1,152 @@ + +using bts; +using bts.api.orderman; +using bts.collections; +using mbts.collections; +using mbts.spark.utilities; +using mbts.ui.utility; +using mbts.utils; +using bts.spark; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; + +using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; + +namespace mbts.spark +{ + static partial class OrderTypeVMFactory + { + class GenericOrderVM : OrderTypeVMBase + { + readonly ObservableKeyedCollection _parameters = new ObservableKeyedCollection(vm => vm.descriptor.ParamName); + readonly Property _algo_type_string; + readonly AlgoType _algo_type; + + public GenericOrderVM(AlgoKey key, AlgoType algo_type, string display_name, AlgoEditingPermissions editing_permissions) + : base(key, display_name, editing_permissions) + { + _algo_type = algo_type; + _algo_type_string = add_property(nameof(this.algo_type), GenericOrderDefinition.KnownTypeFieldNumber, + algo_type.ToString(), permissions: AlgoParamPermissions.None); + _parameters = new ObservableKeyedCollection(vm => vm.descriptor.Name); + _resources.AddRange( + _algo_type_string.Subscribe(_ => + { + _sync_generic_params(); + sync_selectors(); + }), + ObservableAutoWrapper.connect_item_hooks(_parameters, p => + { + p.PropertyChanged += on_param_prop_changed; + return Disposable.Create(() => + { + p.PropertyChanged -= on_param_prop_changed; + remove_property(p.descriptor.Name); + p.Dispose(); + }); + }, true)); + void on_param_prop_changed(object sender, PropertyChangedEventArgs e) => raise_definition_changed(); + } + + public string algo_type => _algo_type_string.Value; + public override string abbreviation => + model == null ? display_name : model.factory.abbreviate_algo(new OneOf(_algo_type)); + public override AlgoDisplayGroup group => AlgoDisplayGroup.API; + public ObservableCollection parameters => _parameters; + + protected CustomOrderDefinition construct() + { + string propname = _algo_type.ToString(); + var pi = typeof(CustomOrderDefinition).GetProperty(propname, + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); + ExceptionAssert.Argument.NotNull(pi, "construction of " + propname); + var rt = pi.PropertyType; + var rtt = Activator.CreateInstance(rt); + + System.Reflection.typ + } + + protected override void on_model_internal() + { + _sync_generic_params(); + } + + + void _sync_generic_params() + { + if (model != null) + { + var desc = model.dynamic_helper.get_descriptor(dyn_type); + Google.Protobuf.Reflection.MessageDescriptor desc = + _parameters.SyncWithDictionary(desc.ParamDesc.Where(_is_value_param_desc).ToDictionary(p => p.ParamName), _mk_param_vm); + } + } + + + protected override IEnumerable get_selector_datum() + { + var data = OrderDataHelper.get_child_algo_data( + new CustomOrderDefinition { Dynamic = model?.dynamic_helper?.create_def(dyn_type) ?? new DynamicOrderDefinition() + }); + return data; + } + + static bool _is_value_param_desc(DynamicOrderParamDescriptor desc) + { + return desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated || + (desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive && desc.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef); + } + + + DynamicOrderParamVM _mk_param_vm(DynamicOrderParamDescriptor descriptor) { + ExceptionAssert.Argument.NotNull(descriptor, nameof(descriptor)); + switch (descriptor.ParamType.DescriptorCase) { + case DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive: + switch (descriptor.ParamType.Primitive) { + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool: return mk(DynamicOrderParam.AsBoolFieldNumber, v => v, v => v.GetValueOrDefault()); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble: return mk(DynamicOrderParam.AsDoubleFieldNumber, v => v, v => v, double.NaN); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return mk(DynamicOrderParam.AsInt32FieldNumber, v => v, v => v.GetValueOrDefault()); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return mk(DynamicOrderParam.AsUint32FieldNumber, v => v, v => v.GetValueOrDefault()); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return mk(DynamicOrderParam.AsStringFieldNumber, v => v, v => v); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: + { + var qm = new DynamicOrderQuantityVM(descriptor); + return attached(qm, DynamicOrderHelper.get_quantity_value, DynamicOrderHelper.set_quantity_value, new QuantityMeasure { Ratio = 1.0, Absolute = 1 }); + } + default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.Primitive, nameof(descriptor)); + } + case DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated: + var pvm = new DynamicOrderEnumeratedVM(descriptor); + attached(pvm, DynamicOrderHelper.get_enumerated_value, DynamicOrderHelper.set_enumerated_value); + return pvm; + default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.DescriptorCase, nameof(descriptor)); + } + + DynamicOrderParamVM mk(int field_number, Func convert, Func convert_back, TView default_value = default) { + var fdesc = DynamicOrderParam.Descriptor.FindFieldByNumber(field_number); + var pvm = new DynamicOrderParamVM(descriptor, fdesc, convert, convert_back); + return attached>(pvm, get_from_param, assign_to_param, default_value); + + TView get_from_param(DynamicOrderParam param) => convert(ConvertUtils.try_convert(fdesc.Accessor.GetValue(param))); + void assign_to_param(DynamicOrderParam param, TView value) => fdesc.Accessor.SetValue(param, convert_back(value)); + } + + TParam attached(TParam pvm, Func selector, Action assign_to_param, T default_value = default) where TParam : DynamicOrderParamVM, IDynamicOrderParamVM { + add_property( + pvm.descriptor.ParamName, + mdef => mdef.OrderParams.TryGetValue(pvm.descriptor.ParamName, out DynamicOrderParam p) ? selector(p) : default_value, + (mdef, v) => assign_to_param(mdef.OrderParams.GetOrAdd(pvm.descriptor.ParamName, pn => new DynamicOrderParam()), v), + () => pvm.value, + v => pvm.value = v, + pvm.subscribe_value(), + default_value); + return pvm; + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs index 693dd9e25..d760f0737 100644 --- a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs +++ b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs @@ -56,6 +56,7 @@ namespace mbts.spark { public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions); public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions); public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions); + public static IAlgoVM generic(AlgoKey key, string display_name, AlgoType algo_type, AlgoEditingPermissions editing_permissions) => new GenericOrderVM(key, algo_type, display_name, editing_permissions); public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { if (def_data.value.CustomCase == AlgoType.Composite) { @@ -87,7 +88,7 @@ namespace mbts.spark { case AlgoType.Spreader: vm = spreader(key, name, editing_permissions); break; case AlgoType.Dynamic: vm = dynamic(key, name, name, editing_permissions); break; case AlgoType.None: vm = new DefaultAlgoVM(); break; - default: throw new NotImplementedException(); + default: vm = generic(key, name, algo_type, editing_permissions); break; } vm.is_expanded = is_expanded && vm.can_expand; return vm; diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index dc159595c..f5dc590c9 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1138,5 +1138,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml.cs b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml.cs index 9e1110cd8..1c8cfaf22 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml.cs +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml.cs @@ -44,6 +44,7 @@ namespace mbts.ui.spark { public DataTemplate SpreaderTemplate { get; set; } public DataTemplate DynamicOrderTemplate { get; set; } public DataTemplate DefaultOrderTemplate { get; set; } + public DataTemplate GenericOrderTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is IDynamicAlgoVMImpl) { @@ -65,6 +66,7 @@ namespace mbts.ui.spark { case CustomOrderDefinition.CustomOneofCase.Iceberg: return IcebergOrderTemplate; case CustomOrderDefinition.CustomOneofCase.Spreader: return SpreaderTemplate; case CustomOrderDefinition.CustomOneofCase.Dynamic: return DynamicOrderTemplate; + default: return GenericOrderTemplate; } } return null; diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 35d385b16..6f1d48fe7 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -103,6 +103,7 @@ message CustomOrderDefinition ScratchOrderDefinition scratch = 28; ProRataOrderDefinition prorata = 29; + GenericOrderDefinition generic = 900; DynamicOrderDefinition dynamic = 1000; } } @@ -220,6 +221,11 @@ message DynamicOrderDefinition { string dynamic_order_type = 1; map order_params = 2; } +//Like dynamic, this order type generates a UI, but is used a wrapper for a typed native algo above +message GenericOrderDefinition { + string known_type = 1; + CustomOrderDefinition definition = 2; +} // End custom order definitions message OrderRecord { @@ -271,6 +277,7 @@ message OrderState { ScratchOrderState scratch = 27; ProRataOrderState prorata = 28; + GenericOrderState generic = 250; DynamicOrderState dynamic = 255; // do not use anything bigger than 255, or things will break } } @@ -348,6 +355,7 @@ message PricerOrderState {} message ScratchOrderState {} message ProRataOrderState {} message DynamicOrderState {} +message GenericOrderState {} message QueueHolderState {} enum OrderStatus { From 01956e92b6b95127b6c334cbcfad40666c889ff1 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 21:25:39 -0400 Subject: [PATCH 18/27] added facility for simple guis of well known order type protos to be generated; worth it. --- src/client/spark/Orders/OrderDataHelper.cs | 28 ++- .../OrderTypeVMs/DynamicOrderParamVM.cs | 2 +- .../Orders/OrderTypeVMs/DynamicOrderVM.cs | 2 +- .../Orders/OrderTypeVMs/GenericOrderHelper.cs | 6 +- .../OrderTypeVMs/GenericOrderParamVM.cs | 39 ++-- .../GenericOrderTemplateSelector.cs | 58 +++--- .../Orders/OrderTypeVMs/GenericOrderVM.cs | 180 ++++++++++-------- .../Orders/OrderTypeVMs/OrderTypeVMFactory.cs | 7 +- .../Collections/ObservableKeyedCollection.cs | 16 ++ src/lib/api/services/OrderService.proto | 8 - src/server/sparkd/cmds/Run.cpp | 58 ------ 11 files changed, 194 insertions(+), 210 deletions(-) diff --git a/src/client/spark/Orders/OrderDataHelper.cs b/src/client/spark/Orders/OrderDataHelper.cs index c3c9a8c96..af4fd93ec 100644 --- a/src/client/spark/Orders/OrderDataHelper.cs +++ b/src/client/spark/Orders/OrderDataHelper.cs @@ -213,8 +213,6 @@ namespace mbts.spark.utilities { public OffsetOrderDefinition offset_order() => OrderDataHelper.Defaults.OffsetOrderDefinition(); public TriggerOrderDefinition trigger_order() => OrderDataHelper.Defaults.TriggerOrderDefinition(); public DynamicOrderDefinition dynamic_order() => OrderDataHelper.Defaults.DynamicOrderDefinition(); - public GenericOrderDefinition generic_order(CustomOrderDefinition.CustomOneofCase order_type) => - OrderDataHelper.Defaults.GenericOrderDefinition(order_type); public SpreaderOrderDefinition spreader_order() => OrderDataHelper.Defaults.SpreaderOrderDefinition(); public SpreaderOrderDefinition spreader_order(SecurityImmutable security, ExecutionStrategyImmutable strategy) => new SpreaderOrderDefinition { @@ -248,7 +246,7 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = dynamic_order(); break; //case CustomOrderDefinition.CustomOneofCase.QueueHolder: rv.QueueHolder = queue_holder_order(); break; default: - rv.Generic = generic_order(order_type); + OrderTypeVMFactory.GenericOrderFactory.setup_generic_custom_order(rv, order_type); break; } return rv; @@ -275,7 +273,6 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order }; case CustomOrderDefinition.CustomOneofCase.Spreader: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order }; case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; - case CustomOrderDefinition.CustomOneofCase.Generic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; case CustomOrderDefinition.CustomOneofCase.None: goto default; //case CustomOrderDefinition.CustomOneofCase.QueueHolder: return new OrderMetadata { KeyBinding = "Q", Color = BTSColors.purple.rgb_color() }; default: return _default_order_metadata; @@ -437,7 +434,6 @@ namespace mbts.spark.utilities { case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order }; case CustomOrderDefinition.CustomOneofCase.Spreader: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order }; case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; - case CustomOrderDefinition.CustomOneofCase.Generic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order }; case CustomOrderDefinition.CustomOneofCase.None: default: return _default_order_metadata; } @@ -593,9 +589,6 @@ namespace mbts.spark.utilities { new AlgoStructureKey(defi.CustomCase))); public static readonly CustomOrderDefinition.CustomOneofCase[] - // The following standard types are not yet ready for production use: - // CustomOrderDefinition.CustomOneofCase.Tick, - // CustomOrderDefinition.CustomOneofCase.Dynamic, exchange_order_types = new[] { CustomOrderDefinition.CustomOneofCase.Market, CustomOrderDefinition.CustomOneofCase.Limit, @@ -605,24 +598,28 @@ namespace mbts.spark.utilities { CustomOrderDefinition.CustomOneofCase.Lean, CustomOrderDefinition.CustomOneofCase.Join, CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, }, - // The following spreader types are not yet ready for production use: - // CustomOrderDefinition.CustomOneofCase.Dynamic, spreader_order_types = new[] { CustomOrderDefinition.CustomOneofCase.Spreader, CustomOrderDefinition.CustomOneofCase.Iceberg, CustomOrderDefinition.CustomOneofCase.Lean, CustomOrderDefinition.CustomOneofCase.Join, - CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top + CustomOrderDefinition.CustomOneofCase.Cover, + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, }, attachable_order_types = new[] { CustomOrderDefinition.CustomOneofCase.Iceberg, CustomOrderDefinition.CustomOneofCase.Lean, CustomOrderDefinition.CustomOneofCase.Join, CustomOrderDefinition.CustomOneofCase.Cover, - CustomOrderDefinition.CustomOneofCase.Top + CustomOrderDefinition.CustomOneofCase.Top, + CustomOrderDefinition.CustomOneofCase.Scratch, + CustomOrderDefinition.CustomOneofCase.Prorata, }; public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray(); @@ -1001,7 +998,7 @@ namespace mbts.spark.utilities { case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = SpreaderOrderDefinition(); break; case bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = DynamicOrderDefinition(); break; default: - rv.Generic = GenericOrderDefinition(order_type); + OrderTypeVMFactory.GenericOrderFactory.setup_generic_custom_order(rv, order_type); break; } return rv; @@ -1026,7 +1023,6 @@ namespace mbts.spark.utilities { public static OffsetOrderDefinition OffsetOrderDefinition() => new OffsetOrderDefinition { Child = CustomOrderDefinition(), }; public static TriggerOrderDefinition TriggerOrderDefinition() => new TriggerOrderDefinition { Child = CustomOrderDefinition(), TriggerCondition = new TriggerCondition(), TriggerAction = new TriggerAction(), }; public static DynamicOrderDefinition DynamicOrderDefinition() => new DynamicOrderDefinition(); - public static GenericOrderDefinition GenericOrderDefinition(CustomOrderDefinition.CustomOneofCase order_type) => new GenericOrderDefinition { knownType = order_type.ToString() } ; public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() }; } } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs index d80ae2413..ade3260a4 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderParamVM.cs @@ -26,7 +26,7 @@ namespace mbts.spark { protected DynamicOrderParamVM(DynamicOrderParamDescriptor descriptor) : this(descriptor, DynamicOrderHelper.init_param(descriptor)) { } - protected DynamicOrderParamVM(DynamicOrderParamDescriptor descriptor, DynamicOrderParam param) { + private DynamicOrderParamVM(DynamicOrderParamDescriptor descriptor, DynamicOrderParam param) { this.descriptor = descriptor; _param = param; } diff --git a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs index 76af9879d..37726c245 100644 --- a/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/DynamicOrderVM.cs @@ -74,7 +74,7 @@ namespace mbts.spark { switch (descriptor.ParamType.Primitive) { case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool: return mk(DynamicOrderParam.AsBoolFieldNumber, v => v, v => v.GetValueOrDefault()); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble: return mk(DynamicOrderParam.AsDoubleFieldNumber, v => v, v => v, double.NaN); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return mk(DynamicOrderParam.AsInt32FieldNumber, v => v, v => v.GetValueOrDefault()); + case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return mk(DynamicOrderParam.AsInt32FieldNumber, v => v, v => v.GetValueOrDefault()); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return mk(DynamicOrderParam.AsUint32FieldNumber, v => v, v => v.GetValueOrDefault()); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return mk(DynamicOrderParam.AsStringFieldNumber, v => v, v => v); case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs index e6a261364..948b8a487 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderHelper.cs @@ -40,7 +40,11 @@ namespace mbts.spark internal static bts.spark.QuantityMeasureImmutable? get_quantity_value(IMessage message, FieldDescriptor fd) { - return (bts.spark.QuantityMeasureImmutable)fd.Accessor.GetValue(message); + var qm = (bts.spark.QuantityMeasure)fd.Accessor.GetValue(message); + if(qm != null) + return new bts.spark.QuantityMeasureImmutable(qm); + else + return null; } internal static void set_quantity_value(IMessage message, FieldDescriptor fd, bts.spark.QuantityMeasureImmutable? value) { diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs index 606c83641..a0ed8fbb8 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderParamVM.cs @@ -8,13 +8,13 @@ using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; -using Google.Protobuf.Reflection; +using Google.Protobuf; namespace mbts.spark { interface IGenericOrderParamVM { - FieldDescriptor descriptor { get; } + FieldDescriptor descriptor { get; } Google.Protobuf.IMessage message { get; set; } } @@ -24,12 +24,14 @@ namespace mbts.spark IObservable subscribe_value(); } - abstract class GenericOrderParamVM : DisposableViewModelBase, IGenericOrderParamVM + abstract class GenericOrderParamVM : DisposableViewModelBase, IGenericOrderParamVM + where TMutable : class, IMessage, new() { - Google.Protobuf.IMessage _message; - protected GenericOrderParamVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) - { - _message = message; + TMutable _message; + + protected GenericOrderParamVM(FieldDescriptor descriptor) + { + _message = new TMutable(); this.descriptor = descriptor; } @@ -39,7 +41,7 @@ namespace mbts.spark get => _message; set { - _message = value; + _message = (TMutable)value; on_param_changed(); } } @@ -47,14 +49,15 @@ namespace mbts.spark protected abstract void on_param_changed(); } - class GenericOrderParamVM : GenericOrderParamVM, IGenericOrderParamVM + class GenericOrderParamVM : GenericOrderParamVM, IGenericOrderParamVM + where TMutable : class, IMessage, new() { readonly Func _convert; readonly Func _convert_back; TView _value; - public GenericOrderParamVM(Google.Protobuf.IMessage message, FieldDescriptor field_descriptor, Func convert, Func convert_back) : - base(message, field_descriptor) + public GenericOrderParamVM(FieldDescriptor field_descriptor, Func convert, Func convert_back) : + base(field_descriptor) { _convert = convert; _convert_back = convert_back; @@ -86,10 +89,11 @@ namespace mbts.spark } } - class GenericOrderEnumeratedVM : GenericOrderParamVM, IGenericOrderParamVM + class GenericOrderEnumeratedVM : GenericOrderParamVM, IGenericOrderParamVM + where TMutable : class, IMessage, new() { - public GenericOrderEnumeratedVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) - : base(message, descriptor) + public GenericOrderEnumeratedVM(FieldDescriptor descriptor) + : base(descriptor) { elements = new ObservableCollection(_get_elements(descriptor)); } @@ -141,10 +145,11 @@ namespace mbts.spark } - class GenericOrderQuantityVM : GenericOrderParamVM, IGenericOrderParamVM + class GenericOrderQuantityVM : GenericOrderParamVM, IGenericOrderParamVM + where TMutable : class, IMessage, new() { - public GenericOrderQuantityVM(Google.Protobuf.IMessage message, FieldDescriptor descriptor) - : base(message, descriptor) { } + public GenericOrderQuantityVM(FieldDescriptor descriptor) + : base(descriptor) { } QuantityMeasureImmutable? IGenericOrderParamVM.value { get => quantity; set => quantity= value; } public QuantityMeasureImmutable? quantity diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs index 8d29d0271..4eaafb297 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderTemplateSelector.cs @@ -12,7 +12,7 @@ using System.Windows.Data; namespace mbts.ui.spark { - class GenericOrderTemplateSelector : DataTemplateSelector + class GenericOrderParamTemplateSelector : DataTemplateSelector { public DataTemplate BoolTemplate { get; set; } public DataTemplate DoubleTemplate { get; set; } @@ -26,36 +26,40 @@ namespace mbts.ui.spark public override DataTemplate SelectTemplate(object item, DependencyObject container) { - var vm = item as GenericOrderParamVM; + var vm = item as IGenericOrderParamVM; if (vm != null) + return select_template(vm.descriptor); + return null; + } + + public DataTemplate select_template(Google.Protobuf.Reflection.FieldDescriptor descriptor) + { + switch (descriptor.FieldType) { - switch (vm.descriptor.FieldType) + case Google.Protobuf.Reflection.FieldType.Bool: + return BoolTemplate; + case Google.Protobuf.Reflection.FieldType.Float: + case Google.Protobuf.Reflection.FieldType.Double: + return DoubleTemplate; + case Google.Protobuf.Reflection.FieldType.Int32: + case Google.Protobuf.Reflection.FieldType.Int64: + return IntTemplate; + case Google.Protobuf.Reflection.FieldType.UInt32: + case Google.Protobuf.Reflection.FieldType.UInt64: + return UIntTemplate; + case Google.Protobuf.Reflection.FieldType.String: + return StringTemplate; + case Google.Protobuf.Reflection.FieldType.Enum: + return EnumTemplate; + case Google.Protobuf.Reflection.FieldType.Message: { - case Google.Protobuf.Reflection.FieldType.Bool: - return BoolTemplate; - case Google.Protobuf.Reflection.FieldType.Float: - case Google.Protobuf.Reflection.FieldType.Double: - return DoubleTemplate; - case Google.Protobuf.Reflection.FieldType.Int32: - case Google.Protobuf.Reflection.FieldType.Int64: - return IntTemplate; - case Google.Protobuf.Reflection.FieldType.UInt32: - case Google.Protobuf.Reflection.FieldType.UInt64: - return UIntTemplate; - case Google.Protobuf.Reflection.FieldType.String: - return StringTemplate; - case Google.Protobuf.Reflection.FieldType.Enum: - return EnumTemplate; - case Google.Protobuf.Reflection.FieldType.Message: - { - if(vm.descriptor.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName) - return QuantityMeasureTemplate; - else if (vm.descriptor.MessageType.FullName == typeof(bts.api.orderman.CustomOrderDefinition).FullName) - return OrderDefTemplate; - } - break; - default: return null; + if(descriptor.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName) + return QuantityMeasureTemplate; + else if (descriptor.MessageType.FullName == typeof(bts.api.orderman.CustomOrderDefinition).FullName) + return OrderDefTemplate; } + break; + default: return null; } return null; } diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs index 6c5bbf74f..3a42bbdfe 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs @@ -14,31 +14,57 @@ using System.ComponentModel; using System.Linq; using System.Reactive.Linq; + +using Google.Protobuf; +using Google.Protobuf.Reflection; +using bts.api; using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; namespace mbts.spark { static partial class OrderTypeVMFactory { - class GenericOrderVM : OrderTypeVMBase + internal class GenericOrderFactory + { + static public IAlgoVM create_vm(AlgoKey key, AlgoType algo_type, string display_name, AlgoEditingPermissions editing_permissions) + { + var prop = typeof(CustomOrderDefinition).GetProperty(algo_type.ToString(), + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); + var rt = prop.PropertyType; + + var propi = typeof(CustomOrderDefinitionImmutable).GetProperty(algo_type.ToString(), + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); + var rti = propi.PropertyType; + + var vmt = typeof(GenericOrderVM<,>); + Type[] typeargs = { rt, rti }; + var makevm = vmt.MakeGenericType(typeargs); + object vm = Activator.CreateInstance(makevm, key, algo_type, display_name, editing_permissions); + return (IAlgoVM)vm; + } + static public void setup_generic_custom_order(CustomOrderDefinition custom, CustomOrderDefinition.CustomOneofCase type) + { + var prop = typeof(CustomOrderDefinition).GetProperty(type.ToString(), + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); + var rt = prop.PropertyType; + var rtt = Activator.CreateInstance(rt); + prop.SetValue(custom, rtt); + } + } + + class GenericOrderVM : OrderTypeVMBase + where TMutable : class, IMessage, new() where TImmutable : struct, IImmutableMessage { - readonly ObservableKeyedCollection _parameters = new ObservableKeyedCollection(vm => vm.descriptor.ParamName); - readonly Property _algo_type_string; + readonly ObservableKeyedCollection, string> _parameters = + new ObservableKeyedCollection, string>(vm => vm.descriptor.Name); readonly AlgoType _algo_type; public GenericOrderVM(AlgoKey key, AlgoType algo_type, string display_name, AlgoEditingPermissions editing_permissions) : base(key, display_name, editing_permissions) { _algo_type = algo_type; - _algo_type_string = add_property(nameof(this.algo_type), GenericOrderDefinition.KnownTypeFieldNumber, - algo_type.ToString(), permissions: AlgoParamPermissions.None); - _parameters = new ObservableKeyedCollection(vm => vm.descriptor.Name); + _parameters = new ObservableKeyedCollection, string>(vm => vm.descriptor.Name); _resources.AddRange( - _algo_type_string.Subscribe(_ => - { - _sync_generic_params(); - sync_selectors(); - }), ObservableAutoWrapper.connect_item_hooks(_parameters, p => { p.PropertyChanged += on_param_prop_changed; @@ -50,103 +76,97 @@ namespace mbts.spark }); }, true)); void on_param_prop_changed(object sender, PropertyChangedEventArgs e) => raise_definition_changed(); + _sync_generic_params(); + sync_selectors(); } - public string algo_type => _algo_type_string.Value; + public string algo_type => _algo_type.ToString(); public override string abbreviation => model == null ? display_name : model.factory.abbreviate_algo(new OneOf(_algo_type)); public override AlgoDisplayGroup group => AlgoDisplayGroup.API; - public ObservableCollection parameters => _parameters; - - protected CustomOrderDefinition construct() - { - string propname = _algo_type.ToString(); - var pi = typeof(CustomOrderDefinition).GetProperty(propname, - System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); - ExceptionAssert.Argument.NotNull(pi, "construction of " + propname); - var rt = pi.PropertyType; - var rtt = Activator.CreateInstance(rt); - - System.Reflection.typ - } + public ObservableCollection> parameters => _parameters; protected override void on_model_internal() { _sync_generic_params(); } - void _sync_generic_params() { if (model != null) - { - var desc = model.dynamic_helper.get_descriptor(dyn_type); - Google.Protobuf.Reflection.MessageDescriptor desc = - _parameters.SyncWithDictionary(desc.ParamDesc.Where(_is_value_param_desc).ToDictionary(p => p.ParamName), _mk_param_vm); + { + Google.Protobuf.Reflection.MessageDescriptor desc = new TMutable().Descriptor; + _parameters.SyncWithDictionaryNotNull( + desc.Fields.InDeclarationOrder().Where(_is_value_param_desc).ToDictionary(p => p.Name), _mk_param_vm); } } + static bool _is_value_param_desc(FieldDescriptor desc) + { + return (desc.FieldType != Google.Protobuf.Reflection.FieldType.Message || + _is_quantity_measure_desc(desc)); + } + static bool _is_quantity_measure_desc(FieldDescriptor desc) + { + return desc.FieldType == Google.Protobuf.Reflection.FieldType.Message && + desc.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName; + } protected override IEnumerable get_selector_datum() { - var data = OrderDataHelper.get_child_algo_data( - new CustomOrderDefinition { Dynamic = model?.dynamic_helper?.create_def(dyn_type) ?? new DynamicOrderDefinition() - }); - return data; + return OrderDataHelper.get_child_algo_data(_algo_type); } - static bool _is_value_param_desc(DynamicOrderParamDescriptor desc) + GenericOrderParamVM _mk_param_vm(FieldDescriptor descriptor) { - return desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated || - (desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive && desc.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef); - } - - - DynamicOrderParamVM _mk_param_vm(DynamicOrderParamDescriptor descriptor) { ExceptionAssert.Argument.NotNull(descriptor, nameof(descriptor)); - switch (descriptor.ParamType.DescriptorCase) { - case DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive: - switch (descriptor.ParamType.Primitive) { - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool: return mk(DynamicOrderParam.AsBoolFieldNumber, v => v, v => v.GetValueOrDefault()); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble: return mk(DynamicOrderParam.AsDoubleFieldNumber, v => v, v => v, double.NaN); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return mk(DynamicOrderParam.AsInt32FieldNumber, v => v, v => v.GetValueOrDefault()); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return mk(DynamicOrderParam.AsUint32FieldNumber, v => v, v => v.GetValueOrDefault()); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return mk(DynamicOrderParam.AsStringFieldNumber, v => v, v => v); - case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity: - { - var qm = new DynamicOrderQuantityVM(descriptor); - return attached(qm, DynamicOrderHelper.get_quantity_value, DynamicOrderHelper.set_quantity_value, new QuantityMeasure { Ratio = 1.0, Absolute = 1 }); - } - default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.Primitive, nameof(descriptor)); - } - case DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated: - var pvm = new DynamicOrderEnumeratedVM(descriptor); - attached(pvm, DynamicOrderHelper.get_enumerated_value, DynamicOrderHelper.set_enumerated_value); - return pvm; - default: throw ExceptionBuilder.Argument.unexpected_case(descriptor.ParamType.DescriptorCase, nameof(descriptor)); + + if (descriptor.FieldType == FieldType.Message && + descriptor.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName) + { + var qm = new GenericOrderQuantityVM(descriptor); + return attached(qm, GenericOrderHelper.get_quantity_value, GenericOrderHelper.set_quantity_value, new QuantityMeasure { Ratio = 1.0, Absolute = 1 }); } - - DynamicOrderParamVM mk(int field_number, Func convert, Func convert_back, TView default_value = default) { - var fdesc = DynamicOrderParam.Descriptor.FindFieldByNumber(field_number); - var pvm = new DynamicOrderParamVM(descriptor, fdesc, convert, convert_back); - return attached>(pvm, get_from_param, assign_to_param, default_value); - - TView get_from_param(DynamicOrderParam param) => convert(ConvertUtils.try_convert(fdesc.Accessor.GetValue(param))); - void assign_to_param(DynamicOrderParam param, TView value) => fdesc.Accessor.SetValue(param, convert_back(value)); - } - - TParam attached(TParam pvm, Func selector, Action assign_to_param, T default_value = default) where TParam : DynamicOrderParamVM, IDynamicOrderParamVM { - add_property( - pvm.descriptor.ParamName, - mdef => mdef.OrderParams.TryGetValue(pvm.descriptor.ParamName, out DynamicOrderParam p) ? selector(p) : default_value, - (mdef, v) => assign_to_param(mdef.OrderParams.GetOrAdd(pvm.descriptor.ParamName, pn => new DynamicOrderParam()), v), - () => pvm.value, - v => pvm.value = v, - pvm.subscribe_value(), - default_value); + else if(descriptor.FieldType == FieldType.Enum) + { + var pvm = new GenericOrderEnumeratedVM(descriptor); + attached(pvm, GenericOrderHelper.get_enumerated_value, GenericOrderHelper.set_enumerated_value); return pvm; } + else if (descriptor.FieldType == FieldType.Bool) + return mk(descriptor, v => v, v => v.GetValueOrDefault()); + else if (descriptor.FieldType == FieldType.Double || descriptor.FieldType == FieldType.Float) + return mk(descriptor, v => v, v => v, double.NaN); + else if (descriptor.FieldType == FieldType.Int32) + return mk(descriptor, v => v, v => v.GetValueOrDefault()); + else if (descriptor.FieldType == FieldType.UInt32) + return mk(descriptor, v => v, v => v.GetValueOrDefault()); + else if (descriptor.FieldType == FieldType.String) + return mk(descriptor, v => v, v => v); + else + return null; } + GenericOrderParamVM mk(FieldDescriptor fdesc, Func convert, Func convert_back, TView default_value = default) + { + var pvm = new GenericOrderParamVM(fdesc, convert, convert_back); + return attached>(pvm, get_from_param, assign_to_param, default_value); + + TView get_from_param(IMessage param, FieldDescriptor fd) => convert(ConvertUtils.try_convert(fdesc.Accessor.GetValue(param))); + void assign_to_param(IMessage param, FieldDescriptor fd, TView value) => fdesc.Accessor.SetValue(param, convert_back(value)); + } + + TParam attached(TParam pvm, Func selector, Action assign_to_param, T default_value = default) where TParam : GenericOrderParamVM, IGenericOrderParamVM + { + add_property( + pvm.descriptor.Name, + mdef => mdef != null ? selector(mdef, pvm.descriptor) : default_value, + (mdef, v) => assign_to_param(mdef, pvm.descriptor, v), + () => pvm.value, + v => pvm.value = v, + pvm.subscribe_value(), + default_value); + return pvm; + } } } } \ No newline at end of file diff --git a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs index d760f0737..ed4ba86db 100644 --- a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs +++ b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs @@ -56,7 +56,12 @@ namespace mbts.spark { public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions); public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions); public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions); - public static IAlgoVM generic(AlgoKey key, string display_name, AlgoType algo_type, AlgoEditingPermissions editing_permissions) => new GenericOrderVM(key, algo_type, display_name, editing_permissions); + + public static IAlgoVM generic(AlgoKey key, string display_name, + AlgoType algo_type, AlgoEditingPermissions editing_permissions) + { + return GenericOrderFactory.create_vm(key, algo_type, display_name, editing_permissions); + } public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) { if (def_data.value.CustomCase == AlgoType.Composite) { diff --git a/src/client/spark/core/Collections/ObservableKeyedCollection.cs b/src/client/spark/core/Collections/ObservableKeyedCollection.cs index 578c51acb..e25dc53a6 100644 --- a/src/client/spark/core/Collections/ObservableKeyedCollection.cs +++ b/src/client/spark/core/Collections/ObservableKeyedCollection.cs @@ -128,6 +128,22 @@ namespace mbts.collections { } } + public void SyncWithDictionaryNotNull(IReadOnlyDictionary dictionary, Func factory) + { + foreach (var k in _map.Keys.Except(dictionary.Keys).ToList()) + Remove(k); + foreach (var kv in dictionary) + { + if (!ContainsKey(kv.Key)) + { + var v = factory(kv.Value); + if(v != null) + Add(v); + } + } + } + + public void SyncWithDictionary(IReadOnlyDictionary dictionary, Func factory) { foreach (var k in _map.Keys.Except(dictionary.Keys).ToList()) Remove(k); diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 6f1d48fe7..35d385b16 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -103,7 +103,6 @@ message CustomOrderDefinition ScratchOrderDefinition scratch = 28; ProRataOrderDefinition prorata = 29; - GenericOrderDefinition generic = 900; DynamicOrderDefinition dynamic = 1000; } } @@ -221,11 +220,6 @@ message DynamicOrderDefinition { string dynamic_order_type = 1; map order_params = 2; } -//Like dynamic, this order type generates a UI, but is used a wrapper for a typed native algo above -message GenericOrderDefinition { - string known_type = 1; - CustomOrderDefinition definition = 2; -} // End custom order definitions message OrderRecord { @@ -277,7 +271,6 @@ message OrderState { ScratchOrderState scratch = 27; ProRataOrderState prorata = 28; - GenericOrderState generic = 250; DynamicOrderState dynamic = 255; // do not use anything bigger than 255, or things will break } } @@ -355,7 +348,6 @@ message PricerOrderState {} message ScratchOrderState {} message ProRataOrderState {} message DynamicOrderState {} -message GenericOrderState {} message QueueHolderState {} enum OrderStatus { diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 299e53901..6460a060b 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -81,64 +81,6 @@ int Run::execute(std::vector const &) { plugin::init_plugins(plugin_services); // finished initializing order plugins - //TODO these will go away once Haris approves algo - using namespace api::orderman; - { - DynamicOrderDescriptor desc; - desc.set_dynamic_order_type("Scratch"); - auto param = desc.add_param_desc(); - param->set_param_name("scratch_threshold"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); - param = desc.add_param_desc(); - param->set_param_name("chase_ticks"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); - - param = desc.add_param_desc(); - param->set_param_name("child"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); - plugin_services.register_dynamic_algo_order( - desc, []() { return std::make_unique(); }); - } - - { - DynamicOrderDescriptor desc; - desc.set_dynamic_order_type("ProRata"); - auto param = desc.add_param_desc(); - param->set_param_name("hedge_ticks"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); - param = desc.add_param_desc(); - param->set_param_name("chase_ticks"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); - - param = desc.add_param_desc(); - param->set_param_name("fill_limit"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); - - param = desc.add_param_desc(); - param->set_param_name("stay_in_threshold"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_QUANTITY); - param = desc.add_param_desc(); - param->set_param_name("enable_scratch_on_overfill"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_BOOL); - param = desc.add_param_desc(); - param->set_param_name("enable_stay_in"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_BOOL); - - param = desc.add_param_desc(); - param->set_param_name("child"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); - param = desc.add_param_desc(); - param->set_param_name("hedge"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); - param = desc.add_param_desc(); - param->set_param_name("overfill_hedge"); - param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); - - - plugin_services.register_dynamic_algo_order( - desc, []() { return std::make_unique(); }); - } - orderman::OrderServiceServer order_service_server( sc, mdclient, dyn_order_registry, stats, perf_log); support::ErrorReportServer error_report_service(sc); From 90178908ba524dca535aedbde04953b4636869d0 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 28 May 2019 22:02:21 -0400 Subject: [PATCH 19/27] looking good; need John to help me figure out the hedge lablels --- .../spark/Orders/OrderTypeVMs/GenericOrderVM.cs | 9 ++++----- .../Order/AlgoContentTemplateSelector.xaml | 14 +++++++------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs index 3a42bbdfe..dd5117dfd 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs @@ -48,6 +48,10 @@ namespace mbts.spark System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var rt = prop.PropertyType; var rtt = Activator.CreateInstance(rt); + + var ci = rt.GetProperties().Where(x => x.PropertyType == typeof(CustomOrderDefinition)); + foreach(var cid in ci) + cid.SetValue(rtt, new CustomOrderDefinition { Limit = new LimitOrderDefinition() }); prop.SetValue(custom, rtt); } } @@ -112,11 +116,6 @@ namespace mbts.spark desc.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName; } - protected override IEnumerable get_selector_datum() - { - return OrderDataHelper.get_child_algo_data(_algo_type); - } - GenericOrderParamVM _mk_param_vm(FieldDescriptor descriptor) { ExceptionAssert.Argument.NotNull(descriptor, nameof(descriptor)); diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index f5dc590c9..34ece4c80 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1167,7 +1167,7 @@ - + - + - + - + - + - + + Text="{Binding descriptor.Name, Converter={x:Static ut:DisplayNameHelper.SnakeToTitleCaseConverter}}"/> From 717c90867aebeab89d3962bd0554e0cff87626ea Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 29 May 2019 15:08:14 -0400 Subject: [PATCH 20/27] fixed multiple child case, thanks Eric --- .../Trading/AlgoStudio/VM/AlgoDefinitionVM.cs | 3 ++ src/client/spark/Orders/OrderDataHelper.cs | 6 ++- .../Orders/OrderTypeVMs/GenericOrderVM.cs | 6 +++ .../spark/Orders/OrderTypeVMs/IOrderTypeVM.cs | 1 + .../Orders/OrderTypeVMs/OrderTypeVMFactory.cs | 2 + .../Order/AlgoContentTemplateSelector.xaml | 2 +- .../orders/algo/algo_orders/ProRataAlgo.cpp | 50 ------------------- .../orders/algo/algo_orders/ScratchAlgo.cpp | 23 --------- 8 files changed, 18 insertions(+), 75 deletions(-) diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs index 7ec794043..55f88e7c2 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs @@ -51,6 +51,9 @@ namespace mbts.spark { readonly Property _selected_format; readonly EnumMaskInt32 _permissions_mask = new EnumMaskInt32(); + mbts.ui.spark.AlgoContentTemplateSelector.OrderKind IAlgoSelector.order_kind => + new mbts.ui.spark.AlgoContentTemplateSelector.OrderKind(string.Empty, string.Empty); + int? _favorite_index; Brush _badge_fill; Snapshot? _committed; diff --git a/src/client/spark/Orders/OrderDataHelper.cs b/src/client/spark/Orders/OrderDataHelper.cs index af4fd93ec..8b5c25c0a 100644 --- a/src/client/spark/Orders/OrderDataHelper.cs +++ b/src/client/spark/Orders/OrderDataHelper.cs @@ -26,7 +26,11 @@ namespace mbts.spark.utilities { public readonly Func get_child; public readonly Action assign_child; - public ChildAlgoData(string name, Func get_child_from_impl, Action assign_child_to_impl, Func get_child, Action assign_child) { + public ChildAlgoData(string name, Func get_child_from_impl, + Action assign_child_to_impl, + Func get_child, + Action assign_child) + { this.name = name; this.get_child = get_child; this.assign_child = assign_child; diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs index dd5117dfd..b8a128520 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs @@ -116,6 +116,12 @@ namespace mbts.spark desc.MessageType.FullName == typeof(bts.spark.QuantityMeasure).FullName; } + protected override IEnumerable get_selector_datum() + { + var v = OrderDataHelper.get_child_algo_data(_algo_type); + return v; + } + GenericOrderParamVM _mk_param_vm(FieldDescriptor descriptor) { ExceptionAssert.Argument.NotNull(descriptor, nameof(descriptor)); diff --git a/src/client/spark/Orders/OrderTypeVMs/IOrderTypeVM.cs b/src/client/spark/Orders/OrderTypeVMs/IOrderTypeVM.cs index 8fd3dfcf6..a8fb64efe 100644 --- a/src/client/spark/Orders/OrderTypeVMs/IOrderTypeVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/IOrderTypeVM.cs @@ -92,6 +92,7 @@ namespace mbts.spark { IReadOnlyObservableCollection algos_view { get; } IAlgoVM selected_algo { get; set; } void load_algo_data(IReadOnlyDictionary algo_data, AlgoKey? default_algo); + mbts.ui.spark.AlgoContentTemplateSelector.OrderKind order_kind {get;} } static class OrderTypeVMExtensions { diff --git a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs index ed4ba86db..7ce192ead 100644 --- a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs +++ b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs @@ -954,6 +954,8 @@ namespace mbts.spark { public string id { get; } public string display_name { get; } + public mbts.ui.spark .AlgoContentTemplateSelector.OrderKind order_kind => + new mbts.ui.spark.AlgoContentTemplateSelector.OrderKind(display_name, string.Empty); public bool is_enabled { get; set; } = true; public bool initialized { get; private set; } diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index 34ece4c80..56a66b77b 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1299,7 +1299,7 @@ SelectedItem="{Binding selected_algo}" CanEditStructure="{Binding DataContext.editing_permissions, Converter={StaticResource CanEditStructureConverter}, RelativeSource={RelativeSource AncestorType=ItemsControl}}" ContentTemplateSelector="{DynamicResource AlgoTemplateSelector}" - OrderKind="{x:Static usp:AlgoContentTemplateSelector.ChildKind}" + OrderKind="{Binding order_kind}" OrderKindTemplate="{StaticResource OrderKindTemplate}" /> diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 96b7aa52e..00a39730c 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -63,56 +63,6 @@ ProRataAlgo::ProRataAlgo() : me(new PImpl()) {} ProRataAlgo::~ProRataAlgo() {} IAlgoServices &ProRataAlgo::algo() const { return *me->algo; } -// template -// T convert_from_dynamic(const T& orig) -// { -// T newt = orig; -// if(has_custom(orig) && custom(orig).has_dynamic()) -// { -// const DynamicOrderDefinition& dprorata = custom(orig).dynamic(); -// auto& prorata = *mutable_custom(newt).mutable_prorata(); - -// if(dprorata.order_params().count("hedge_ticks") > 0) -// prorata.set_hedge_ticks(dprorata.order_params().at("hedge_ticks").as_uint32()); -// prorata.set_hedge_ticks(std::max(1u, prorata.hedge_ticks())); - -// if(dprorata.order_params().count("chase_ticks") > 0) -// prorata.set_chase_ticks(dprorata.order_params().at("chase_ticks").as_uint32()); - -// if(dprorata.order_params().count("fill_limit") > 0) -// *prorata.mutable_fill_limit() = dprorata.order_params().at("fill_limit").as_quantity(); -// if(!prorata.has_fill_limit() || -// prorata.fill_limit().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) -// prorata.mutable_fill_limit()->set_absolute(1u); - -// if(dprorata.order_params().count("stay_in_threshold") > 0) -// *prorata.mutable_stay_in_threshold() = dprorata.order_params().at("stay_in_threshold").as_quantity(); -// if(!prorata.has_stay_in_threshold() || -// prorata.stay_in_threshold().quantity_case() == bts::spark::QuantityMeasure::QuantityCase::QUANTITY_NOT_SET) -// prorata.mutable_stay_in_threshold()->set_absolute(1u); - -// if(dprorata.order_params().count("enable_scratch_on_overfill") > 0) -// prorata.set_enable_scratch_on_overfill(dprorata.order_params().at("enable_scratch_on_overfill").as_bool()); -// if(dprorata.order_params().count("enable_stay_in") > 0) -// prorata.set_enable_stay_in(dprorata.order_params().at("enable_stay_in").as_bool()); - -// if(dprorata.order_params().count("child") > 0) -// *prorata.mutable_child() = dprorata.order_params().at("child").as_order_def(); -// else -// prorata.mutable_child()->mutable_limit(); - -// if(dprorata.order_params().count("hedge") > 0) -// *prorata.mutable_hedge() = dprorata.order_params().at("hedge").as_order_def(); -// else -// prorata.mutable_hedge()->mutable_limit(); - -// if(dprorata.order_params().count("overfill_hedge") > 0) -// *prorata.mutable_overfill_hedge() = dprorata.order_params().at("overfill_hedge").as_order_def(); -// else -// prorata.mutable_overfill_hedge()->mutable_limit(); -// } -// return newt; -// } OrderOpResult ProRataAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 2bb3b56ad..9d9af6b98 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -33,29 +33,6 @@ ScratchAlgo::ScratchAlgo() : me(new PImpl()) {} ScratchAlgo::~ScratchAlgo() {} IAlgoServices &ScratchAlgo::algo() const { return *me->algo; } -// template -// T convert_from_dynamic(const T& orig) -// { -// T newt = orig; -// if ( has_custom(orig) && custom(orig).has_dynamic()) -// { -// const DynamicOrderDefinition& dscratch = custom(orig).dynamic(); -// auto& scratch = *mutable_custom(newt).mutable_scratch(); - -// if(dscratch.order_params().count("scratch_threshold") > 0) -// *scratch.mutable_scratch_threshold() = dscratch.order_params().at("scratch_threshold").as_quantity(); - -// if(dscratch.order_params().count("chase_ticks") > 0) -// scratch.set_chase_ticks(dscratch.order_params().at("chase_ticks").as_uint32()); - -// if(dscratch.order_params().count("child") > 0) -// *scratch.mutable_child() = dscratch.order_params().at("child").as_order_def(); -// else -// scratch.mutable_child()->mutable_limit(); -// } -// return newt; -// } - OrderOpResult ScratchAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { const auto& def = serv.definition(); From 3d11aba8ef9ee12c1539d462d437c2d24ef5b3f3 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 29 May 2019 15:35:47 -0400 Subject: [PATCH 21/27] fix build from merge --- src/lib/CMakeDeps_win.cmake | 2 +- src/lib/api/services/OrderService.proto | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib/CMakeDeps_win.cmake b/src/lib/CMakeDeps_win.cmake index c332cbc98..39c84c8bb 100644 --- a/src/lib/CMakeDeps_win.cmake +++ b/src/lib/CMakeDeps_win.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/thread_manager.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index e45314190..235b49171 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -101,8 +101,8 @@ message CustomOrderDefinition OCOOrderDefinition oco = 25; PricerOrderDefinition pricer = 26; CompositeOrderDefinition composite = 27; - ScratchOrderDefinition scratch = 28; - ProRataOrderDefinition prorata = 29; + ScratchOrderDefinition scratch = 31; + ProRataOrderDefinition prorata = 32; DynamicOrderDefinition dynamic = 1000; } @@ -272,8 +272,8 @@ message OrderState { QueueHolderState queue_holder = 30; OCOOrderState oco = 25; PricerOrderState pricer = 26; - ScratchOrderState scratch = 27; - ProRataOrderState prorata = 28; + ScratchOrderState scratch = 31; + ProRataOrderState prorata = 32; DynamicOrderState dynamic = 255; // do not use anything bigger than 255, or things will break } From d8559276d04c12aff67715e1b729bc0b4cec18a9 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 29 May 2019 16:55:11 -0400 Subject: [PATCH 22/27] test case for scratchalgo --- .../orders/algo/algo_orders/ScratchAlgo.cpp | 14 +++--- testing/manual/algos/scratch_controlled.txt | 48 +++++++++++++++++++ 2 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 testing/manual/algos/scratch_controlled.txt diff --git a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp index 9d9af6b98..d2645d7a1 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ScratchAlgo.cpp @@ -146,16 +146,16 @@ void ScratchAlgo::try_to_scratch() Quantity my_quan; auto &my_side_psz = me->last_book.side(my_side)[0]; auto &other_side_psz = me->last_book.side(other_side)[0]; - bool market_moved = !securities::is_equal_or_better(other_side, - Price(other_side_psz.price()), Price(me->book_at_inception.side(other_side)[0].price())); + auto other_side_price = Price(other_side_psz.price()); + auto inception_other_side_price = Price(me->book_at_inception.side(other_side)[0].price()); + + bool market_moved = !securities::is_equal_or_better(other_side, other_side_price, inception_other_side_price); bool on_market = securities::is_same(Price(my_side_psz.price()), Price(algo().price())); if (market_moved || (on_market && my_side_psz.size() <= me->scratch_threshold.value()) ) { - Price scratch_price; - Quantity scratch_quan; - SpreaderUtils::traverse_depth_for_quantity(me->last_book, other_side, algo().quantity(), scratch_price, scratch_quan); - LOG(OrderMan, Diag, "ScratchOrder order {} scratching: {}@{} {}", - algo().order_key().value(), algo().quantity().value(), scratch_price, scratch_quan); + Price scratch_price = securities::worsen_price(other_side, inception_other_side_price, me->chase_diff); + LOG(OrderMan, Diag, "ScratchOrder order {} scratching: {}@{}", + algo().order_key().value(), algo().quantity().value(), scratch_price); // Time to scratch Update child_update; diff --git a/testing/manual/algos/scratch_controlled.txt b/testing/manual/algos/scratch_controlled.txt new file mode 100644 index 000000000..0d8740cb4 --- /dev/null +++ b/testing/manual/algos/scratch_controlled.txt @@ -0,0 +1,48 @@ +Test Author: Kevin +If it breaks: Kevin + +When the scratch order is placed, it takes a snapshot of the opposite inside market; if that level gets +worse, it will cross the market chase_ticks through. + +It also continually monitors the size on the same side of the market if the quantity at that (same side) level falls below the "Scratch Threshold" AND the order's price is equal to the best bid or offer. It will cross by chase_ticks. + +0. This needs sim market data **not** to be merged with replay (or +cert), so we can create our own markets. Use the following key to set +market data up: + +ExchangeSim { + value { + merge_with_md: false + } +} + +1. Bring up a ladder, lets say in SIM:ESU9 (does not matter which security) + +2. Create the ask side of the market by sending 50 lot sell limit orders at 2833.25 through 2832.25 +(if there are no markets use the M View and the ticket to enter, if you already had left over +orders cancel them) + +2. Create the bid side of the market by sending 50 lot buy limit orders at 2830.50 through 2831.50. +You should have no orders at 2831.75 and 2832. + +Basics: +3. Enter a 20 lot buy scratch order at 2831.50 with the following parameters +Scratch Threshold = Absolute:21 +Max Chase Ticks = 2 +Child = Limit +Verify that the Lean order along with the Child order shows up + +4) Now cancel the 50 lot sell at 2832.25, you should see the 20 lot scratch pay 2832.50 on 20 + +5) Repeat 3, now cancel the 50 lot buy at 2831.50, you should again see scratch pay 2832.50 on 20. +Put the 50 lot buy back in. + +6) Repeat 3, put an offer in at 2832.25, cancel it; nothing should happen. Cancel the Scratch Algo + +7) This time enter the algo with Max Chase = 0, cancel the 50 lot offer at 2832.75 and 2833. Nothing should happen. Now cancel the 2832.5 offer, you should see the algo pay up to 2832.5, but not fill. + +8) Cancel the last offer at 2833.25. Nothing should happen. + +9) Repeat all of this on the sell side + + From 5b818bf276ecd64629ec5955cee81795e16e842e Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 29 May 2019 17:43:05 -0400 Subject: [PATCH 23/27] test for prorata order --- .../orders/algo/algo_orders/ProRataAlgo.cpp | 1 + testing/manual/algos/pro_rata_controlled.txt | 87 +++++++++++++++++++ testing/manual/algos/scratch_controlled.txt | 9 +- 3 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 testing/manual/algos/pro_rata_controlled.txt diff --git a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp index 00a39730c..bebd90879 100644 --- a/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/ProRataAlgo.cpp @@ -187,6 +187,7 @@ void ProRataAlgo::scratch(std::pair kk) Price scratch_price; Quantity scratch_quan; SpreaderUtils::traverse_depth_for_quantity(me->last_book, cross_side, kk.second, scratch_price, scratch_quan); + //Quantity scratch_quan = Price(me->book_at_inception.side(other_side)[0].price()) scratch_price = securities::worsen_price(cross_side, scratch_price, me->chase_diff); Update update; diff --git a/testing/manual/algos/pro_rata_controlled.txt b/testing/manual/algos/pro_rata_controlled.txt new file mode 100644 index 000000000..b9ea169e6 --- /dev/null +++ b/testing/manual/algos/pro_rata_controlled.txt @@ -0,0 +1,87 @@ +Test Author: Kevin +If it breaks: Kevin + +When the prorata order is placed, it acts as a slightly more complex hedging algorithm than Cover. +It will: + - Classify each fill as a normal fill or an 'overfill' according to "Fill Limit" parameters + - Standard fills are hedged with the "Hedge" child order + - Over fills are hedge with the "Overfill Hedge" child order + +The prorata order works the child until the Fill Limit is breached. +Once the fill limit is breached, the algo will begin the 'get out process' +Unless: + - If "Enable Stay In" is checked, AND + a) The opposite inside market (at inception) doesn't move against us AND + b) The same side quantity remains ABOVE the "Stay in Threshold" +If "Enable Stay In" is not checked, 'get out process' begins right away + +"Get Out Process" means + 1) Cancel the child order + 2) Scratch the overfill hedges if and only if the "Enable Scratch on Overfill" is checked + -Scratches are done "Chase Ticks" through the original opposite market + + +0. This needs sim market data **not** to be merged with replay (or +cert), so we can create our own markets. Use the following key to set +market data up: + +ExchangeSim { + value { + merge_with_md: false + } +} + +1. Bring up a ladder, lets say in SIM:ESU9 (does not matter which security) + +2. Create the ask side of the market by sending 50 lot sell limit orders at 2833.25 through 2832.25 +(if there are no markets use the M View and the ticket to enter, if you already had left over +orders cancel them) + +2. Create the bid side of the market by sending 50 lot buy limit orders at 2830.75 through 2831.50. +You should have no orders at 2831.50, 2831.75 and 2832. + +Basics: +3. Enter a 20 lot buy prorata order at 2831.50 with the following parameters + + Hedge Ticks = 1 + Chase Ticks = 1 + Fill Limit = Absolute:5 + Stay in Threshold = Absolute:21 + Enable Scratch on Overfill = true + Enable Stay In = true + +Verify that the Prorata order along with the Child order shows up. + +Next put a 50 lot buy limit order on top of your prorata at 2831.50 + + +4) Using 1 lot limit sells, fill 5 of your prorata order. Verify that you see covers going in 1 tick better + +5) Cancel the 50 lot limit at 2831.50. Nothing should happen. Put the 50 lot back. + +6) Fill one more 1 lot. + +7) Again cancel the 50 lot limit at 2831.50. You should see: + - The remainder of the 20 lot should cancel + - 1 lot of your hedges should scratch to sell at 2831.25 + - The parent order should stay in + - You should still be working 5 sales for hedges + +8) Fill the 5 sells, it should cancel the parent. + +9) Repeat 3-8, but this time set Enable Scratch on Overfill = false, Enable Stay In = true + - You should see the same results in 7, except the 1 lot scratch won't happen so you'll still have 6 working hedges + +9) Repeat 3-6, but this time set Enable Scratch on Overfill = false, Enable Stay In = false + - After filling your last lot in 1 you should see your working order cancel, with 6 hedges working + - The ladder may deceive you here, check the OB + - Cancel your hedges, this should cancel the whole chain + +9) Repeat 3-6, but this time set Enable Scratch on Overfill = true, Enable Stay In = false + - After filling your last lot in 1 you should see your working order cancel, one hedge scratch (at 2831.50), and 5 hedges working + - The ladder may deceive you here, check the OB + - Cancel your hedges, this should cancel the whole chain + +10) Repeat all of this on the sell side + + diff --git a/testing/manual/algos/scratch_controlled.txt b/testing/manual/algos/scratch_controlled.txt index 0d8740cb4..e711374a2 100644 --- a/testing/manual/algos/scratch_controlled.txt +++ b/testing/manual/algos/scratch_controlled.txt @@ -27,10 +27,11 @@ You should have no orders at 2831.75 and 2832. Basics: 3. Enter a 20 lot buy scratch order at 2831.50 with the following parameters -Scratch Threshold = Absolute:21 -Max Chase Ticks = 2 -Child = Limit -Verify that the Lean order along with the Child order shows up + Scratch Threshold = Absolute:21 + Max Chase Ticks = 2 + Child = Limit + + Verify that the Scratch order along with the Child order shows up 4) Now cancel the 50 lot sell at 2832.25, you should see the 20 lot scratch pay 2832.50 on 20 From 9eb76bdfbcc6c888eb8df9f27043779d05672359 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 23 Jul 2019 10:42:41 -0400 Subject: [PATCH 24/27] Fix prorata build --- .gitignore | 1 + src/web/api/package-lock.json | 91 ++++++++++++++++++++++++--------- src/web/ui/src/Access.fs | 6 +-- src/web/ui/src/Accounts/View.fs | 6 +-- 4 files changed, 74 insertions(+), 30 deletions(-) diff --git a/.gitignore b/.gitignore index cf4c7c358..70c62ec28 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ trace_data/ /src/lib/orderman/perf_analysis/log.csv /doc/user/public/* .ionide/* +src/web/ui/.ionide/symbolCache.db diff --git a/src/web/api/package-lock.json b/src/web/api/package-lock.json index f923270ae..29e3dec15 100644 --- a/src/web/api/package-lock.json +++ b/src/web/api/package-lock.json @@ -132,6 +132,7 @@ "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", "dev": true, + "optional": true, "requires": { "kind-of": "^3.0.2", "longest": "^1.0.1", @@ -1832,7 +1833,8 @@ "ansi-regex": { "version": "2.1.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "aproba": { "version": "1.1.1", @@ -1883,7 +1885,8 @@ "balanced-match": { "version": "0.4.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "bcrypt-pbkdf": { "version": "1.0.1", @@ -1898,6 +1901,7 @@ "version": "0.0.9", "bundled": true, "dev": true, + "optional": true, "requires": { "inherits": "~2.0.0" } @@ -1906,6 +1910,7 @@ "version": "2.10.1", "bundled": true, "dev": true, + "optional": true, "requires": { "hoek": "2.x.x" } @@ -1914,6 +1919,7 @@ "version": "1.1.7", "bundled": true, "dev": true, + "optional": true, "requires": { "balanced-match": "^0.4.1", "concat-map": "0.0.1" @@ -1922,7 +1928,8 @@ "buffer-shims": { "version": "1.0.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "caseless": { "version": "0.12.0", @@ -1939,12 +1946,14 @@ "code-point-at": { "version": "1.1.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "combined-stream": { "version": "1.0.5", "bundled": true, "dev": true, + "optional": true, "requires": { "delayed-stream": "~1.0.0" } @@ -1952,22 +1961,26 @@ "concat-map": { "version": "0.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "core-util-is": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "cryptiles": { "version": "2.0.5", "bundled": true, "dev": true, + "optional": true, "requires": { "boom": "2.x.x" } @@ -2007,7 +2020,8 @@ "delayed-stream": { "version": "1.0.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "delegates": { "version": "1.0.0", @@ -2039,7 +2053,8 @@ "extsprintf": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "forever-agent": { "version": "0.6.1", @@ -2061,12 +2076,14 @@ "fs.realpath": { "version": "1.0.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "fstream": { "version": "1.0.11", "bundled": true, "dev": true, + "optional": true, "requires": { "graceful-fs": "^4.1.2", "inherits": "~2.0.0", @@ -2122,6 +2139,7 @@ "version": "7.1.2", "bundled": true, "dev": true, + "optional": true, "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -2134,7 +2152,8 @@ "graceful-fs": { "version": "4.1.11", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "har-schema": { "version": "1.0.5", @@ -2162,6 +2181,7 @@ "version": "3.1.3", "bundled": true, "dev": true, + "optional": true, "requires": { "boom": "2.x.x", "cryptiles": "2.x.x", @@ -2172,7 +2192,8 @@ "hoek": { "version": "2.16.3", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "http-signature": { "version": "1.1.1", @@ -2189,6 +2210,7 @@ "version": "1.0.6", "bundled": true, "dev": true, + "optional": true, "requires": { "once": "^1.3.0", "wrappy": "1" @@ -2197,7 +2219,8 @@ "inherits": { "version": "2.0.3", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "ini": { "version": "1.3.4", @@ -2209,6 +2232,7 @@ "version": "1.0.0", "bundled": true, "dev": true, + "optional": true, "requires": { "number-is-nan": "1.0.1" } @@ -2222,7 +2246,8 @@ "isarray": { "version": "1.0.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "isstream": { "version": "0.1.2", @@ -2295,12 +2320,14 @@ "mime-db": { "version": "1.27.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "mime-types": { "version": "2.1.15", "bundled": true, "dev": true, + "optional": true, "requires": { "mime-db": "1.27.0" } @@ -2309,6 +2336,7 @@ "version": "3.0.4", "bundled": true, "dev": true, + "optional": true, "requires": { "brace-expansion": "1.1.7" } @@ -2316,12 +2344,14 @@ "minimist": { "version": "0.0.8", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "mkdirp": { "version": "0.5.1", "bundled": true, "dev": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -2376,7 +2406,8 @@ "number-is-nan": { "version": "1.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "oauth-sign": { "version": "0.8.2", @@ -2394,6 +2425,7 @@ "version": "1.4.0", "bundled": true, "dev": true, + "optional": true, "requires": { "wrappy": "1" } @@ -2423,7 +2455,8 @@ "path-is-absolute": { "version": "1.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "performance-now": { "version": "0.2.0", @@ -2434,7 +2467,8 @@ "process-nextick-args": { "version": "1.0.7", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "punycode": { "version": "1.4.1", @@ -2472,6 +2506,7 @@ "version": "2.2.9", "bundled": true, "dev": true, + "optional": true, "requires": { "buffer-shims": "~1.0.0", "core-util-is": "~1.0.0", @@ -2516,6 +2551,7 @@ "version": "2.6.1", "bundled": true, "dev": true, + "optional": true, "requires": { "glob": "^7.0.5" } @@ -2523,7 +2559,8 @@ "safe-buffer": { "version": "5.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "semver": { "version": "5.3.0", @@ -2547,6 +2584,7 @@ "version": "1.0.9", "bundled": true, "dev": true, + "optional": true, "requires": { "hoek": "2.x.x" } @@ -2580,6 +2618,7 @@ "version": "1.0.2", "bundled": true, "dev": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -2590,6 +2629,7 @@ "version": "1.0.1", "bundled": true, "dev": true, + "optional": true, "requires": { "safe-buffer": "^5.0.1" } @@ -2604,6 +2644,7 @@ "version": "3.0.1", "bundled": true, "dev": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -2618,6 +2659,7 @@ "version": "2.2.1", "bundled": true, "dev": true, + "optional": true, "requires": { "block-stream": "*", "fstream": "^1.0.2", @@ -2673,7 +2715,8 @@ "util-deprecate": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "uuid": { "version": "3.0.1", @@ -2702,7 +2745,8 @@ "wrappy": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true } } }, @@ -4011,7 +4055,8 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", - "dev": true + "dev": true, + "optional": true }, "loose-envify": { "version": "1.3.1", diff --git a/src/web/ui/src/Access.fs b/src/web/ui/src/Access.fs index 935e66560..7ff47b329 100644 --- a/src/web/ui/src/Access.fs +++ b/src/web/ui/src/Access.fs @@ -111,10 +111,8 @@ module Accounts = } } riskLimitEnforcement = - { productLimitInNetTerms = true - } - accountLossLimit = - { + { productLimitInNetTerms = true } + accountLossLimit = { enforce = false totalLossLimit = 0u } diff --git a/src/web/ui/src/Accounts/View.fs b/src/web/ui/src/Accounts/View.fs index 73d8aff1e..2f0b5db66 100644 --- a/src/web/ui/src/Accounts/View.fs +++ b/src/web/ui/src/Accounts/View.fs @@ -611,7 +611,7 @@ let lazyProductLimitsView model dispatch = productLimits model dispatch -let lossLimitView model dispatch = +let lossLimitView (model:Model) dispatch = div [] [ div [ ClassName "columns" ][ h1 [ ClassName "is-size-3 column is-narrow" ][str "Loss Limit" ] @@ -624,7 +624,7 @@ let lossLimitView model dispatch = ] ] -let securityLimitsView model dispatch = +let securityLimitsView (model:Model) dispatch = let headerRow:TableControl.row = { cells = @@ -740,7 +740,7 @@ let securityLimitsView model dispatch = TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus-circle" Button.Enabled addRow) ] -let LimitsView model dispatch = +let LimitsView (model:Model) dispatch = div [ Class "limits-container"] [ lossLimitView model dispatch br [] From 2a16ac77fbbe7c5663f85496b013becbfd84fcdf Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 23 Jul 2019 10:45:11 -0400 Subject: [PATCH 25/27] Clean up some indentation warnings --- src/web/ui/src/Access.fs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/web/ui/src/Access.fs b/src/web/ui/src/Access.fs index 7ff47b329..7cce85068 100644 --- a/src/web/ui/src/Access.fs +++ b/src/web/ui/src/Access.fs @@ -112,16 +112,16 @@ module Accounts = } riskLimitEnforcement = { productLimitInNetTerms = true } - accountLossLimit = { - enforce = false - totalLossLimit = 0u - } + accountLossLimit = + { enforce = false + totalLossLimit = 0u } } let emptyMargin : ExcessLiquidityReport = { account = "ERROR NO DATA" accountId = 0u - marginResult = { + marginResult = + { account = "ERROR NO DATA" status = bts.api.position.MarginResult.ResultStatus.Error portfolioId = "" @@ -137,11 +137,10 @@ module Accounts = shouldEnforceMargin = false leverageFactor = 0.0 cashBalance = 0.0 - accountPnl = { - accountId = 0u - accountName = "" - dayPnl = 0.0 - } + accountPnl = + { accountId = 0u + accountName = "" + dayPnl = 0.0 } excessLiquidity = 0.0 } From 16d5341285d7dd56255465032c539aae581ab778 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 23 Jul 2019 11:17:15 -0400 Subject: [PATCH 26/27] Remove unused messages (warnings) --- src/web/ui/src/Accounts/Types.fs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/web/ui/src/Accounts/Types.fs b/src/web/ui/src/Accounts/Types.fs index 5536dae53..21d38d90b 100644 --- a/src/web/ui/src/Accounts/Types.fs +++ b/src/web/ui/src/Accounts/Types.fs @@ -62,8 +62,6 @@ type Msg = | SelectAccount of BTSAccount | DeleteAccount of BTSAccount | AddAccount - | SaveLeverageFactor - | SaveCashBalance | SaveScratch | ErrorOccured of obj From 94e77ce2b848e183172f0ead116ddc4ad03ea144 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Thu, 1 Aug 2019 09:56:54 -0400 Subject: [PATCH 27/27] fix merge --- src/client/spark/Orders/OrderDataHelper.cs | 2 +- src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client/spark/Orders/OrderDataHelper.cs b/src/client/spark/Orders/OrderDataHelper.cs index 093b1ea0a..ff350c1e0 100644 --- a/src/client/spark/Orders/OrderDataHelper.cs +++ b/src/client/spark/Orders/OrderDataHelper.cs @@ -634,7 +634,7 @@ namespace mbts.spark.utilities { CustomOrderDefinition.CustomOneofCase.Join, CustomOrderDefinition.CustomOneofCase.Cover, CustomOrderDefinition.CustomOneofCase.Top, - CustomOrderDefinition.CustomOneofCase.Offset + CustomOrderDefinition.CustomOneofCase.Offset, CustomOrderDefinition.CustomOneofCase.Scratch, CustomOrderDefinition.CustomOneofCase.Prorata, }, diff --git a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs index b8a128520..45d13e78a 100644 --- a/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/GenericOrderVM.cs @@ -100,7 +100,7 @@ namespace mbts.spark if (model != null) { Google.Protobuf.Reflection.MessageDescriptor desc = new TMutable().Descriptor; - _parameters.SyncWithDictionaryNotNull( + _parameters.SyncWithDictionary( desc.Fields.InDeclarationOrder().Where(_is_value_param_desc).ToDictionary(p => p.Name), _mk_param_vm); } }