From f2c3ff4be6f1170c58bff47ad3dff17f71fea076 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Wed, 5 Jul 2023 15:16:45 +0000 Subject: [PATCH 1/6] Adding vol to PrecomputedTheoPoint --- src/lib/api/services/OrderService.proto | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 95a73c4bf..f74f61c98 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -44,6 +44,7 @@ message PrecomputedTheoPoint { double vega = 60; double theta = 70; double rho = 80; + double vol = 90; } message PrecomputedTheos { From 3704d1ed16ca4739ca63ece62e806538eae1fd61 Mon Sep 17 00:00:00 2001 From: Taha Date: Wed, 5 Jul 2023 14:41:31 -0400 Subject: [PATCH 2/6] InterptheosServerPublisher is now opulated the newly added vol field in the PrecomputedTheoPoint proto --- src/client/spark/AW2/InterpTheosServerPublisher.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/client/spark/AW2/InterpTheosServerPublisher.cs b/src/client/spark/AW2/InterpTheosServerPublisher.cs index e3b4bffaa..d3045bfe6 100644 --- a/src/client/spark/AW2/InterpTheosServerPublisher.cs +++ b/src/client/spark/AW2/InterpTheosServerPublisher.cs @@ -111,6 +111,7 @@ namespace mbts.spark { ptp.Vega = is_call ? tp.cvega : tp.pvega; ptp.Theta = is_call ? tp.c_theta : tp.p_theta; ptp.Rho = Double.NaN; + ptp.Vol = tp.vol; ptp_list.Add(ptp); } bts.api.orderman.PrecomputedTheos server_theos = new PrecomputedTheos(); From 8355e3e1bec69344fe64b8b4850e631e51d7a1cc Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sun, 9 Jul 2023 04:21:42 +0000 Subject: [PATCH 3/6] VolAlgo code complete - need to test --- src/lib/domain_model/Security.h | 4 + .../orderman/calculations/ITheoCalculator.h | 4 + .../orderman/calculations/TheoCalculator.cpp | 13 + .../orderman/calculations/TheoCalculator.h | 2 + .../orderman/orderman_utils/orderman_common.h | 8 + .../algo/algo_orders/RegisterDorman.cpp | 14 + .../orders/algo/algo_orders/VolAlgo.cpp | 257 ++++++++++++++++++ .../orders/algo/algo_orders/VolAlgo.h | 38 +++ 8 files changed, 340 insertions(+) create mode 100644 src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp create mode 100644 src/lib/orderman/orders/algo/algo_orders/VolAlgo.h diff --git a/src/lib/domain_model/Security.h b/src/lib/domain_model/Security.h index 7a9620239..7ec120f8b 100644 --- a/src/lib/domain_model/Security.h +++ b/src/lib/domain_model/Security.h @@ -114,6 +114,10 @@ inline bool is_same(Price p1, Price p2) { return std::abs(p1.value() - p2.value()) < market_epsilon(); } +inline bool is_same(double d1, double d2) { + return std::abs(d1 - d2) < market_epsilon(); +} + inline bool is_equal_or_better(api::Side side, Price p1, Price p2) { return is_same(p1, p2) || is_better(side, p1, p2); } diff --git a/src/lib/orderman/calculations/ITheoCalculator.h b/src/lib/orderman/calculations/ITheoCalculator.h index 95293f66f..d679383a5 100644 --- a/src/lib/orderman/calculations/ITheoCalculator.h +++ b/src/lib/orderman/calculations/ITheoCalculator.h @@ -25,5 +25,9 @@ class ITheoCalculator { bts::api::orderman::PrecomputedTheoPoint &result) const = 0; // gets the driver security for a security with id sec_id virtual std::optional get_driver_sec(uint32_t sec_id) const = 0; + // given a vol for an option and the current driver, returns the theo that + // corresponds to that vol. + virtual double get_theo_correspoding_to_vol( + uint32_t sec_id, double driver, double vol) const = 0; }; } // namespace bts::orderman::analytics \ No newline at end of file diff --git a/src/lib/orderman/calculations/TheoCalculator.cpp b/src/lib/orderman/calculations/TheoCalculator.cpp index b2bd8ffce..4dc9e0501 100644 --- a/src/lib/orderman/calculations/TheoCalculator.cpp +++ b/src/lib/orderman/calculations/TheoCalculator.cpp @@ -213,6 +213,19 @@ std::optional TheoCalculator::get_driver_sec(uint32_t sec_id) const { return me->total_theo_data.get_driver_sec(sec_id); } +double TheoCalculator::get_theo_correspoding_to_vol( + uint32_t sec_id, double driver, double vol) const { + PrecomputedTheoPoint rv; + if (!get_theo(sec_id, driver, rv)) { + return bts::os::nan(); + } + // use the vega to compute the theo + double d_vol = vol - rv.vol(); + double d_theo = rv.vega() * d_vol; + double new_unnormalized_theo = (rv.theo() * driver) + d_theo; + return new_unnormalized_theo / driver; +} + void TheoCalculator::set_data(const PrecomputedTheos &theos) { LOG(Gen, Info, "TheoCalculator::set_data size: {}", theos.theos_size()); WriteLock write_lock(me->lock); diff --git a/src/lib/orderman/calculations/TheoCalculator.h b/src/lib/orderman/calculations/TheoCalculator.h index be5e14a0a..8e821b45b 100644 --- a/src/lib/orderman/calculations/TheoCalculator.h +++ b/src/lib/orderman/calculations/TheoCalculator.h @@ -23,6 +23,8 @@ class TheoCalculator : public ITheoCalculator { double driver, bts::api::orderman::PrecomputedTheoPoint &result) const override; std::optional get_driver_sec(uint32_t sec_id) const override; + double get_theo_correspoding_to_vol( + uint32_t sec_id, double driver, double vol) const override; void set_data(const bts::api::orderman::PrecomputedTheos &theos); private: diff --git a/src/lib/orderman/orderman_utils/orderman_common.h b/src/lib/orderman/orderman_utils/orderman_common.h index ac4d53fa4..8afe3256c 100644 --- a/src/lib/orderman/orderman_utils/orderman_common.h +++ b/src/lib/orderman/orderman_utils/orderman_common.h @@ -279,5 +279,13 @@ inline Quantity get_update_quantity(const bts::api::orderman::Update &u) { return rv; } +inline void set_update_quantity( + bts::api::orderman::Update &state, Quantity cqty) { + uint32_t int_qty = cqty.int_part(); + double fractional_qty = cqty.fractional_part(); + state.set_quantity(int_qty); + state.mutable_fractional_quantity()->set_fraction(fractional_qty); +} + } // namespace orderman } // namespace bts diff --git a/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp b/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp index 5a42ed9ab..28364762f 100644 --- a/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp @@ -12,6 +12,7 @@ #include "lib/orderman/orderman_utils/orderman_utils.h" #include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h" #include "lib/orderman/orders/algo/algo_orders/TaskingEyeAlgo.h" +#include "lib/orderman/orders/algo/algo_orders/VolAlgo.h" #include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h" #include "lib/orderman/orders/algo/algo_orders/tests/ExecutionTesterAlgo.h" #include "lib/plugin/SparkServices.h" @@ -325,6 +326,18 @@ extern "C" void init_task_eye_plugin(bts::SparkServices &srv) { }); } +extern "C" void init_vol_algo_plugin(bts::SparkServices &srv) { + DynamicOrderDescriptor vol_algo; + vol_algo.set_dynamic_order_type("Vol"); + *vol_algo.add_param_desc() = param_string("Account Override"); + *vol_algo.add_param_desc() = param_double("Vol"); + *vol_algo.add_param_desc() = param_bool("Requote?"); + *vol_algo.add_param_desc() = param_bool("Improve Price?"); + *vol_algo.add_param_desc() = param_int32("Distance From Top"); + srv.register_dynamic_algo_order( + vol_algo, []() { return std::make_unique(); }); +} + extern "C" void init_spark_plugin(bts::SparkServices &srv) { auto &dyn_algo_config = config::get(); if (dyn_algo_config.enable_dorman()) @@ -345,6 +358,7 @@ extern "C" void init_spark_plugin(bts::SparkServices &srv) { init_execution_tester_plugin(srv); // init_sniper_plugin(srv); init_task_eye_plugin(srv); + init_vol_algo_plugin(srv); } } // namespace dorman diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp new file mode 100644 index 000000000..953359b90 --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp @@ -0,0 +1,257 @@ +#include "VolAlgo.h" +#include "lib/api/services/OrderService.pb.h" +#include "lib/domain_model/Security.h" +#include "lib/domain_model/Security.pb.h" +#include "lib/domain_model/SecurityKey.h" +#include "lib/domain_model/common.h" +#include "lib/logging/logging.h" +#include "lib/md/PriceSize.h" +#include "lib/orderman/ChildOrder.h" +#include "lib/orderman/OrderBuilder.h" +#include "lib/orderman/limiter/SecurityLimitNode.h" +#include "lib/orderman/order_factory/IOrderFactory.h" +#include "lib/orderman/orderman_utils/Book.h" +#include "lib/orderman/orderman_utils/orderman_common.h" +#include "lib/orderman/orderman_utils/orderman_utils.h" +#include "lib/orderman/orders/OrderOpResult.h" +#include "lib/orderman/orders/algo/ChildTemplate.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" +#include "lib/orderman/orders/algo/IAlgoServices.h" +#include "lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h" +#include "lib/os/os.h" +#include "lib/utils/PBUtils.h" +#include "lib/utils/bts_assert.h" +#include +#include +#include +#include + +using namespace bts::api::orderman; + +namespace bts::orderman { + +ChildTemplate *get_vol_algo_child_template( + IBeforeLaunchAlgoServices &serv, + SecurityKey key, + api::Side side, + std::optional account_override) { + OrderDefinition order_def = serv.definition(); + order_def.set_security_key(key.value()); + order_def.set_side(side); + order_def.set_time_in_force(order_def.time_in_force()); + if (account_override.has_value()) { + // order_def.set_account(account_override); + } + order_def.mutable_custom_def()->mutable_limit()->MergeFrom( + api::orderman::LimitOrderDefinition()); + return &(serv.make_child_template(order_def)); +} + +struct VolAlgoParams { + std::optional account_override; + double vol; + bool re_quote = false; + bool improve_price = false; + int distance_from_top = 2; +}; + +struct VolAlgo ::PImpl { + IAlgoServices *service_ptr = nullptr; + analytics::ITheoCalculator const *theo_calc = nullptr; + uint32_t sec_key; + api::Side side; + std::optional account_override; + double qty = 0; + VolAlgoParams params = {}; + uint32_t driver_sec_key = 0; + bool subbed_to_driver = false; + std::optional driver_book = std::nullopt; + std::optional sec_book = std::nullopt; + // out + ChildTemplate *order = nullptr; + std::optional child_order_key = std::nullopt; + Price current_price = Price{os::nan()}; + bool inited() const { + return driver_book.has_value() && sec_book.has_value(); + } + bool order_fired() const { return child_order_key.has_value(); } +}; + +VolAlgo::VolAlgo() : me(new PImpl()) { LOG(OrderMan, Info, "VolAlgo created"); } + +VolAlgo::~VolAlgo() {} + +OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { + auto is_data_valid = [&](const auto &d_params) { + return get_if(d_params, "Requote?").has_value() && + get_if(d_params, "Improve Price?").has_value() && + get_if(d_params, "Distance From Top").has_value() && + serv.definition().side() != api::SIDE_UNDEFINED; + }; + LOG(OrderMan, Info, + "VolAlgo::do_before_launch order_key: {} security: {} " + "definition: {}", + serv.order_key().value(), utils::pb::to_string(serv.security()), + utils::pb::to_string(serv.definition())); + auto &def = serv.definition(); + if (def.has_custom_def() && def.custom_def().has_dynamic()) { + const auto &d_params = def.custom_def().dynamic().order_params(); + if (is_data_valid(d_params)) { + me->sec_key = def.security_key(); + me->side = def.side(); + me->params.account_override = + get_if(d_params, "Account Override"); + me->params.re_quote = get_if(d_params, "Requote?").value(); + me->params.improve_price = + get_if(d_params, "Improve Price?").value(); + me->params.distance_from_top = + get_if(d_params, "Distance From Top").value(); + me->order = get_vol_algo_child_template( + serv, SecurityKey(me->sec_key), me->side, + me->params.account_override); + LOG(OrderMan, Info, + "VolAlgo::do_before_launch sec_key: {} side: {} account_override: " + "{} vol: {} re_quote: {} improve_price: {} distance_from_top: {}", + me->sec_key, me->side == true, + me->params.account_override.has_value() + ? me->params.account_override.value() + : "", + me->params.vol, me->params.re_quote, me->params.improve_price, + me->params.distance_from_top); + return {}; + } + } + return { + bts::api::orderman::OrderError::ORDER_ERROR_INVALID_PARAMETER, + std::string("Parameters are not well formed")}; + return {}; +} + +void VolAlgo::do_launch(IAlgoServices &serv) { + LOG(OrderMan, Info, "VolAlgo::do_launch order_key: {} qty: {}", + serv.order_key(), serv.quantity()); + me->service_ptr = &serv; + me->qty = serv.quantity().full_value(); + me->service_ptr->subscribe_theos(); + me->service_ptr->subscribe_timer(); + me->service_ptr->subscribe_book(SecurityKey(me->sec_key)); +} + +void VolAlgo::do_launch_attached(IAlgoServices &serv, OrderKey, ChildState) { + me->service_ptr = &serv; + _terminate_algo(true, "Vol Algo can not be attached to working orders"); +} + +void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { + if (sec_key.value() == me->sec_key) { + me->sec_book = book; + _analyze_and_act(); + } else if (sec_key.value() == me->driver_sec_key) { + me->driver_book = book; + _analyze_and_act(); + } +} +void VolAlgo::do_update(api::orderman::Update const &) {} +void VolAlgo::on_child_change(OrderKey order_key, ChildState const &) { + if (me->child_order_key.has_value() && + me->child_order_key.value() == order_key) { + // child_state. + } +} +void VolAlgo::on_status(SecurityKey, co2::TradingStatus) {} +void VolAlgo::on_timer() {} +void VolAlgo::on_theos(analytics::ITheoCalculator const *theo_calculator) { + me->theo_calc = theo_calculator; + if (me->subbed_to_driver) { + _analyze_and_act(); + } + if (!me->subbed_to_driver) { + auto driver_sec = me->theo_calc->get_driver_sec(me->sec_key); + if (driver_sec.has_value()) { + me->driver_sec_key = driver_sec.value(); + me->service_ptr->subscribe_book(SecurityKey(me->driver_sec_key)); + } + } +} +void VolAlgo::on_position(PositionUpdate const &) {} + +void VolAlgo::_analyze_and_act() { + // check for period (to stop frequent updates) + auto get_driver = [&]() { + const md::PriceSize &driver_bid = me->driver_book->bid().at(0); + const md::PriceSize &driver_ask = me->driver_book->ask().at(0); + if (bts::securities::is_same(driver_bid.size(), 0) || + bts::securities::is_same(driver_ask.size(), 0)) + return os::nan(); + // finding weighted mean (TODO change it to mark price later) + double driver = (driver_bid.price() * driver_bid.size() + + driver_ask.price() * driver_ask.size()) / + (driver_bid.size() + driver_ask.size()); + return driver; + }; + if (me->order_fired()) { + if (!me->params.re_quote) + return; + // working order + double driver = get_driver(); + if (os::is_nan(driver)) { + // keep working it + return; + } + double theo = me->theo_calc->get_theo_correspoding_to_vol( + me->sec_key, driver, me->params.vol); + Price new_price = _get_order_price(theo); + if (securities::is_same(me->current_price, new_price)) { + return; + } + bool improving = + securities::is_better(me->side, new_price, me->current_price); + if (!improving || me->params.improve_price) { + bts::api::orderman::Update update; + update.set_price(new_price.value()); + set_update_quantity(update, Quantity::create_new(me->qty)); + me->service_ptr->update_child(me->child_order_key.value(), update); + return; + } + } else { + if (me->inited()) { + // time to fire + double driver = get_driver(); + if (os::is_nan(driver)) { + return; + } + // entering order + double theo = me->theo_calc->get_theo_correspoding_to_vol( + me->sec_key, driver, me->params.vol); + me->current_price = _get_order_price(theo); + me->child_order_key = me->service_ptr->launch_child( + *me->order, me->current_price, Quantity(me->qty)); + } + } +} + +void VolAlgo::_terminate_algo(bool is_error, const std::string &err_msg) { + // TODO unsub ? + if (is_error) { + me->service_ptr->terminate_error(err_msg); + } else { + me->service_ptr->complete(); + } +} + +Price VolAlgo::_get_order_price(double theo) const { + // BTC Opts (p <= 0.005) : price = 0.0001 qty = 0.1 + // BTC Opts (p > 0.005) : price = 0.0005 qty = 0.1 + // ------------------------------------------------- + // ETH Opts (p <= 0.005) : price = 0.0001 qty = 1 + // ETH Opts (p > 0.005) : price = 0.0005 qty = 1 + // TODO: get the above from the security itself + if (theo > 0.005) { + return Price{ + securities::raw_round_to_quote_price(theo, 0.0005, me->side)}; + } else { + return Price{ + securities::raw_round_to_quote_price(theo, 0.0001, me->side)}; + } +} +} // namespace bts::orderman diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h new file mode 100644 index 000000000..c2a892a4a --- /dev/null +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h @@ -0,0 +1,38 @@ +#pragma once + +#include "lib/domain_model/SecurityKey.h" +#include "lib/domain_model/common.h" +#include "lib/orderman/calculations/ITheoCalculator.h" +#include "lib/orderman/orders/algo/IAlgoOrder.h" +#include + +namespace bts::orderman { + +// This is a test algo, not to be used in prod, that sends an order and modifies +// it by moving the price up and down at a given period +class VolAlgo : public IAlgoOrder { + public: + VolAlgo(); + ~VolAlgo(); + OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override; + void on_book(SecurityKey, Book const &) 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 on_status(SecurityKey, co2::TradingStatus) override; + void on_timer() override; + void on_theos(analytics::ITheoCalculator const *theo_calculator) override; + void on_position(PositionUpdate const &) override; + + private: + struct PImpl; + std::unique_ptr me; + + private: + void _analyze_and_act(); + void _terminate_algo(bool is_error, const std::string &err_msg); + Price _get_order_price(double theo) const; +}; + +} // namespace bts::orderman From 071c28e925dde12f91d7e3925c4753f3713dc74a Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Mon, 10 Jul 2023 03:20:05 +0000 Subject: [PATCH 4/6] VolAlgo reflects its state correctly now --- .../orderman/calculations/TheoCalculator.cpp | 12 ++- .../orders/algo/algo_orders/VolAlgo.cpp | 75 ++++++++++++++----- 2 files changed, 67 insertions(+), 20 deletions(-) diff --git a/src/lib/orderman/calculations/TheoCalculator.cpp b/src/lib/orderman/calculations/TheoCalculator.cpp index 4dc9e0501..4370c96b0 100644 --- a/src/lib/orderman/calculations/TheoCalculator.cpp +++ b/src/lib/orderman/calculations/TheoCalculator.cpp @@ -50,12 +50,15 @@ void interpolate( lower.driver(), lower.theta(), higher.driver(), higher.theta(), driver); double rho = lin_interp_exterp( lower.driver(), lower.rho(), higher.driver(), higher.rho(), driver); + double vol = lin_interp_exterp( + lower.driver(), lower.vol(), higher.driver(), higher.vol(), driver); result.set_theo(theo); result.set_delta(delta); result.set_gamma(gamma); result.set_vega(vega); result.set_theta(theta); result.set_rho(rho); + result.set_vol(vol); } struct DriverNeighbors { @@ -222,8 +225,13 @@ double TheoCalculator::get_theo_correspoding_to_vol( // use the vega to compute the theo double d_vol = vol - rv.vol(); double d_theo = rv.vega() * d_vol; - double new_unnormalized_theo = (rv.theo() * driver) + d_theo; - return new_unnormalized_theo / driver; + double new_theo = rv.theo() + d_theo; + LOG(Gen, Info, + "TheoCalculator::get_theo_correspoding_to_vol sec_id: {} driver: {} " + "vol: {} rv.theo: {} rv.vol: {} rv.vega: {} " + "new_theo: {}", + sec_id, driver, vol, rv.theo(), rv.vol(), rv.vega(), new_theo); + return new_theo; } void TheoCalculator::set_data(const PrecomputedTheos &theos) { diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp index 953359b90..eea81cc67 100644 --- a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp @@ -58,6 +58,7 @@ struct VolAlgoParams { struct VolAlgo ::PImpl { IAlgoServices *service_ptr = nullptr; analytics::ITheoCalculator const *theo_calc = nullptr; + OrderKey order_key; uint32_t sec_key; api::Side side; std::optional account_override; @@ -83,7 +84,8 @@ VolAlgo::~VolAlgo() {} OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { auto is_data_valid = [&](const auto &d_params) { - return get_if(d_params, "Requote?").has_value() && + return get_if(d_params, "Vol").has_value() && + get_if(d_params, "Requote?").has_value() && get_if(d_params, "Improve Price?").has_value() && get_if(d_params, "Distance From Top").has_value() && serv.definition().side() != api::SIDE_UNDEFINED; @@ -97,10 +99,12 @@ OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { if (def.has_custom_def() && def.custom_def().has_dynamic()) { const auto &d_params = def.custom_def().dynamic().order_params(); if (is_data_valid(d_params)) { + me->order_key = serv.order_key(); me->sec_key = def.security_key(); me->side = def.side(); me->params.account_override = get_if(d_params, "Account Override"); + me->params.vol = get_if(d_params, "Vol").value(); me->params.re_quote = get_if(d_params, "Requote?").value(); me->params.improve_price = get_if(d_params, "Improve Price?").value(); @@ -112,7 +116,7 @@ OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { LOG(OrderMan, Info, "VolAlgo::do_before_launch sec_key: {} side: {} account_override: " "{} vol: {} re_quote: {} improve_price: {} distance_from_top: {}", - me->sec_key, me->side == true, + me->sec_key, bts::api::Side_Name(me->side), me->params.account_override.has_value() ? me->params.account_override.value() : "", @@ -124,12 +128,11 @@ OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { return { bts::api::orderman::OrderError::ORDER_ERROR_INVALID_PARAMETER, std::string("Parameters are not well formed")}; - return {}; } void VolAlgo::do_launch(IAlgoServices &serv) { LOG(OrderMan, Info, "VolAlgo::do_launch order_key: {} qty: {}", - serv.order_key(), serv.quantity()); + serv.order_key().value(), serv.quantity()); me->service_ptr = &serv; me->qty = serv.quantity().full_value(); me->service_ptr->subscribe_theos(); @@ -143,6 +146,8 @@ void VolAlgo::do_launch_attached(IAlgoServices &serv, OrderKey, ChildState) { } void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { + LOG(OrderMan, Info, "VolAlgo::on_book order_key: {} sec_key: {}", + me->order_key, sec_key); if (sec_key.value() == me->sec_key) { me->sec_book = book; _analyze_and_act(); @@ -152,25 +157,44 @@ void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { } } void VolAlgo::do_update(api::orderman::Update const &) {} -void VolAlgo::on_child_change(OrderKey order_key, ChildState const &) { - if (me->child_order_key.has_value() && - me->child_order_key.value() == order_key) { - // child_state. +void VolAlgo::on_child_change(OrderKey, ChildState const &state) { + me->service_ptr->update_fill_state(state.total_fills, state.last_price); + switch (state.status) { + case ChildStatus::WORKING: + break; + case ChildStatus::COMPLETED: + me->service_ptr->complete(); + break; + case ChildStatus::CANCELED: + me->service_ptr->cancel("Child Order Cancelled"); + break; } } + void VolAlgo::on_status(SecurityKey, co2::TradingStatus) {} void VolAlgo::on_timer() {} + void VolAlgo::on_theos(analytics::ITheoCalculator const *theo_calculator) { + LOG(OrderMan, Info, "VolAlgo::on_theos sec_key: {} order_key: {}", + me->sec_key, me->order_key); me->theo_calc = theo_calculator; if (me->subbed_to_driver) { _analyze_and_act(); + return; } - if (!me->subbed_to_driver) { - auto driver_sec = me->theo_calc->get_driver_sec(me->sec_key); - if (driver_sec.has_value()) { - me->driver_sec_key = driver_sec.value(); - me->service_ptr->subscribe_book(SecurityKey(me->driver_sec_key)); - } + auto driver_sec = me->theo_calc->get_driver_sec(me->sec_key); + if (driver_sec.has_value()) { + LOG(OrderMan, Info, + "VolAlgo::on_theos sec_key: {} order_key: {} subscribing to " + "driver sec_key: {}", + me->sec_key, me->order_key, driver_sec.value()); + me->subbed_to_driver = true; + me->driver_sec_key = driver_sec.value(); + me->service_ptr->subscribe_book(SecurityKey(me->driver_sec_key)); + } else { + LOG(OrderMan, Info, + "VolAlgo::on_theos sec_key: {} order_key: {} could not find driver", + me->sec_key, me->order_key); } } void VolAlgo::on_position(PositionUpdate const &) {} @@ -200,6 +224,8 @@ void VolAlgo::_analyze_and_act() { } double theo = me->theo_calc->get_theo_correspoding_to_vol( me->sec_key, driver, me->params.vol); + // TODO: normalize + theo = theo / driver; Price new_price = _get_order_price(theo); if (securities::is_same(me->current_price, new_price)) { return; @@ -210,6 +236,11 @@ void VolAlgo::_analyze_and_act() { bts::api::orderman::Update update; update.set_price(new_price.value()); set_update_quantity(update, Quantity::create_new(me->qty)); + me->current_price = new_price; + LOG(Gen, Info, + "VolAlgo::_analyze_and_act updating order order_key: {} price: {} " + "qty: {}", + me->order_key, me->current_price, me->qty); me->service_ptr->update_child(me->child_order_key.value(), update); return; } @@ -223,7 +254,12 @@ void VolAlgo::_analyze_and_act() { // entering order double theo = me->theo_calc->get_theo_correspoding_to_vol( me->sec_key, driver, me->params.vol); + theo = theo / driver; me->current_price = _get_order_price(theo); + LOG(Gen, Info, + "VolAlgo::_analyze_and_act placing order order_key: {} price: {} " + "qty: {}", + me->order_key, me->current_price, me->qty); me->child_order_key = me->service_ptr->launch_child( *me->order, me->current_price, Quantity(me->qty)); } @@ -246,12 +282,15 @@ Price VolAlgo::_get_order_price(double theo) const { // ETH Opts (p <= 0.005) : price = 0.0001 qty = 1 // ETH Opts (p > 0.005) : price = 0.0005 qty = 1 // TODO: get the above from the security itself + double rv = 0; if (theo > 0.005) { - return Price{ - securities::raw_round_to_quote_price(theo, 0.0005, me->side)}; + rv = securities::raw_round_to_quote_price(theo, 0.0005, me->side); } else { - return Price{ - securities::raw_round_to_quote_price(theo, 0.0001, me->side)}; + rv = securities::raw_round_to_quote_price(theo, 0.0001, me->side); } + LOG(Gen, Info, + "VolAlgo::_get_order_price order_key: {} theo: {} order_price: {}", + me->order_key, theo, rv); + return Price{rv}; } } // namespace bts::orderman From 65736c13efbe51813bc11fe43f7f339b085c0045 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Fri, 14 Jul 2023 03:54:14 +0000 Subject: [PATCH 5/6] VolAlgo completed --- .../algo/algo_orders/RegisterDorman.cpp | 3 +- .../orders/algo/algo_orders/VolAlgo.cpp | 148 ++++++++++++------ .../orders/algo/algo_orders/VolAlgo.h | 2 +- 3 files changed, 105 insertions(+), 48 deletions(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp b/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp index 28364762f..0bc2d0e0c 100644 --- a/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/RegisterDorman.cpp @@ -329,8 +329,9 @@ extern "C" void init_task_eye_plugin(bts::SparkServices &srv) { extern "C" void init_vol_algo_plugin(bts::SparkServices &srv) { DynamicOrderDescriptor vol_algo; vol_algo.set_dynamic_order_type("Vol"); - *vol_algo.add_param_desc() = param_string("Account Override"); + //*vol_algo.add_param_desc() = param_string("Account Override"); *vol_algo.add_param_desc() = param_double("Vol"); + *vol_algo.add_param_desc() = param_bool("Cross At Entry?"); *vol_algo.add_param_desc() = param_bool("Requote?"); *vol_algo.add_param_desc() = param_bool("Improve Price?"); *vol_algo.add_param_desc() = param_int32("Distance From Top"); diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp index eea81cc67..00e335ead 100644 --- a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp @@ -49,12 +49,40 @@ ChildTemplate *get_vol_algo_child_template( struct VolAlgoParams { std::optional account_override; - double vol; - bool re_quote = false; + double vol_perc; + bool cross_at_entry = false; + bool requote = false; bool improve_price = false; int distance_from_top = 2; }; +std::optional parse_parameters( + const DynamicOrderDefinition &def) { + const auto &d_params = def.order_params(); + VolAlgoParams rv = {}; + // vol + auto vol_perc = get_if(d_params, "Vol"); + if (!vol_perc.has_value()) + return std::nullopt; + rv.vol_perc = vol_perc.value(); + // cross at entry + auto cross_at_entry = get_if(d_params, "Cross At Entry?"); + rv.cross_at_entry = + cross_at_entry.has_value() ? cross_at_entry.value() : false; + // requote + auto requote = get_if(d_params, "Requote?"); + rv.requote = requote.has_value() ? requote.value() : false; + // improve price + auto improve_price = get_if(d_params, "Improve Price?"); + rv.improve_price = improve_price.has_value() ? improve_price.value() : false; + // Distance from Top + auto distance_from_top = get_if(d_params, "Distance From Top"); + if (!distance_from_top.has_value()) + return std::nullopt; + rv.distance_from_top = distance_from_top.value(); + return rv; +} + struct VolAlgo ::PImpl { IAlgoServices *service_ptr = nullptr; analytics::ITheoCalculator const *theo_calc = nullptr; @@ -83,47 +111,36 @@ VolAlgo::VolAlgo() : me(new PImpl()) { LOG(OrderMan, Info, "VolAlgo created"); } VolAlgo::~VolAlgo() {} OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { - auto is_data_valid = [&](const auto &d_params) { - return get_if(d_params, "Vol").has_value() && - get_if(d_params, "Requote?").has_value() && - get_if(d_params, "Improve Price?").has_value() && - get_if(d_params, "Distance From Top").has_value() && - serv.definition().side() != api::SIDE_UNDEFINED; - }; LOG(OrderMan, Info, "VolAlgo::do_before_launch order_key: {} security: {} " "definition: {}", serv.order_key().value(), utils::pb::to_string(serv.security()), utils::pb::to_string(serv.definition())); auto &def = serv.definition(); + me->order_key = serv.order_key(); + me->sec_key = def.security_key(); + me->side = def.side(); if (def.has_custom_def() && def.custom_def().has_dynamic()) { - const auto &d_params = def.custom_def().dynamic().order_params(); - if (is_data_valid(d_params)) { - me->order_key = serv.order_key(); - me->sec_key = def.security_key(); - me->side = def.side(); - me->params.account_override = - get_if(d_params, "Account Override"); - me->params.vol = get_if(d_params, "Vol").value(); - me->params.re_quote = get_if(d_params, "Requote?").value(); - me->params.improve_price = - get_if(d_params, "Improve Price?").value(); - me->params.distance_from_top = - get_if(d_params, "Distance From Top").value(); - me->order = get_vol_algo_child_template( - serv, SecurityKey(me->sec_key), me->side, - me->params.account_override); - LOG(OrderMan, Info, - "VolAlgo::do_before_launch sec_key: {} side: {} account_override: " - "{} vol: {} re_quote: {} improve_price: {} distance_from_top: {}", - me->sec_key, bts::api::Side_Name(me->side), - me->params.account_override.has_value() - ? me->params.account_override.value() - : "", - me->params.vol, me->params.re_quote, me->params.improve_price, - me->params.distance_from_top); - return {}; + auto va_params = parse_parameters(def.custom_def().dynamic()); + if (!va_params.has_value()) { + return { + bts::api::orderman::OrderError::ORDER_ERROR_INVALID_PARAMETER, + std::string("Parameters are not well formed")}; } + me->params = va_params.value(); + me->order = get_vol_algo_child_template( + serv, SecurityKey(me->sec_key), me->side, + me->params.account_override); + LOG(OrderMan, Info, + "VolAlgo::do_before_launch sec_key: {} side: {} account_override: " + "{} vol: {} re_quote: {} improve_price: {} distance_from_top: {}", + me->sec_key, bts::api::Side_Name(me->side), + me->params.account_override.has_value() + ? me->params.account_override.value() + : "", + me->params.vol_perc, me->params.requote, me->params.improve_price, + me->params.distance_from_top); + return {}; } return { bts::api::orderman::OrderError::ORDER_ERROR_INVALID_PARAMETER, @@ -156,8 +173,27 @@ void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { _analyze_and_act(); } } -void VolAlgo::do_update(api::orderman::Update const &) {} +void VolAlgo::do_update(api::orderman::Update const &u) { + LOG(OrderMan, Info, + "VolAlgo::do_update order_key: {} security: {} " + "update: {}", + me->order_key, me->sec_key, utils::pb::to_string(u)); + const auto &p = u.custom().dynamic(); + auto params = parse_parameters(p); + if (!params.has_value()) { + LOG(Gen, Error, + "VolAlgo::do_update order_key: {} parameters are not well formed", + me->order_key); + return; + } + me->qty = u.quantity(); + me->params = params.value(); + _analyze_and_act(true); + // price changes are ignored the price is the vol +} + void VolAlgo::on_child_change(OrderKey, ChildState const &state) { + // price / qty is reflected from the child me->service_ptr->update_fill_state(state.total_fills, state.last_price); switch (state.status) { case ChildStatus::WORKING: @@ -199,7 +235,7 @@ void VolAlgo::on_theos(analytics::ITheoCalculator const *theo_calculator) { } void VolAlgo::on_position(PositionUpdate const &) {} -void VolAlgo::_analyze_and_act() { +void VolAlgo::_analyze_and_act(bool force_reprice) { // check for period (to stop frequent updates) auto get_driver = [&]() { const md::PriceSize &driver_bid = me->driver_book->bid().at(0); @@ -213,8 +249,17 @@ void VolAlgo::_analyze_and_act() { (driver_bid.size() + driver_ask.size()); return driver; }; + auto crosses_opp_market = [&](Price order_price) { + if (me->side == api::SIDE_BUY) { + double top = me->sec_book->ask().at(0).price(); + return securities::gr_than_eq(order_price.value(), top); + } else { + double top = me->sec_book->bid().at(0).price(); + return securities::gr_than_eq(top, order_price.value()); + } + }; if (me->order_fired()) { - if (!me->params.re_quote) + if (!me->params.requote && !force_reprice) return; // working order double driver = get_driver(); @@ -222,17 +267,21 @@ void VolAlgo::_analyze_and_act() { // keep working it return; } - double theo = me->theo_calc->get_theo_correspoding_to_vol( - me->sec_key, driver, me->params.vol); + double theo_unnorm = me->theo_calc->get_theo_correspoding_to_vol( + me->sec_key, driver, me->params.vol_perc / 100.0); // TODO: normalize - theo = theo / driver; + double theo = theo_unnorm / driver; Price new_price = _get_order_price(theo); + LOG(OrderMan, Info, + "VolAlgo::_analyze_and_act (updating) theo_unnorm: {} driver: {} " + "theo: {} order_price: {}", + theo_unnorm, driver, theo, new_price); if (securities::is_same(me->current_price, new_price)) { return; } bool improving = securities::is_better(me->side, new_price, me->current_price); - if (!improving || me->params.improve_price) { + if (!improving || me->params.improve_price || force_reprice) { bts::api::orderman::Update update; update.set_price(new_price.value()); set_update_quantity(update, Quantity::create_new(me->qty)); @@ -252,10 +301,17 @@ void VolAlgo::_analyze_and_act() { return; } // entering order - double theo = me->theo_calc->get_theo_correspoding_to_vol( - me->sec_key, driver, me->params.vol); - theo = theo / driver; - me->current_price = _get_order_price(theo); + double theo_unnorm = me->theo_calc->get_theo_correspoding_to_vol( + me->sec_key, driver, me->params.vol_perc / 100.0); + double theo = theo_unnorm / driver; + Price order_price = _get_order_price(theo); + LOG(OrderMan, Info, + "VolAlgo::_analyze_and_act theo_unnorm: {} driver: {} theo: {} " + "order_price: {}", + theo_unnorm, driver, theo, order_price); + if (!me->params.cross_at_entry && crosses_opp_market(order_price)) + return; + me->current_price = order_price; LOG(Gen, Info, "VolAlgo::_analyze_and_act placing order order_key: {} price: {} " "qty: {}", diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h index c2a892a4a..64df8b1f5 100644 --- a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.h @@ -30,7 +30,7 @@ class VolAlgo : public IAlgoOrder { std::unique_ptr me; private: - void _analyze_and_act(); + void _analyze_and_act(bool force_reprice = false); void _terminate_algo(bool is_error, const std::string &err_msg); Price _get_order_price(double theo) const; }; From d9e5c846c2621110c355563b020abb22a497717f Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Fri, 14 Jul 2023 16:57:55 +0000 Subject: [PATCH 6/6] Adding more logs to VolAlgo --- .../orders/algo/algo_orders/VolAlgo.cpp | 58 ++++++++++--------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp index 00e335ead..93c2fd577 100644 --- a/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp +++ b/src/lib/orderman/orders/algo/algo_orders/VolAlgo.cpp @@ -40,7 +40,7 @@ ChildTemplate *get_vol_algo_child_template( order_def.set_side(side); order_def.set_time_in_force(order_def.time_in_force()); if (account_override.has_value()) { - // order_def.set_account(account_override); + // no need for it now } order_def.mutable_custom_def()->mutable_limit()->MergeFrom( api::orderman::LimitOrderDefinition()); @@ -97,10 +97,11 @@ struct VolAlgo ::PImpl { std::optional driver_book = std::nullopt; std::optional sec_book = std::nullopt; // out - ChildTemplate *order = nullptr; + ChildTemplate *child_order = nullptr; std::optional child_order_key = std::nullopt; Price current_price = Price{os::nan()}; bool inited() const { + // once we have receved both books we are ready to go return driver_book.has_value() && sec_book.has_value(); } bool order_fired() const { return child_order_key.has_value(); } @@ -128,18 +129,16 @@ OrderOpResult VolAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) { std::string("Parameters are not well formed")}; } me->params = va_params.value(); - me->order = get_vol_algo_child_template( + me->child_order = get_vol_algo_child_template( serv, SecurityKey(me->sec_key), me->side, me->params.account_override); LOG(OrderMan, Info, - "VolAlgo::do_before_launch sec_key: {} side: {} account_override: " - "{} vol: {} re_quote: {} improve_price: {} distance_from_top: {}", - me->sec_key, bts::api::Side_Name(me->side), - me->params.account_override.has_value() - ? me->params.account_override.value() - : "", - me->params.vol_perc, me->params.requote, me->params.improve_price, - me->params.distance_from_top); + "VolAlgo::do_before_launch order_key: {} sec_key: {} side: {} vol: " + "{} cross_at_entry: {} re_quote: {} improve_price: {} " + "distance_from_top: {}", + me->order_key, me->sec_key, bts::api::Side_Name(me->side), + me->params.vol_perc, me->params.cross_at_entry, me->params.requote, + me->params.improve_price, me->params.distance_from_top); return {}; } return { @@ -163,7 +162,7 @@ void VolAlgo::do_launch_attached(IAlgoServices &serv, OrderKey, ChildState) { } void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { - LOG(OrderMan, Info, "VolAlgo::on_book order_key: {} sec_key: {}", + LOG(OrderMan, Diag, "VolAlgo::on_book order_key: {} sec_key: {}", me->order_key, sec_key); if (sec_key.value() == me->sec_key) { me->sec_book = book; @@ -175,7 +174,7 @@ void VolAlgo::on_book(SecurityKey sec_key, Book const &book) { } void VolAlgo::do_update(api::orderman::Update const &u) { LOG(OrderMan, Info, - "VolAlgo::do_update order_key: {} security: {} " + "VolAlgo::do_update order_key: {} sec_key: {} " "update: {}", me->order_key, me->sec_key, utils::pb::to_string(u)); const auto &p = u.custom().dynamic(); @@ -211,8 +210,7 @@ void VolAlgo::on_status(SecurityKey, co2::TradingStatus) {} void VolAlgo::on_timer() {} void VolAlgo::on_theos(analytics::ITheoCalculator const *theo_calculator) { - LOG(OrderMan, Info, "VolAlgo::on_theos sec_key: {} order_key: {}", - me->sec_key, me->order_key); + LOG(OrderMan, Info, "VolAlgo::on_theos order_key: {}", me->order_key); me->theo_calc = theo_calculator; if (me->subbed_to_driver) { _analyze_and_act(); @@ -221,20 +219,21 @@ void VolAlgo::on_theos(analytics::ITheoCalculator const *theo_calculator) { auto driver_sec = me->theo_calc->get_driver_sec(me->sec_key); if (driver_sec.has_value()) { LOG(OrderMan, Info, - "VolAlgo::on_theos sec_key: {} order_key: {} subscribing to " - "driver sec_key: {}", - me->sec_key, me->order_key, driver_sec.value()); + "VolAlgo::on_theos order_key: {} subscribing to driver sec_key: {}", + me->order_key, driver_sec.value()); me->subbed_to_driver = true; me->driver_sec_key = driver_sec.value(); me->service_ptr->subscribe_book(SecurityKey(me->driver_sec_key)); } else { - LOG(OrderMan, Info, - "VolAlgo::on_theos sec_key: {} order_key: {} could not find driver", - me->sec_key, me->order_key); + LOG(OrderMan, Warn, + "VolAlgo::on_theos order_key: {} could not find driver", + me->order_key); } } void VolAlgo::on_position(PositionUpdate const &) {} +// this is where all the action happens, both new order (just once) as well as +// order updates void VolAlgo::_analyze_and_act(bool force_reprice) { // check for period (to stop frequent updates) auto get_driver = [&]() { @@ -259,6 +258,7 @@ void VolAlgo::_analyze_and_act(bool force_reprice) { } }; if (me->order_fired()) { + // repricing if parameters (and arg) allows if (!me->params.requote && !force_reprice) return; // working order @@ -273,9 +273,9 @@ void VolAlgo::_analyze_and_act(bool force_reprice) { double theo = theo_unnorm / driver; Price new_price = _get_order_price(theo); LOG(OrderMan, Info, - "VolAlgo::_analyze_and_act (updating) theo_unnorm: {} driver: {} " - "theo: {} order_price: {}", - theo_unnorm, driver, theo, new_price); + "VolAlgo::_analyze_and_act (calc updating) order_key: {} " + "theo_unnorm: {} driver: {} theo: {} order_price: {}", + me->order_key, theo_unnorm, driver, theo, new_price); if (securities::is_same(me->current_price, new_price)) { return; } @@ -294,6 +294,7 @@ void VolAlgo::_analyze_and_act(bool force_reprice) { return; } } else { + // new order path if (me->inited()) { // time to fire double driver = get_driver(); @@ -306,9 +307,9 @@ void VolAlgo::_analyze_and_act(bool force_reprice) { double theo = theo_unnorm / driver; Price order_price = _get_order_price(theo); LOG(OrderMan, Info, - "VolAlgo::_analyze_and_act theo_unnorm: {} driver: {} theo: {} " - "order_price: {}", - theo_unnorm, driver, theo, order_price); + "VolAlgo::_analyze_and_act (calc new) order_key: {} theo_unnorm: " + "{} driver: {} theo: {} order_price: {}", + me->order_key, theo_unnorm, driver, theo, order_price); if (!me->params.cross_at_entry && crosses_opp_market(order_price)) return; me->current_price = order_price; @@ -317,7 +318,8 @@ void VolAlgo::_analyze_and_act(bool force_reprice) { "qty: {}", me->order_key, me->current_price, me->qty); me->child_order_key = me->service_ptr->launch_child( - *me->order, me->current_price, Quantity(me->qty)); + *me->child_order, me->current_price, + Quantity::create_new(me->qty)); } } }