From 73f4e4814cfe0808548f682234fa290e06b52f42 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 12 May 2020 13:27:16 -0500 Subject: [PATCH] LimitCover algo for pure --- src/lib/orderman/orderman_utils/BookUtils.cpp | 26 ++ src/lib/orderman/orderman_utils/BookUtils.h | 18 + src/lib/orderman/orderman_utils/PriceComp.h | 32 ++ .../algo/algo_orders/LimitCoverAlgo.cpp | 412 ++++++++++++++++++ .../orders/algo/algo_orders/LimitCoverAlgo.h | 95 ++++ .../limit_cover/LimitCoverAdapter.cpp | 162 +++++++ .../limit_cover/LimitCoverAdapter.h | 15 + .../limit_cover/LimitCoverDefinition.h | 71 +++ .../algo_orders/limit_cover/LimitCoverGate.h | 90 ++++ 9 files changed, 921 insertions(+) create mode 100644 src/lib/orderman/orderman_utils/BookUtils.cpp create mode 100644 src/lib/orderman/orderman_utils/BookUtils.h create mode 100644 src/lib/orderman/orderman_utils/PriceComp.h create mode 100644 src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.cpp create mode 100644 src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h create mode 100644 src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.cpp create mode 100644 src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h create mode 100644 src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h create mode 100644 src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h diff --git a/src/lib/orderman/orderman_utils/BookUtils.cpp b/src/lib/orderman/orderman_utils/BookUtils.cpp new file mode 100644 index 000000000..d76874e97 --- /dev/null +++ b/src/lib/orderman/orderman_utils/BookUtils.cpp @@ -0,0 +1,26 @@ +#include "BookUtils.h" + +namespace bts { +namespace orderman { +using Size = bts::md::Size; +using Side = bts::api::Side; + +Size BookUtils::volume_at_or_better(const Book& book, Side side, Price price) { + return volume_at_or_better(book, side, price.value()); +} +Size BookUtils::volume_at_or_better(const Book& book, Side side, double price) { + Size volume = 0; + SidePriceComp spc(side); + for (const auto& plevel : book.side(side)) { + if (spc(price, plevel.price())) + break; + volume += plevel.size(); + } + return volume; +} + +SidePriceComp BookUtils::price_comp(Side side) { + return SidePriceComp(side); +} +} // namespace orderman +} // namespace bts \ No newline at end of file diff --git a/src/lib/orderman/orderman_utils/BookUtils.h b/src/lib/orderman/orderman_utils/BookUtils.h new file mode 100644 index 000000000..668349ae9 --- /dev/null +++ b/src/lib/orderman/orderman_utils/BookUtils.h @@ -0,0 +1,18 @@ +#pragma once +#include "lib/api/services/OrderService.pb.h" +#include "lib/config/protos/MarketData.pb.h" +#include "lib/domain_model/Security.h" +#include "lib/domain_model/common.h" +#include "lib/orderman/orderman_utils/Book.h" +#include "lib/orderman/orderman_utils/PriceComp.h" + +namespace bts { +namespace orderman { + +struct BookUtils { + static md::Size volume_at_or_better(const Book& book, api::Side side, Price price); + static md::Size volume_at_or_better(const Book& book, api::Side side, double price); + static SidePriceComp price_comp(api::Side side); +}; +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orderman_utils/PriceComp.h b/src/lib/orderman/orderman_utils/PriceComp.h new file mode 100644 index 000000000..649453d0b --- /dev/null +++ b/src/lib/orderman/orderman_utils/PriceComp.h @@ -0,0 +1,32 @@ +#pragma once +#include "lib/domain_model/Security.h" + +namespace bts { +namespace orderman { +struct PriceComp { + bool operator()(const Price& lhs, const Price& rhs) { return lhs.value() > rhs.value(); } + bool operator()(const double& lhs, const double& rhs) { return lhs > rhs; } +}; + +struct ReversePriceComp { + bool operator()(const Price& lhs, const Price& rhs) { return lhs.value() < rhs.value(); } + bool operator()(const double& lhs, const double& rhs) { return lhs < rhs; } +}; + +struct SidePriceComp { + SidePriceComp(api::Side side) : _side(side) {} + + api::Side side() const { return _side; } + + bool operator()(const Price& lhs, const Price& rhs) { + return _side == api::SIDE_SELL ? lhs.value() < rhs.value() : lhs.value() > rhs.value(); + } + + bool operator()(const double& lhs, const double& rhs) { + return _side == api::SIDE_SELL ? lhs < rhs : lhs > rhs; + } +private: + api::Side _side; +}; +} // namespace orderman +} // namespace bts \ No newline at end of file diff --git a/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.cpp new file mode 100644 index 000000000..bedce093b --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.cpp @@ -0,0 +1,412 @@ +#include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h" +#include "lib/sparkproto/SparkProtos.pb.h" +#include "lib/api/services/OrderService.pb.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orderman_utils/orderman_utils.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include "lib/orderman/orders/algo/utils/DynamicOrderAdapter.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h" +#include +#include +#include +#include + +#define DEFAULT_LOG_LEVEL Info + +#define SUMMARIZE_TRANSACTION_BEGIN(id, type, ...) Summary __LOG_TRANS(this, id, Formatter::fmt(__VA_ARGS__), type, DEFAULT_LOG_LEVEL) + +#define SUMMARIZE_TRANSACTION(id, type) Summary __LOG_TRANS(this, id, "", type, DEFAULT_LOG_LEVEL) +#define SUMMARIZE SUMMARIZE_TRANSACTION(__FUNCTION__, SummaryType::StatusChange) + +// define 'PRINT_SUMMARIES' to print all logs to the console +// (assuming logs are made with the MSG/MSG_LEVEL macros) +#ifdef PRINT_SUMMARIES +#define _PRINT_MSG(x) std::cout << x << std::endl; +#else +#define _PRINT_MSG(x) +#endif + +#define _MSG(level, msg) \ + _PRINT_MSG(msg); \ + LOG(OrderMan, level, "{}", msg) + +#define MSG_LEVEL(level, ...) _MSG(level, (Formatter::fmt(__VA_ARGS__))) +// these automatically prepend log_header() to the args +#define MSG(...) MSG_LEVEL(DEFAULT_LOG_LEVEL, log_header(), " ", __VA_ARGS__) +#define DIAG(...) MSG_LEVEL(Diag, log_header(), " ", __VA_ARGS__) +#define INFO(...) MSG_LEVEL(Info, log_header(), " ", __VA_ARGS__) +#define WARN(...) MSG_LEVEL(Warn, log_header(), " ", __VA_ARGS__) +#define ERROR(...) MSG_LEVEL(Error, log_header(), " ", __VA_ARGS__) + +namespace bts { +namespace orderman { +using namespace api::orderman; +using namespace bts::orderman::limit_cover::utils; +using Adapter = bts::orderman::LimitCoverAdapter; + +namespace limit_cover { +namespace utils { +void init_delete_and_cover(OrderDefinition& target, const DeleteAndCoverDefinition& def) { + if (!target.has_custom_def()) + *target.mutable_custom_def() = CustomOrderDefinition(); + init_delete_and_cover(*target.mutable_custom_def(), def); +} + +void init_delete_and_cover(CustomOrderDefinition& target, const DeleteAndCoverDefinition& def) { + if (!target.has_delete_and_cover()) { + *target.mutable_delete_and_cover() = DeleteAndCoverDefinition(def); + } else { + target.mutable_delete_and_cover()->CopyFrom(def); + } +} + +void init_child_update(Update& target, uint32_t qty, double price, const DeleteAndCoverDefinition& def) { + target.set_quantity(qty); + target.set_price(price); + init_delete_and_cover(*target.mutable_custom(), def); +} + +#define INVALID_DEF(x) OrderOpResult(api::orderman::ORDER_ERROR_INVALID_ORDER_DEFINITON, x) + +OrderOpResult validate_custom_def(const CustomOrderDefinition& custom_def) { + if (!custom_def.has_dynamic()) + return INVALID_DEF("DynamicOrderDefinition is undefined"); + return Adapter::validate_proto(custom_def.dynamic()); +} +OrderOpResult validate_def(const OrderDefinition& def) { + if (def.attach_target_order_key() != 0) { + return INVALID_DEF("Attach not supported."); + } else if (def.has_custom_def()) { + return validate_custom_def(def.custom_def()); + } else { + return INVALID_DEF("CustomOrderDefinition is undefined."); + } +} + +OrderOpResult validate_update(const Update& upd) { + return upd.has_custom() ? + validate_custom_def(upd.custom()) : OrderOpResult(); +} +} // namespace utils +} // namespace limit_cover + +struct LimitCoverAlgo::PImpl { + IAlgoServices *algo = nullptr; + Status status = Status::WAITING_TO_DEPLOY; + OrderKey child_key = null_order_key(); + double child_price = os::nan(); + uint32_t child_qty = 0; + Book book; + uint32_t limit_volume = 0; + std::map gates; + double settlement = os::nan(); + int tick_offset_from_settle = 0; + double limit_price = os::nan(); +}; + +struct LimitCoverAlgo::Summary { + Summary(LimitCoverAlgo* owner, std::string transaction_id, std::string begin_tag = {}, SummaryType type = SummaryType::StatusChange, log::Level level = DEFAULT_LOG_LEVEL) + : _owner(owner), _transaction_id(transaction_id), _original_status(owner->me->status), _type(type), _level(level) { + if (_owner != nullptr && !_transaction_id.empty()) { + std::stringstream str; + str << owner->log_header() << " begin " << transaction_id << "."; + if (!begin_tag.empty()) { + str << " " << begin_tag << "."; + } + if (type == SummaryType::FullState) { + str << " Algo State: " << _owner->fmt_state() << "."; + } + MSG_LEVEL(level, str.str()); + } + } + + ~Summary() { + std::stringstream msg_str; + if (!_transaction_id.empty()) { + msg_str << " end " << _transaction_id << "."; + } + switch (_type) { + case SummaryType::StatusChange: + if (_owner->me->status != _original_status) + msg_str << " Status changed from " << _original_status << " to " << _owner->me->status << "."; + break; + case SummaryType::FullState: + msg_str << " Algo State: " << _owner->fmt_state() << "."; + break; + } + auto msg = msg_str.str(); + if (!msg.empty()) { + MSG_LEVEL(_level, _owner->log_header(), msg); + } + } + + private: + LimitCoverAlgo *_owner; + std::string _transaction_id; + Status _original_status; + SummaryType _type; + log::Level _level; +}; + +LimitCoverAlgo::LimitCoverAlgo() : me(new PImpl()) {} +LimitCoverAlgo::~LimitCoverAlgo() {} + +OrderOpResult +LimitCoverAlgo::do_before_launch(IBeforeLaunchAlgoServices &balgo) { + SUMMARIZE; + bts_assert(me->status == Status::WAITING_TO_DEPLOY); + bts_assert(me->gates.empty()); + auto vd = validate_def(balgo.definition()); + if (vd.ok()) { + auto lcdef = Adapter::from_proto(balgo.definition()); + me->tick_offset_from_settle = lcdef.ticks_offset(); + me->gates = lcdef.normal_gates(); + } else { + me->status = Status::DONE; + } + return vd; +} + +void LimitCoverAlgo::do_launch(IAlgoServices& algo) { + SUMMARIZE; + bts_assert(me->status == Status::WAITING_TO_DEPLOY); + me->algo = &algo; + algo.subscribe_book(SecurityKey(algo.security().id())); + algo.subscribe_settlement(SecurityKey(algo.security().id())); +} + +void LimitCoverAlgo::do_launch_attached(IAlgoServices &, OrderKey, ChildState) { + bts_assert_msg(false, "LimitCoverAlgo does not support attach."); +} + +void LimitCoverAlgo::do_update(Update const &upd) { + SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::StatusChange, utils::pb::to_string(upd)); + auto vup = validate_update(upd); + if (!vup.ok()) { + me->status = Status::DONE; + algo().terminate_error(Formatter::fmt("Invalid update: ", vup.error_msg, ".")); + return; + } + if (upd.has_custom()) { + auto lcdef = Adapter::from_proto(upd.custom()); + if (me->status == Status::WAITING_TO_DEPLOY) { + me->tick_offset_from_settle = lcdef.ticks_offset(); + recompute_limit_price(); + recompute_limit_volume(); + } + me->gates = Adapter::from_proto(upd.custom()).normal_gates(); + if (me->status == Status::WORKING) + recompute_gate(); + } + switch (me->status) { + case Status::WAITING_TO_DEPLOY: + try_deploy(); + break; + case Status::WORKING: { + // don't change the child price; the price param is irrelevant to this algo. + if (upd.has_custom() || me->child_qty != upd.quantity()) + update_child(upd.quantity()); + break; + } + default: + break; + } +} + +void LimitCoverAlgo::on_book(SecurityKey, Book const &b) { + SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::StatusChange, "BBO: ", Formatter::to_string(b)); + me->book = b; + recompute_limit_volume(); + switch (me->status) { + case Status::WAITING_TO_DEPLOY: + try_deploy(); + break; + case Status::WORKING: { + if (recompute_gate()) + update_child(me->child_qty); + break; + } + default: + break; + } +} + +void LimitCoverAlgo::update_child(uint32_t qty) { + bts_assert(me->algo != nullptr); + bts_assert(me->status == Status::WORKING); + Update upd; + init_child_update(upd, qty, me->child_price, curr_gate().definition()); + MSG("updating algo child: ", utils::pb::to_string(upd)); + me->algo->update_child(me->child_key, upd); +} + +void LimitCoverAlgo::on_child_change(OrderKey key, ChildState const& state) { + bts_assert(key == me->child_key); + SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::FullState, "Child State: ", Formatter::to_string(state)); + algo().update_fill_state(state.total_fills, state.last_price); + me->child_price = state.price.value(); + me->child_qty = state.quantity.value(); + switch (me->status) { + case Status::WORKING: + switch (state.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::CANCELED: { + auto msg = Formatter::fmt("main child (", key, ") canceled unexpectedly."); + MSG(msg, ". ", fmt_state()); + me->status = Status::DONE; + algo().terminate_error(msg); + break; + } + case ChildStatus::COMPLETED: + me->status = Status::DONE; + algo().complete(); + break; + } + break; + case Status::DONE: + break; + default: + bts_assert_msg(false, Formatter::fmt(log_header(), " unexpected status: ", me->status)); + break; + } +} + +void LimitCoverAlgo::on_settlement(SecurityKey, Price settlement) { + if (me->status == Status::WAITING_TO_DEPLOY) { + MSG("updating settlement from ", me->settlement, " to ", settlement); + me->settlement = settlement.value(); + DIAG("recomputing limit price..."); + recompute_limit_price(); + DIAG("limit price is ", me->limit_price); + DIAG("recomputing limit volume..."); + recompute_limit_volume(); + DIAG("limit volume is ", me->limit_volume); + try_deploy(); + } else { + MSG("ignored settlement update to ", settlement, + ": settlement updates are only processed while the algo is ", Status::WAITING_TO_DEPLOY, + ". Settlement at time of deploy was ", me->settlement); + } +} + +void LimitCoverAlgo::try_deploy() { + MSG("trying to deploy. ", fmt_state()); + bts_assert(me->status == Status::WAITING_TO_DEPLOY); + bts_assert(me->algo != nullptr); + // this is probably redundant (better safe than sorry tho). + bts_assert(me->child_key == null_order_key()); + if (os::is_nan(me->settlement)) { + MSG("still waiting for settle."); + } else if (me->limit_volume < activation_threshold()) { + MSG("still waiting for limit volume (", me->limit_volume, ") to breech activation threshold (", activation_threshold(), ")."); + } else { + bts_assert(!os::is_nan(me->limit_price)); + recompute_gate(); + OrderDefinition child_def; + bts_assert(!me->gates.empty()); + child_def.CopyFrom(algo().definition()); + init_delete_and_cover(child_def, curr_gate().definition()); + bts_assert(child_def.custom_def().has_delete_and_cover()); + MSG("deploying child order: ", utils::pb::to_string(child_def)); + me->child_key = algo().launch_child(child_def, Price(me->limit_price), algo().quantity()); + me->status = Status::WORKING; + algo().set_ladder_visibility(false); + } +} + +template +bool did_change(T& backing, T new_value) { + if (backing == new_value) + return false; + backing = new_value; + return true; +} + +bool LimitCoverAlgo::recompute_gate() { + if (me->gates.empty()) + return false; + auto orig_sz = me->gates.size(); + auto it = me->gates.lower_bound(me->limit_volume); + if (it == me->gates.end() || (it != me->gates.begin() && it->first > me->limit_volume)) + it--; + me->gates.erase(me->gates.begin(), it); + return me->gates.size() < orig_sz; +} + +// limit price +double LimitCoverAlgo::compute_limit_price() const { + return me->algo == nullptr ? os::nan() : + os::is_nan(me->settlement) ? + os::nan() : + securities::payup( + side(), + algo().security().contract_spec(), + me->settlement, + me->tick_offset_from_settle) + .value(); +} +bool LimitCoverAlgo::recompute_limit_price() { + return did_change(me->limit_price, compute_limit_price()); +} + +// limit volume +uint32_t LimitCoverAlgo::compute_limit_volume() const { + return me->algo == nullptr ? 0 : + BookUtils::volume_at_or_better(me->book, side(), me->limit_price); +} +bool LimitCoverAlgo::recompute_limit_volume() { + return did_change(me->limit_volume, compute_limit_volume()); +} + +// pseudo properties (const state accessors) +IAlgoServices &LimitCoverAlgo::algo() const { return *me->algo; } + +api::Side LimitCoverAlgo::side() const { + return me->algo == nullptr ? api::SIDE_UNDEFINED : me->algo->definition().side(); +} + +const LimitCoverGate& LimitCoverAlgo::curr_gate() const { + bts_assert(!me->gates.empty()); + return me->gates.begin()->second; +} + +uint32_t LimitCoverAlgo::activation_threshold() const { + return me->gates.empty() ? std::numeric_limits::max() : me->gates.begin()->first; +} + +std::string LimitCoverAlgo::log_header() const { + std::stringstream ostr; + ostr << "LimitCoverAlgo"; + if (me->algo != nullptr) { + ostr << "(" << me->algo->order_key().value() << ")"; + } + ostr << "[" << fmt_status(me->status) << "]"; + return ostr.str(); +} + +std::string LimitCoverAlgo::fmt_state() const { + std::stringstream ostr; + if (me->algo != nullptr) { + ostr << " [" << fmt_status(me->status) << "]" + << Formatter::to_string(side()) << " " << me->algo->quantity().value() + << " @ " << me->algo->price().value() + << " (" << me->tick_offset_from_settle + << " ticks away from settle)."; + if (me->child_key != null_order_key()) { + ostr << " Main child key: " << me->child_key << ", "; + } + ostr << " Settle: " << me->settlement + << ", Limit Price: " << me->limit_price + << ", BBO: " << Formatter::to_string(me->book); + } else { + ostr << "(initializing)"; + } + return ostr.str(); +} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h b/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h new file mode 100644 index 000000000..42ba1bd3c --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h @@ -0,0 +1,95 @@ +#pragma once +#include "lib/orderman/orderman_utils/BookUtils.h" +#include "lib/orderman/orderman_utils/Formatter.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h" +#include + +namespace bts { +namespace orderman { +class LimitCoverAlgo : public IAlgoOrder { + public: + LimitCoverAlgo(); + ~LimitCoverAlgo(); + + 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_settlement(SecurityKey, Price settlement) override; + void on_child_change(OrderKey, ChildState const &) override; + + enum class Status { + WAITING_TO_DEPLOY, + WORKING, + DONE + }; + using Status = bts::orderman::LimitCoverAlgo::Status; + + enum SummaryType { + StatusChange, + FullState + }; + + private: + struct PImpl; + struct Summary; + std::unique_ptr me; + + IAlgoServices &algo() const; + api::Side side() const; + std::string log_header() const; + std::string fmt_state() const; + // returns the first gate in gates (asserts that gates isn't empty). + // Note: after the child is deployed, gates with lower thresholds are + // removed when the limit volume passes the next gates' thresh. + const LimitCoverGate& curr_gate() const; + /// On the compute/recompute methods: + /// compute_blah just returns the result (doesn't mutate any state), + /// while recompute_blah assigns the result to the appropriate field, + /// and returns a bool indicating whether or not the value changed. + // limit price + double compute_limit_price() const; + bool recompute_limit_price(); + // limit volume + uint32_t compute_limit_volume() const; + bool recompute_limit_volume(); + // recomputes the current gate (i.e., the one with the + // highest activation thresh that is still less than + // the limit volume) then removes all gates with lower threshs. + bool recompute_gate(); + uint32_t activation_threshold() const; + // + void try_deploy(); + void update_child(uint32_t qty); +}; + +namespace limit_cover { +namespace utils { +inline std::string fmt_status(LimitCoverAlgo::Status status) { + switch (status) { + case LimitCoverAlgo::Status::WAITING_TO_DEPLOY: return "WAITING_TO_DEPLOY"; + case LimitCoverAlgo::Status::WORKING: return "WORKING"; + case LimitCoverAlgo::Status::DONE: return "DONE"; + default: return Formatter::fmt("STATUS_", static_cast(status)); + } +} + +inline std::ostream& operator<<(std::ostream& ostr, LimitCoverAlgo::Status status) { + ostr << fmt_status(status); + return ostr; +} + +void init_delete_and_cover(api::orderman::OrderDefinition& target, const api::orderman::DeleteAndCoverDefinition& def); +void init_delete_and_cover(api::orderman::CustomOrderDefinition& target, const api::orderman::DeleteAndCoverDefinition& def); +void init_child_update(api::orderman::Update& target, uint32_t qty, double price, const api::orderman::DeleteAndCoverDefinition& def); +OrderOpResult validate_def(const api::orderman::OrderDefinition&); +OrderOpResult validate_custom_def(const api::orderman::CustomOrderDefinition&); +OrderOpResult validate_update(const api::orderman::Update&); +} // namespace utils +} // namespace limit_cover + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.cpp b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.cpp new file mode 100644 index 000000000..dbd9459c9 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.cpp @@ -0,0 +1,162 @@ +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h" +#include "lib/orderman/orders/OrderOpResult.h" +#include "lib/orderman/orders/algo/utils/DynamicOrderAdapter.h" +#include + +namespace bts { +namespace orderman { +template +using Param = bts::orderman::dynamic_adapter::ParamKey; +using DynamicOrderEnumerated = bts::api::orderman::DynamicOrderEnumerated; +using OnToward = bts::api::orderman::LeanOnToward; +using LimitCoverDefinition = bts::orderman::LimitCoverDefinition; +using namespace bts::api::orderman; +#define ON_TOWARD_NAME_PAIR(x) std::make_pair(x, #x) + +template +std::string gate_param_name(std::string name) { + return Formatter::fmt("Gate ", gate_num, " ", name); +} + +template<> +std::string gate_param_name<0>(std::string name) { + return Formatter::fmt("Initial ", name); +} + +struct TicksOffset : public Param { + TicksOffset() : Param(std::string("Settle Ticks Offset"), + [](const LimitCoverDefinition& def) { return def.ticks_offset(); }, + [](LimitCoverDefinition& def, int v) { def.ticks_offset(v); }) {} +}; + +template +struct ActivationThreshold : public Param { + ActivationThreshold() : Param(gate_param_name("Activation Threshold"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).activation_threshold(); }, + [](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).activation_threshold(v); }) { } +}; + +template +struct CoverThreshold : public Param { + CoverThreshold() : Param(gate_param_name("Cover Threshold"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).cover_threshold(); }, + [](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).cover_threshold(v); }) { } +}; + +template +struct DeleteThreshold : public Param { + DeleteThreshold() : Param(gate_param_name("Delete Threshold"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).delete_threshold(); }, + [](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).delete_threshold(v); }) { } +}; + +template +struct TopTicksOff : public Param { + TopTicksOff() : Param(gate_param_name("Top Ticks Offset"), + [](const LimitCoverDefinition& def) {return def.gate(gate_num).top_ticks_offset(); }, + [](LimitCoverDefinition& def, uint32_t v) {return def.gate(gate_num).top_ticks_offset(v); }) { } +}; + +template +struct MaxChaseTicks : public Param { + MaxChaseTicks() : Param(gate_param_name("Max Chase Ticks"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).max_chase_ticks(); }, + [](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).max_chase_ticks(v); }) { } +}; + +template +struct CancelHedgesOnCancel : public Param { + CancelHedgesOnCancel() : Param(gate_param_name("Cancel Hedges On Cancel"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).cancel_hedges_on_cancel(); }, + [](LimitCoverDefinition& def, bool v) { def.mgate(gate_num).cancel_hedges_on_cancel(v); }) { } +}; + +template +struct CancelOnExternalHedgeCancel : public Param { + CancelOnExternalHedgeCancel() : Param(gate_param_name("Cancel On External Hedge Cancel"), + [](const LimitCoverDefinition& def) { return def.gate(gate_num).cancel_on_external_hedge_cancel(); }, + [](LimitCoverDefinition& def, bool v) { def.mgate(gate_num).cancel_on_external_hedge_cancel(v); }) { } +}; + +template +struct TradeTowardBehavior : public dynamic_adapter::EnumParamKey { + TradeTowardBehavior() : EnumParamKey( + gate_param_name("Trade Toward Behavior"), { + ON_TOWARD_NAME_PAIR(NO_CHANGE), + ON_TOWARD_NAME_PAIR(CANCEL), + ON_TOWARD_NAME_PAIR(DETACH), + ON_TOWARD_NAME_PAIR(REPRICE) + }, + [](const LimitCoverDefinition& def) { return def.gate(gate_num).on_toward(); }, + [](LimitCoverDefinition& def, OnToward v) { def.mgate(gate_num).on_toward(v); }) + {} +}; + +template<> +struct ActivationThreshold<0> : public Param { + ActivationThreshold() : Param(std::string("Entry Threshold"), + [](const LimitCoverDefinition& def) { return def.gate(0).activation_threshold(); }, + [](LimitCoverDefinition& def, uint32_t v) { + auto& g = def.mgate(0); + g.activation_threshold(v); + g.cover_threshold(v); + g.delete_threshold(v); + }) {} +}; + +using Adapter = dynamic_adapter::DynamicOrderAdapter, + TopTicksOff<0>, + MaxChaseTicks<0>, + TradeTowardBehavior<0>, + CancelHedgesOnCancel<0>, + CancelOnExternalHedgeCancel<0>, + // gate 1 + ActivationThreshold<1>, + CoverThreshold<1>, + DeleteThreshold<1>, + TopTicksOff<1>, + MaxChaseTicks<1>, + TradeTowardBehavior<1>, + CancelHedgesOnCancel<1>, + CancelOnExternalHedgeCancel<1>, + // gate 2 + ActivationThreshold<2>, + CoverThreshold<2>, + DeleteThreshold<2>, + TopTicksOff<2>, + MaxChaseTicks<2>, + TradeTowardBehavior<2>, + CancelHedgesOnCancel<2>, + CancelOnExternalHedgeCancel<2>>; + +LimitCoverDefinition LimitCoverAdapter::from_proto(const api::orderman::OrderDefinition& order) { + if (order.has_custom_def()) + return from_proto(order.custom_def()); + return LimitCoverDefinition(); +} +LimitCoverDefinition LimitCoverAdapter::from_proto(const api::orderman::CustomOrderDefinition& custom_def) { + LimitCoverDefinition rv; + if (custom_def.has_dynamic()) + Adapter().from_proto(custom_def.dynamic(), rv); + return rv; +} + +#define INVALID_DEF(x) OrderOpResult(api::orderman::ORDER_ERROR_INVALID_ORDER_DEFINITON, x) + +OrderOpResult LimitCoverAdapter::validate_proto(const api::orderman::DynamicOrderDefinition& dyn) { + return Adapter().validate_proto(dyn) ? + OrderOpResult() : + INVALID_DEF("One or more dynamic parameters are missing or invalid."); +} +void LimitCoverAdapter::init_proto(const LimitCoverDefinition& def, api::orderman::DynamicOrderDefinition& dyn) { + Adapter().to_proto(dyn, def); +} + +void LimitCoverAdapter::define_proto(api::orderman::DynamicOrderDescriptor& desc) { + Adapter().define_proto(desc); +} +} // namespace orderman +} // namespace bts \ No newline at end of file diff --git a/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h new file mode 100644 index 000000000..6c019e9c9 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h @@ -0,0 +1,15 @@ +#pragma once +#include "lib/api/services/OrderService.pb.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h" + +namespace bts { +namespace orderman { +struct LimitCoverAdapter { + static LimitCoverDefinition from_proto(const api::orderman::OrderDefinition& order); + static LimitCoverDefinition from_proto(const api::orderman::CustomOrderDefinition& custom_def); + static OrderOpResult validate_proto(const api::orderman::DynamicOrderDefinition& order); + static void init_proto(const LimitCoverDefinition& def, api::orderman::DynamicOrderDefinition& dyn); + static void define_proto(api::orderman::DynamicOrderDescriptor& desc); +}; +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h new file mode 100644 index 000000000..63445da7c --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h @@ -0,0 +1,71 @@ +#pragma once +#include "lib/api/services/OrderService.pb.h" +#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h" +#include "lib/orderman/orderman_utils/Formatter.h" +#include +#include +#include + +namespace bts { +namespace orderman { +namespace limit_cover { +// The exclusive maximum number of gates. +// Note: the limit cover spec called for 3 gates (2 gates explicitly, +// plus an initial activation threshold, which is treated as another gate). +const uint32_t max_num_gates = 4; +} +struct LimitCoverDefinition { + // ticks offset + int ticks_offset() const { + return _ticks_offset; + } + void ticks_offset(int value) { + _ticks_offset = value; + } + + LimitCoverGate gate(uint32_t index) const { + return _gate_or_default(index); + } + LimitCoverGate& mgate(uint32_t index) { + return _ensure_gate(index); + } + void gate(uint32_t index, LimitCoverGate value) { + _ensure_gate(index) = value; + } + + // The original LimitAlgo spec called for an initial activation thresh, and 2 gates + // (fyi a gate has 3 members: activation thresh, cover thresh, and delete thresh). + // The initial activation thresh serves as the initial cover, and delete threshes as well. + // In this sense, the activation threshold can be considered as an 'initial gate' itself. + // 'normal_gates' does just that: returns a map of both gates plus the 'initial gate.' + std::map normal_gates() const { + std::map m; + for (auto g : _gates) + m.insert(std::make_pair(g.activation_threshold(), g)); + return m; + } +private: + int _ticks_offset; + std::vector _gates; + + LimitCoverGate& _ensure_gate(uint32_t index) { + bts_assert(index < limit_cover::max_num_gates); + while (_gates.size() <= index) + _gates.push_back(LimitCoverGate()); + return _gates[index]; + } + + LimitCoverGate _gate_or_default(uint32_t index) const { + return _gates.size() > index ? _gates[index] : LimitCoverGate(); + } +}; + +inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverDefinition& lcd) { + auto ngates = lcd.normal_gates(); + ostr << "Ticks Offset: " << lcd.ticks_offset() + << ", Activation Thresh: " << lcd.gate(0).activation_threshold() + << ", Gates: " << Formatter::fmt_values(ngates); + return ostr; +} +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h new file mode 100644 index 000000000..67e1ae347 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h @@ -0,0 +1,90 @@ +#pragma once +#include "lib/api/services/OrderService.pb.h" +#include "lib/sparkproto/SparkProtos.pb.h" +#include "lib/utils/PBUtils.h" +#include + +namespace bts { +namespace orderman { +struct LimitCoverGate { + LimitCoverGate() : LimitCoverGate(0, 0, 0) {} + + LimitCoverGate(const LimitCoverGate& other) + : _activation_threshold(other._activation_threshold), _definition(other._definition) {} + + LimitCoverGate(uint32_t activation_thresh, uint32_t cover_thresh, uint32_t delete_thresh) + : _activation_threshold(activation_thresh), _definition() { + cover_threshold(cover_thresh); + delete_threshold(delete_thresh); + } + + // activation threshold + uint32_t activation_threshold() const { return _activation_threshold; } + void activation_threshold(uint32_t value) { _activation_threshold = value; } + + // cover threshold + uint32_t cover_threshold() const { + return _definition.has_cross_threshold() ? _get_absolute(_definition.cross_threshold()) : 0; + } + void cover_threshold(uint32_t value) { + if (!_definition.has_cross_threshold()) { + *_definition.mutable_cross_threshold() = bts::spark::QuantityMeasure(); + } + _definition.mutable_cross_threshold()->set_absolute(value); + } + + // delete threshold + uint32_t delete_threshold() const { + return _definition.has_top_threshold() ? _get_absolute(_definition.top_threshold()) : 0; + } + void delete_threshold(uint32_t value) { + if (!_definition.has_top_threshold()) { + *_definition.mutable_top_threshold() = bts::spark::QuantityMeasure(); + } + _definition.mutable_top_threshold()->set_absolute(value); + } + + // top ticks offset + uint32_t top_ticks_offset() const { return _definition.ticks_off(); } + void top_ticks_offset(uint32_t value) { _definition.set_ticks_off(value); } + // max chase ticks + uint32_t max_chase_ticks() const { return _definition.max_chase_ticks(); } + void max_chase_ticks(uint32_t value) { _definition.set_max_chase_ticks(value); } + // on toward + api::orderman::LeanOnToward on_toward() const { return _definition.trade_toward_behavior(); } + void on_toward(api::orderman::LeanOnToward value) { _definition.set_trade_toward_behavior(value); } + // cancel hedges on cancel + bool cancel_hedges_on_cancel() const { return _definition.cancel_hedges_on_cancel(); } + void cancel_hedges_on_cancel(bool value) { _definition.set_cancel_hedges_on_cancel(value); } + // cancel on external hedge cancel + bool cancel_on_external_hedge_cancel() const { return _definition.cancel_on_external_hedge_cancel(); } + void cancel_on_external_hedge_cancel(bool value) { _definition.set_cancel_on_external_hedge_cancel(value); } + // definition + const api::orderman::DeleteAndCoverDefinition& definition() const { return _definition; } + api::orderman::DeleteAndCoverDefinition& mdefinition() { return _definition; } + void definition(api::orderman::DeleteAndCoverDefinition value) { _definition = value; } + + api::orderman::CustomOrderDefinition custom_def() const { + api::orderman::CustomOrderDefinition cod; + *(cod.mutable_delete_and_cover()) = definition(); + return cod; + } + void custom_def(const api::orderman::CustomOrderDefinition &cod) { + if (cod.has_delete_and_cover()) + definition(cod.delete_and_cover()); + } +private: + uint32_t _activation_threshold; + api::orderman::DeleteAndCoverDefinition _definition; + + static inline uint32_t _get_absolute(spark::QuantityMeasure qty_measure, uint32_t fallback_value = 0) { + return qty_measure.quantity_case() == spark::QuantityMeasure::kAbsolute ? qty_measure.absolute() : fallback_value; + } +}; + +inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverGate& g) { + ostr << "Activation Thresh: " << g.activation_threshold() << ", Definition: " << utils::pb::to_string(g.custom_def()); + return ostr; +} +} // namespace orderman +} // namespace bts