diff --git a/src/client/spark/mspark/MarketView/MarketViewVM.cs b/src/client/spark/mspark/MarketView/MarketViewVM.cs index 7931a641b..467a0bda1 100644 --- a/src/client/spark/mspark/MarketView/MarketViewVM.cs +++ b/src/client/spark/mspark/MarketView/MarketViewVM.cs @@ -82,7 +82,7 @@ namespace mbts.spark } private IObservable _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); } - private static Security _get_security(DataGridCellInfo cell) { return ((Row)cell.Item).security.value; } + private static Security _get_security(DataGridCellInfo cell) { return (cell.Item as Row)?.security.value; } private static Order _create_order(DataGridCellInfo cell) { return _create_order((Row)cell.Item, (Columns)DataGridEx.GetArgument(cell.Column)); } private static Order _create_order(Row row, Columns col) { var order = new Order { Security = row.security.value, MarketOrder = new MarketOrder(), Price = 0, Size = 1 }; diff --git a/src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs b/src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs index 3c89b831d..d1bcbae1f 100644 --- a/src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs +++ b/src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs @@ -1,7 +1,6 @@ using bts.api; using mbts.ui.shell; using System; -using System.Linq; using System.Windows.Controls; using static bts.api.Security; diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index eced8cafd..a635dd0ae 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1 +1 @@ -set(sources ;cmds/CmdRegistry.cpp;cmds/Help.cpp;cmds/Run.cpp;cmds/Test.cpp;cmds/TestOrderman.cpp;event_grid/EventNode.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/FillRecorder.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/components/OrderRecorder.cpp;orderman/events/ExecutionReport.cpp;orderman/events/NativeOrderStateChange.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/persistence/FillDB.cpp;orderman/persistence/OrderDB.cpp;orderman/persistence/gen_order_id.cpp;orderman/service/OrderServiceServer.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/SharedRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/QuoteLegPriceQuantityState.cpp;spreader/SimpleSpreader.cpp;spreader/SingleFillHedger.cpp;spreader/SingleLegQuoter.cpp;spreader/SpreaderBase.cpp;testing/catch_test_runner.cpp;user/UserServiceServer.cpp) \ No newline at end of file +set(sources ;cmds/CmdRegistry.cpp;cmds/Help.cpp;cmds/Run.cpp;cmds/Test.cpp;cmds/TestOrderman.cpp;event_grid/EventNode.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/FillRecorder.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/components/OrderRecorder.cpp;orderman/events/ExecutionReport.cpp;orderman/events/NativeOrderStateChange.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/persistence/FillDB.cpp;orderman/persistence/OrderDB.cpp;orderman/persistence/gen_order_id.cpp;orderman/service/OrderServiceServer.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/SharedRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/QuoteLegPriceQuantityState.cpp;spreader/SimpleSpreader.cpp;spreader/SingleFillHedger.cpp;spreader/SingleLegQuoter.cpp;spreader/SpreaderBase.cpp;spreader/SpreaderTests.cpp;testing/catch_test_runner.cpp;user/UserServiceServer.cpp) \ No newline at end of file diff --git a/src/server/sparkd/sparkd.vcxproj b/src/server/sparkd/sparkd.vcxproj index edf8ce381..228c45c07 100644 --- a/src/server/sparkd/sparkd.vcxproj +++ b/src/server/sparkd/sparkd.vcxproj @@ -61,6 +61,7 @@ + @@ -136,13 +137,16 @@ - + + + + @@ -215,4 +219,4 @@ - + \ No newline at end of file diff --git a/src/server/sparkd/sparkd.vcxproj.filters b/src/server/sparkd/sparkd.vcxproj.filters index c450a515b..579316745 100644 --- a/src/server/sparkd/sparkd.vcxproj.filters +++ b/src/server/sparkd/sparkd.vcxproj.filters @@ -64,6 +64,9 @@ {0a189ff2-332a-45cc-bffe-a2d16a62ab11} + + {19a71c1d-76f4-4046-925b-c593ba08388d} + @@ -220,6 +223,9 @@ spreader\hedger + + spreader\tests + @@ -432,9 +438,6 @@ setup - - spreader - spreader @@ -465,6 +468,18 @@ spreader + + spreader + + + spreader + + + spreader + + + spreader + @@ -477,4 +492,4 @@ - + \ No newline at end of file diff --git a/src/server/sparkd/spreader/ISpreaderInternalOrderBridge.h b/src/server/sparkd/spreader/ISpreaderInternalOrderBridge.h deleted file mode 100644 index 1d3cda9cb..000000000 --- a/src/server/sparkd/spreader/ISpreaderInternalOrderBridge.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -namespace bts { -namespace spreader { -class ISpreaderInternalOrderBridge -{ -public: - virtual int get_id(const api::Security& security, api::BuySell side) = 0; - virtual void send_limit_order(int client_id, bts::Price price, bts::Quantity quantity) = 0; - virtual void send_market_order(int client_id, bts::Quantity quantity) = 0; - virtual void update_order(int client_id, bts::Price price, bts::Quantity quantity) = 0; - virtual void cancel_order(int client_id) = 0; -}; -}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/ISpreaderManager.h b/src/server/sparkd/spreader/ISpreaderManager.h new file mode 100644 index 000000000..315760795 --- /dev/null +++ b/src/server/sparkd/spreader/ISpreaderManager.h @@ -0,0 +1,33 @@ +#pragma once +#include "SpreaderBase.h" + +namespace bts { +namespace spreader { +class LegPropertyData; +// spreader, spawns a bunch of SingleLegQuoters (to quote each active +// leg) and SingleFillHedgers (to hedge each fill), and offers them +// this interface, ISpreaderManager, to a. send orders and b. get data +// such as book and leg properties (this could have been pushed, but +// is avoided, to keep all the state in the main Spreader class, and +// provide easy O(1) access to the Quoter and Hedger) +class ISpreaderManager +{ +public: + // call this to send an order. OrderTemplate is used to prefill data + virtual bts::orderman::OrderKey send_limit_order(const OrderTemplate&, bts::Price price, bts::Quantity quantity) = 0; + // orders are modified through this. order_key uniquely distinguishes orders + virtual void update_order(bts::orderman::OrderKey order_key, bts::Price price, bts::Quantity quantity) = 0; + // call this to cancel orders + virtual void cancel_order(bts::orderman::OrderKey order_key) = 0; + // for a leg index, returns the Book in O(1). the caller can hold at + // reference to the returned type forever (the data in the returned + // type can change beneath it) + virtual const orderman::Book& get_book(size_t leg_index) const = 0; + // the caller can keep a reference to the returned type forever. the + // data in the returned type is all const, so nothing will change + // beneath it + virtual const LegPropertyData& get_leg_data(size_t leg_index) const = 0; + // number of legs on the spread + virtual size_t n_legs() const = 0; +}; +}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/LegPropertyData.h b/src/server/sparkd/spreader/LegPropertyData.h new file mode 100644 index 000000000..1a8425217 --- /dev/null +++ b/src/server/sparkd/spreader/LegPropertyData.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include "lib/domain_model/Security.pb.h" +#include "server/sparkd/orderman/utils/orderman_utils.h" + +#include "lib/api/services/OrderService.pb.h" +#include "lib/sparkproto/SparkProtos.pb.h" +#include "server/sparkd/orderman/md/Book.h" +#include + +namespace bts { +namespace spreader { +// collection of immutable leg data properties, shared +// between the Spreader, SingleLegQuoter and SingleFillHedger +class LegPropertyData +{ +public: + const size_t leg_index; + const bts::api::Security spread_security; + const bts::api::ContractLeg leg_contract; + const bts::spark::LegSpreaderParams leg_params; + const api::BuySell trading_side; + LegPropertyData(size_t leg_index_arg, + const bts::api::Security& spread_security_arg, + const bts::api::ContractLeg& leg_contract_arg, + const bts::spark::LegSpreaderParams& leg_params_arg, + api::BuySell trading_side_arg) + : + // copying the values via copy cons + leg_index(leg_index_arg), + spread_security(spread_security_arg), + leg_contract(leg_contract_arg), + leg_params(leg_params_arg), + trading_side (trading_side_arg) + { + } + uint32_t security_key() const { return spread_security.id(); } + double price_multiplier() const { return leg_contract.price_multiplier(); } + double size_multiplier() const { return leg_contract.quantity(); } + double tick_size() const { return leg_contract.security().contract_spec().low_tick(); } +}; + +class LegPropertyDataCollection +{ +private: + std::vector _leg_data_vector; + boost::container::flat_map _sec_key_to_index; +public: + LegPropertyDataCollection(const std::vector& leg_data_vector) + : _leg_data_vector(leg_data_vector) + { + for (auto it = leg_data_vector.begin(); it != leg_data_vector.end(); ++it) + _sec_key_to_index.insert(std::pair(it->security_key(), it->leg_index)); + } + const LegPropertyData& get_at_index(size_t index) const + { + bts_assert_d(index < _leg_data_vector.size()); + return _leg_data_vector[index]; + } + LegPropertyData& get_at_index(size_t index) + { + bts_assert_d(index < _leg_data_vector.size()); + return _leg_data_vector[index]; + } + size_t get_security_index(const api::Security& s) const + { + return get_security_index(SecurityKey(s.id())); + } + size_t get_security_index(bts::SecurityKey sec_key) const + { + auto it = _sec_key_to_index.find(sec_key.value()); + bts_assert(it != _sec_key_to_index.end()); + return it->second; + } + size_t count() const { return _leg_data_vector.size(); } +}; + +}} diff --git a/src/server/sparkd/spreader/SimpleSpreader.cpp b/src/server/sparkd/spreader/SimpleSpreader.cpp index 64439b3f7..0af7d9302 100644 --- a/src/server/sparkd/spreader/SimpleSpreader.cpp +++ b/src/server/sparkd/spreader/SimpleSpreader.cpp @@ -1,28 +1,12 @@ #include "SimpleSpreader.h" +#include "SingleLegQuoter.h" +#include "SpreaderUtils.h" +#include "SingleFillHedger.h" namespace bts { namespace spreader -{ - struct SimpleSpreaderLeg - { - const api::Security* security; - double size_ratio; - double price_multiplier; - double tick; - - bool is_working; - bool is_hedging; - - uint32_t pre_quote_outside_ticks; - uint32_t pre_quote_inside_ticks; - - int pre_hedge_payup_ticks; - - uint32_t post_hedge_ticks_threshold; - uint32_t post_hedge_cross_ticks; - }; - +{ //this is a mock up of what should proably be in the spreadercreate message class SimpleSpreaderCreate : public SpreaderCreate { @@ -34,9 +18,6 @@ namespace spreader api::orderman::CustomerOrFirm cust_code; api::orderman::CTICode cti_code; UserLogin user_login; - - public: - std::vector legs; }; struct SimpleSpreader::PImpl @@ -44,28 +25,47 @@ namespace spreader orderman::OrderKey my_key; const SimpleSpreaderCreate& create; bool connected; - PImpl(orderman::OrderKey key, const SpreaderCreate& screate) : - my_key(key), + PImpl(orderman::OrderKey key, const SpreaderCreate& screate) : + my_key(key), create(static_cast(screate)), connected(false) - { - - } - + { } void cancel_all() - { - - } + { } }; - SimpleSpreader::SimpleSpreader() { } SimpleSpreader::~SimpleSpreader() { } SpreaderSubscriptions SimpleSpreader::init(orderman::OrderKey my_key, const SpreaderCreate& create) { - me.reset(new PImpl(my_key, create)); - + const api::Security& sec = create.order.security(); + std::vector leg_data_vector; + bts_assert(sec.has_synthetic()); + size_t index = 0; + // creating the basic data + ISpreaderManager& me_ref = *this; + for (auto it = sec.synthetic().legs().begin(); it != sec.synthetic().legs().end(); ++it) + { + uint32_t sec_key = it->security().id(); + const spark::ExecutionStrategy& execution_strategy = create.order.execution_strategy(); + auto st_it = execution_strategy.leg_params_map().find(sec_key); + bts_assert(st_it != execution_strategy.leg_params_map().end()); + const bts::api::ContractLeg& leg = *it; + api::BuySell leg_order_side = SpreaderUtils::get_leg_side(create.order.side(), leg); + LegPropertyData leg_property_data(index++, sec, leg, st_it->second, leg_order_side); + SpreaderBookkeepingData::LegData leg_data(leg_property_data); + leg_data_vector.push_back(leg_data); + } + _bookkeeping_data = std::make_unique(leg_data_vector); + // now settings up the quoters + for (size_t index = 0; index < _bookkeeping_data->count(); index++) + { + OrderTemplate order_template; + SpreaderBookkeepingData::LegData& leg_data = _bookkeeping_data->get_leg_data(index); + leg_data.quoter = new SingleLegQuoter(me_ref, order_template, index, Price(create.order.price()), Quantity(create.order.size())); + } + me.reset(new PImpl(my_key, create)); SpreaderSubscriptions subs; return subs; } @@ -78,12 +78,42 @@ namespace spreader if(me->connected) me->cancel_all(); } - void SimpleSpreader::on_md(const api::Security&, const Book&) + + void SimpleSpreader::on_md(const orderman::Book& book) { + SpreaderBookkeepingData::LegData& md_leg = _bookkeeping_data->get_leg_data(book.security_key()); + md_leg.set_book(book); + for (size_t idx = 0; idx < _bookkeeping_data->count(); idx++) + { + SpreaderBookkeepingData::LegData& d = _bookkeeping_data->get_leg_data(idx); + d.quoter->update_md(md_leg.leg_shared_data.leg_index); + } + // TODO, not sending to the hedgers for now. this means post-quoting + // rules wont work } - void SimpleSpreader::on_child_order(const OrderState&, const std::vector& ) - { + + void SimpleSpreader::on_child_order(const OrderState& order_state) + { + size_t fill_leg_index; + if (_bookkeeping_data->find_quoter_from_orderkey(order_state.key, fill_leg_index)) + { + SpreaderBookkeepingData::LegData& leg_data = _bookkeeping_data->get_leg_data(fill_leg_index); + leg_data.quoter->update_order_status(order_state); + if (leg_data.filled_quantity != order_state.filled_quantity) + { + bts_assert(order_state.filled_quantity.value() > leg_data.filled_quantity.value()); + Quantity this_fill_quantity = Quantity(order_state.filled_quantity.value() - leg_data.filled_quantity.value()); + leg_data.filled_quantity = order_state.filled_quantity; + // send this to fill to everyone else + _adapt_to_fill(leg_data.leg_shared_data.leg_index, this_fill_quantity, Price(0.0)); // TODO + } + } + else + { + // hedger fill + } } + void SimpleSpreader::on_time(const TimeStamp&) { } @@ -99,5 +129,62 @@ namespace spreader void SimpleSpreader::on_system_error() { } -} -} \ No newline at end of file + + bts::orderman::OrderKey SimpleSpreader::send_limit_order(const OrderTemplate& t, bts::Price price, bts::Quantity quantity) + { + return create_child(t, price, quantity); + } + + void SimpleSpreader::update_order(bts::orderman::OrderKey order_key, bts::Price price, bts::Quantity quantity) + { + update_child(order_key, price, quantity); + } + + void SimpleSpreader::cancel_order(bts::orderman::OrderKey order_key) + { + cancel_child(order_key); + } + + const orderman::Book& SimpleSpreader::get_book(size_t leg_index) const + { + return _bookkeeping_data->get_leg_data(leg_index).book; + } + + const LegPropertyData& SimpleSpreader::get_leg_data(size_t leg_index) const + { + return _bookkeeping_data->get_leg_data(leg_index).leg_shared_data; + } + + size_t SimpleSpreader::n_legs() const + { + return _bookkeeping_data->count(); + } + + void SimpleSpreader::_adapt_to_fill(size_t leg_index, Quantity filled_quantity, Price filled_price) + { + for (size_t idx = 0; idx < _bookkeeping_data->count(); idx++) + { + if (idx != leg_index) + { + SpreaderBookkeepingData::LegData& leg_data = _bookkeeping_data->get_leg_data(idx); + leg_data.quoter->update_other_leg_fills(idx, filled_quantity); + _send_hedge(leg_index, filled_price, filled_quantity, idx); + } + } + } + + void SimpleSpreader::_send_hedge(size_t filled_leg_index, Price filled_price, Quantity filled_quantity, size_t leg_index) + { + Price hedge_price; Quantity hedge_quantity; + _compute_hedge_price_quantity(filled_leg_index, filled_price, filled_quantity, + leg_index, hedge_price, hedge_quantity); + // TODO + //SingleFillHedger* hedger = new SingleFillHedger () + } + + void SimpleSpreader::_compute_hedge_price_quantity(size_t, + Price, Quantity, + size_t, + Price&, Quantity&) + {} +}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/SimpleSpreader.h b/src/server/sparkd/spreader/SimpleSpreader.h index d25983f4e..1fd14fa29 100644 --- a/src/server/sparkd/spreader/SimpleSpreader.h +++ b/src/server/sparkd/spreader/SimpleSpreader.h @@ -1,33 +1,59 @@ #pragma once +#include #include "SpreaderBase.h" +#include "ISpreaderManager.h" +#include "LegPropertyData.h" +#include "SpreaderBookkeepingData.h" namespace bts { namespace spreader { - class SimpleSpreader : public SpreaderBase + class SingleFillHedger; + class SingleLegQuoter; + + class SimpleSpreader : public SpreaderBase, public ISpreaderManager { public: SimpleSpreader(); virtual ~SimpleSpreader(); SpreaderSubscriptions init(orderman::OrderKey my_key, const SpreaderCreate&); - virtual void on_connect(); - virtual void on_disconnect(); + void on_connect() override; + void on_disconnect() override; - virtual void on_md(const api::Security&, const Book&); - virtual void on_child_order(const OrderState&, const std::vector&); - virtual void on_time(const TimeStamp&); - virtual void on_user_update(const SpreaderUpdate&); - virtual void on_user_cancel(); + void on_md(const orderman::Book&) override; + void on_child_order(const OrderState&) override; + void on_time(const TimeStamp&) override; + void on_user_update(const SpreaderUpdate&) override; + void on_user_cancel() override; - virtual void on_limit_breach(); - virtual void on_system_error(); + void on_limit_breach() override; + void on_system_error() override; + + // ISpreaderManager members + bts::orderman::OrderKey send_limit_order(const OrderTemplate&, bts::Price price, bts::Quantity quantity) override; + void update_order(bts::orderman::OrderKey order_key, bts::Price price, bts::Quantity quantity) override; + void cancel_order(bts::orderman::OrderKey order_key) override; + const orderman::Book& get_book(size_t leg_index) const override; + const LegPropertyData& get_leg_data(size_t leg_index) const override; + virtual size_t n_legs() const override; - private: struct PImpl; std::unique_ptr me; + private: + std::unique_ptr _bookkeeping_data; + + void _adapt_to_fill(size_t leg_index, Quantity filled_quantity, Price filled_price); + + void _compute_hedge_price_quantity(size_t filled_leg_index, + Price filled_price, Quantity filled_quantity, + size_t hedged_index, + Price& hedge_price, Quantity& hedge_quantity); + + void _send_hedge(size_t filled_leg_index, Price filled_price, Quantity filled_quantity, size_t leg_to_hedge_index); + }; } } \ No newline at end of file diff --git a/src/server/sparkd/spreader/SingleFillHedger.cpp b/src/server/sparkd/spreader/SingleFillHedger.cpp index 7ff2ce102..4bf163ff8 100644 --- a/src/server/sparkd/spreader/SingleFillHedger.cpp +++ b/src/server/sparkd/spreader/SingleFillHedger.cpp @@ -1,26 +1,25 @@ #include #include "SingleFillHedger.h" -#include "ISpreaderInternalOrderBridge.h" +#include "ISpreaderManager.h" #include "SpreaderUtils.h" namespace bts { namespace spreader { -SingleFillHedger::SingleFillHedger(ISpreaderInternalOrderBridge* order_bridge, - int order_client_id, - bts::api::ContractLeg const& this_leg, - const bts::spark::ExecutionStrategy& execution_strategy, +SingleFillHedger::SingleFillHedger(ISpreaderManager& spreader_manager, + size_t leg_index, + const OrderTemplate& order_template, + const LegPropertyData& leg_property_data, bts::Price hedge_price, bts::Quantity hedge_quantity, api::BuySell hedge_side) : - _tick_size(this_leg.security().contract_spec().low_tick()), - _order_client_id(order_client_id), - // _contract_leg(this_leg), - _post_hedge_params(SpreaderUtils::get_leg_params(execution_strategy,this_leg).post_hedge_params()), + _spreader_manager(spreader_manager), + _leg_index (leg_index), + _order_template (order_template), + _leg_property_data (leg_property_data), _price_quantity_state(hedge_price, hedge_quantity, hedge_side), - _state(HedgerState::START), - _order_bridge(order_bridge) + _state(HedgerState::START) { } @@ -36,10 +35,9 @@ void SingleFillHedger::update_order_state(const OrderState& order_state) _fire_event(event_data); } -void SingleFillHedger::update_md(const Book &b) +void SingleFillHedger::update_md() { - _book = b; - SingleFillHedger::EventData event_data(&b); + SingleFillHedger::EventData event_data(ExternalHedgerEvents::MDUpdate); _fire_event(event_data); } @@ -73,7 +71,7 @@ void SingleFillHedger::transform_to_WAITING_FOR_FIRST_ACK() _state = HedgerState::WAITING_FOR_FIRST_ACK; // The order is sent for the one and only time here // TODO check for market orders pre hedge rule - _order_bridge->send_limit_order(_order_client_id, _price_quantity_state.target_price(), _price_quantity_state.target_quantity()); + _order_key = _spreader_manager.send_limit_order(_order_template, _price_quantity_state.target_price(), _price_quantity_state.target_quantity()); } void SingleFillHedger::_handle_events_in_WAITING_FOR_FIRST_ACK(const EventData& event_data) @@ -125,7 +123,7 @@ void SingleFillHedger::_handle_events_in_WORKING(const EventData& event_data) else if (event_data.external_event == ExternalHedgerEvents::UserHedgePriceChange) { _price_quantity_state.udpate_target_price(event_data.hedge_price); - _order_bridge->update_order(_order_client_id, _price_quantity_state.target_price(), _price_quantity_state.target_quantity()); + _spreader_manager.update_order(_order_key, _price_quantity_state.target_price(), _price_quantity_state.target_quantity()); } else if (event_data.external_event == ExternalHedgerEvents::HedgeCancel) transform_to_WAITING_FOR_CANCEL_ACK(); @@ -137,7 +135,7 @@ void SingleFillHedger::transform_to_WAITING_FOR_CANCEL_ACK() { bts_assert(_state == HedgerState::WAITING_FOR_FIRST_ACK || _state == HedgerState::WORKING); _state = HedgerState::WAITING_FOR_CANCEL_ACK; - _order_bridge->cancel_order(_order_client_id); + _spreader_manager.cancel_order(_order_key); } void SingleFillHedger::_handle_events_in_WAITING_FOR_CANCEL_ACK(const EventData& event_data) { diff --git a/src/server/sparkd/spreader/SingleFillHedger.h b/src/server/sparkd/spreader/SingleFillHedger.h index d815f4cd6..2b286e6bd 100644 --- a/src/server/sparkd/spreader/SingleFillHedger.h +++ b/src/server/sparkd/spreader/SingleFillHedger.h @@ -8,9 +8,8 @@ namespace bts { namespace spreader { - -class ISpreaderInternalOrderBridge; - +class ISpreaderManager; +class LegPropertyData; class SingleFillHedger { enum class ExternalHedgerEvents @@ -40,38 +39,27 @@ class SingleFillHedger public: const ExternalHedgerEvents external_event; const OrderState* order_state; - const Book* book; const Price hedge_price; EventData(const OrderState* order_state_arg) : external_event(ExternalHedgerEvents::OrderState), order_state(order_state_arg), - book(NULL), - hedge_price(0.0) - {} - EventData(const Book* book_arg) - : external_event(ExternalHedgerEvents::MDUpdate), - order_state(NULL), - book(book_arg), hedge_price(0.0) {} EventData(Price hedge_price_arg) : external_event(ExternalHedgerEvents::UserHedgePriceChange), order_state(NULL), - book(NULL), hedge_price(hedge_price_arg) {} EventData(ExternalHedgerEvents external_event_arg) : external_event(external_event_arg), order_state(NULL), - book(NULL), hedge_price(0.0) {} private: EventData() : external_event(ExternalHedgerEvents::Timer), order_state(NULL), - book(NULL), hedge_price(0.0) {} }; @@ -121,14 +109,13 @@ class SingleFillHedger }; private: - const double _tick_size; - const int _order_client_id; - // const bts::api::ContractLeg& _contract_leg; - const bts::spark::PostHedgeParams& _post_hedge_params; + ISpreaderManager& _spreader_manager; + const size_t _leg_index; + const OrderTemplate& _order_template; + const LegPropertyData& _leg_property_data; HedgePriceQuantityState _price_quantity_state; - HedgerState _state; - ISpreaderInternalOrderBridge* _order_bridge; - Book _book; + HedgerState _state; + bts::orderman::OrderKey _order_key; private: /********************External Event Handling in START***********************/ void _handle_events_in_START(const EventData& event_data); @@ -147,14 +134,14 @@ private: void _fire_event(const EventData& event_data); public: - SingleFillHedger(ISpreaderInternalOrderBridge* order_bridge, - int order_client_id, - bts::api::ContractLeg const& this_leg, - const bts::spark::ExecutionStrategy& execution_strategy, - bts::Price hedge_price, - bts::Quantity hedge_quantity, - api::BuySell hedge_side); - + SingleFillHedger(ISpreaderManager& spreader_manager, + size_t leg_index, + const OrderTemplate& order_template, + const LegPropertyData& leg_property_data, + bts::Price hedge_price, + bts::Quantity hedge_quantity, + api::BuySell hedge_side); + ~SingleFillHedger() {} // true if the hedger has an active working order bool is_active(); // true if the hedger can accept a price change @@ -166,7 +153,7 @@ public: void update_order_state(OrderState const& state); // called when the market data associated // with this security is changed - void update_md(Book const&b); + void update_md(); // called when a user changed the price of a working // hedge order void modify_hedge_price(Price new_hedge_price); diff --git a/src/server/sparkd/spreader/SingleLegQuoter.cpp b/src/server/sparkd/spreader/SingleLegQuoter.cpp index 9bf912c4c..5e6774ca9 100644 --- a/src/server/sparkd/spreader/SingleLegQuoter.cpp +++ b/src/server/sparkd/spreader/SingleLegQuoter.cpp @@ -1,96 +1,69 @@ #include #include "SingleLegQuoter.h" -#include "ISpreaderInternalOrderBridge.h" +#include "ISpreaderManager.h" #include "SpreaderUtils.h" +#include "LegPropertyData.h" namespace bts { namespace spreader { -SingleLegQuoter::SingleLegQuoter(ISpreaderInternalOrderBridge* order_bridge, - api::Security const& spread_security, - bts::api::ContractLeg const& this_leg, - const bts::spark::ExecutionStrategy& execution_strategy, +SingleLegQuoter::SingleLegQuoter(ISpreaderManager& order_bridge, + const OrderTemplate& order_template, + size_t leg_index, bts::Price spread_order_price, - bts::Quantity spread_order_quantity, - api::BuySell side) + bts::Quantity spread_order_quantity) : - _tick_size(this_leg.security().contract_spec().low_tick()), - _size_ratio(this_leg.quantity()), - _spread_security(spread_security), - _contract_leg(this_leg), + _tick_size(order_bridge.get_leg_data(leg_index).leg_contract.security().contract_spec().low_tick()), _order_bridge(order_bridge), - _bridge_client_id(order_bridge->get_id(_contract_leg.security(), _contract_leg.side())), - _side(side), - _quote_side(SpreaderUtils::get_leg_side(_side, _contract_leg)), - _this_leg_index(SpreaderUtils::get_leg_index(_spread_security, _contract_leg)), - _quote_params(SpreaderUtils::get_leg_params(execution_strategy, _contract_leg).quote_params()), + _order_template (order_template), + _this_leg_data (order_bridge.get_leg_data(leg_index)), + _this_leg_index(leg_index), _state(QuoterState::START), - _price_quantity_state(QuoteLegPriceQuantityState(spread_order_price, Quantity(static_cast(spread_order_quantity.value() * _contract_leg.quantity())))) + _price_quantity_state(QuoteLegPriceQuantityState(spread_order_price, Quantity(static_cast(spread_order_quantity.value() * _this_leg_data.size_multiplier())))) { - _leg_data.reserve(spread_security.synthetic().legs_size()); - _aux_comp_data.reserve(spread_security.synthetic().legs_size()); - size_t n_legs = static_cast(spread_security.synthetic().legs_size()); - for (size_t i = 0; i < n_legs; i++) - { - auto leg_contract = spread_security.synthetic().legs(i); - auto leg_params_it = execution_strategy.leg_params_map().find(leg_contract.security().id()); - bts_assert(leg_params_it != execution_strategy.leg_params_map().end()); - bts::spark::LegSpreaderParams leg_params = leg_params_it->second; - double leg_lean_ratio = leg_params.quote_params().lean_quantity_ratio() * (static_cast(leg_contract.quantity()) / static_cast(this_leg.quantity())); - LegData leg_data = LegData(leg_contract, leg_params, *(new bts::spreader::Book()), leg_lean_ratio); - _leg_data.push_back(leg_data); - _key_index_map.insert(std::pair(leg_contract.security().id(), i)); - } + _aux_comp_data.reserve(order_bridge.n_legs()); } -bool SingleLegQuoter::is_active() { return _state == QuoterState::WAITING_FOR_FIRST_ACK || _state == QuoterState::WORKING || _state == QuoterState::WAITING_FOR_CANCEL_ACK; } +bool SingleLegQuoter::is_active() const { return _state == QuoterState::WAITING_FOR_FIRST_ACK || _state == QuoterState::WORKING || _state == QuoterState::WAITING_FOR_CANCEL_ACK; } -bool SingleLegQuoter::accept_modifications() { return _state == QuoterState::WAITING_FOR_MARKET || _state == QuoterState::WORKING; } +bool SingleLegQuoter::accept_modifications() const { return _state == QuoterState::WAITING_FOR_MARKET || _state == QuoterState::WORKING; } void SingleLegQuoter::update_order_status(OrderState const& order_state) { - _event_data.set_order_event(order_state); - _fire_event(_event_data); + EventData ev(order_state); + _fire_event(ev); } -void SingleLegQuoter::update_md(api::Security const& s, Book const& b) +void SingleLegQuoter::update_md(size_t leg_index) { - size_t index = 0; - if (SpreaderUtils::find_index(_key_index_map, s.id(), index)) - { - _event_data.set_md_event(index, b); - _fire_event(_event_data); - } + EventData ev(leg_index); + _fire_event(ev); } -void SingleLegQuoter::update_other_leg_fills(api::Security const& security, Quantity filled_quantity, Price) +void SingleLegQuoter::update_other_leg_fills(size_t leg_index, Quantity filled_quantity) { - size_t leg_index; - if (SpreaderUtils::find_index(_key_index_map, security.id(), leg_index)) - { - double equivelant_quantity = _get_equivelant_quantity(leg_index, filled_quantity); - uint32_t this_leg_reduction = static_cast (equivelant_quantity); - _event_data.set_other_leg_quoting_fill(Quantity(this_leg_reduction)); - } + double equivelant_quantity = _get_equivelant_quantity(leg_index, filled_quantity); + uint32_t this_leg_reduction = static_cast (equivelant_quantity); + EventData ev(Quantity(this_leg_reduction), ExternalEvents::OtherLegQuotingFill); } void SingleLegQuoter::modify_order_price(Price new_price) { - _event_data.set_new_spread_price(new_price); - _fire_event(_event_data); + EventData ev(new_price); + _fire_event(ev); } void SingleLegQuoter::modify_order_quantity(Quantity new_quantity) { - double leg_quantity_d = _size_ratio * new_quantity.value(); - _event_data.set_new_leg_quantity(Quantity(leg_quantity_d)); - _fire_event(_event_data); + double leg_quantity_d = _this_leg_data.size_multiplier() * new_quantity.value(); + EventData ev(Quantity(leg_quantity_d), ExternalEvents::SpreadQuantityChange); + _fire_event(ev); } void SingleLegQuoter::cancel_order() { - _event_data.set_cancel_order(); - _fire_event(_event_data); + EventData ev(ExternalEvents::CancelOrder); + _fire_event(ev); } /**********************************************************************/ @@ -127,7 +100,7 @@ void SingleLegQuoter::_handle_events_in_WAITING_FOR_MARKET(const EventData& even bts_assert(false); else if (event_data.external_event == ExternalEvents::MDUpdate) { - _leg_data.at(event_data.book_leg_index).book = event_data.book; + //_leg_data.at(event_data.book_leg_index).book = event_data.book; _check_md_in_WAITING_FOR_MARKET(); } else if (event_data.external_event == ExternalEvents::OtherLegQuotingFill) @@ -165,7 +138,6 @@ void SingleLegQuoter::_handle_events_in_WAITING_FOR_MARKET(const EventData& even _transform_to_END(); } } - /********************************************************************************/ /*****************External Event Handling in WAITING_FOR_FIRST_ACK***************/ /********************************************************************************/ @@ -181,14 +153,14 @@ void SingleLegQuoter::_tranform_to_WAITING_FOR_FIRST_ACK() bts_assert(quantity.value() > 0); _price_quantity_state.update_out_price_quantity(price, quantity); // This is the first and only time a quoting order is sent - _order_bridge->send_limit_order(_bridge_client_id, _price_quantity_state.out_price(), _price_quantity_state.out_quantity()); + _order_key = _order_bridge.send_limit_order(_order_template, _price_quantity_state.out_price(), _price_quantity_state.out_quantity()); } void SingleLegQuoter::_handle_events_in_WAITING_FOR_FIRST_ACK(const EventData& event_data) { if (event_data.external_event == ExternalEvents::OrderStateUpdate) { - OrderState& order_state = event_data.order_state; + const OrderState& order_state = *(event_data.order_state); bool filled, terminal_state, encountered_error, new_fills; SpreaderUtils::parse_order(order_state, _price_quantity_state.aggregated_filled_quantity(), filled, terminal_state, encountered_error, new_fills); _price_quantity_state.update_filled_quantity(order_state.filled_quantity); @@ -258,17 +230,17 @@ void SingleLegQuoter::_reprice_in_WORKING() if (new_quantity.value() != _price_quantity_state.out_quantity().value()) { _price_quantity_state.update_out_price_quantity(new_price, new_quantity); - _order_bridge->update_order(_bridge_client_id, new_price, new_quantity); + _order_bridge.update_order(_order_key, new_price, new_quantity); } else { bool reprice = true; - if (_quote_params.has_quote_mute_zone()) - reprice = SpreaderUtils::reprice_quote_mute_zone(_price_quantity_state.out_price().value(), new_price.value(), _quote_side, _tick_size, _quote_params.quote_mute_zone()); + if (_this_leg_data.leg_params.quote_params().has_quote_mute_zone()) + reprice = SpreaderUtils::reprice_quote_mute_zone(_price_quantity_state.out_price().value(), new_price.value(), _this_leg_data.trading_side, _tick_size, _this_leg_data.leg_params.quote_params().quote_mute_zone()); if (reprice) { _price_quantity_state.update_out_price_quantity(new_price, new_quantity); - _order_bridge->update_order(_bridge_client_id, new_price, new_quantity); + _order_bridge.update_order(_order_key, new_price, new_quantity); } } } @@ -278,7 +250,7 @@ void SingleLegQuoter::_handle_events_in_WORKING(const EventData& event_data) { if (event_data.external_event == ExternalEvents::OrderStateUpdate) { - const OrderState& order_state = event_data.order_state; + const OrderState& order_state = *(event_data.order_state); bool filled, terminal_state, encountered_error, new_fills; SpreaderUtils::parse_order(order_state, _price_quantity_state.aggregated_filled_quantity(), filled, terminal_state, encountered_error, new_fills); _price_quantity_state.update_filled_quantity(order_state.filled_quantity); @@ -342,14 +314,14 @@ void SingleLegQuoter::_transform_to_WAITING_FOR_CANCEL_ACK() bts_assert(_state == QuoterState::WAITING_FOR_FIRST_ACK || _state == QuoterState::WORKING); _state = QuoterState::WAITING_FOR_CANCEL_ACK; // this is only place where the order is cancelled - _order_bridge->cancel_order(_bridge_client_id); + _order_bridge.cancel_order(_order_key); } void SingleLegQuoter::_handle_events_in_WAITING_FOR_CANCEL_ACK(const EventData& event_data) { if (event_data.external_event == ExternalEvents::OrderStateUpdate) { - const OrderState& order_state = event_data.order_state; + const OrderState& order_state = *(event_data.order_state); bool filled, terminal_state, encountered_error, new_fills; SpreaderUtils::parse_order(order_state, _price_quantity_state.aggregated_filled_quantity(), filled, terminal_state, encountered_error, new_fills); _price_quantity_state.update_filled_quantity(order_state.filled_quantity); @@ -414,16 +386,16 @@ void SingleLegQuoter::_fire_event(const EventData& event_data) void SingleLegQuoter::_compute_price_quantity(Price& price, Quantity& quantity) { - size_t idx = 0, min_quoter_leg_quantity_index = 0; - for (auto it = _leg_data.begin(); it != _leg_data.end(); it++) + size_t min_quoter_leg_quantity_index = 0; + for (size_t idx = 0; idx < _order_bridge.n_legs(); idx++) { if (idx != _this_leg_index) { - const Book& leg_book = it->book; + const orderman::Book leg_book = _order_bridge.get_book(idx); Price leg_price; Quantity leg_quantity, quoter_leg_quantity; Quantity leg_target_quantity = _price_quantity_state.remaining_to_fill(); - SpreaderUtils::traverse_depth_for_quantity(leg_book, api::BuySell::BUY, Quantity(static_cast(leg_target_quantity.value() * it->lean_ratio)), leg_price, leg_quantity); - quoter_leg_quantity = Quantity(static_cast(it->lean_ratio * leg_quantity.value())); + SpreaderUtils::traverse_depth_for_quantity(leg_book, api::BuySell::BUY, Quantity(static_cast(leg_target_quantity.value() * 1.0 /*TODO*/)), leg_price, leg_quantity); + quoter_leg_quantity = Quantity(static_cast(1.0 /*TODOit->lean_ratio*/ * leg_quantity.value())); PQPair& leg_price_quantity = _aux_comp_data.at(idx); leg_price_quantity.set(leg_price, leg_quantity, quoter_leg_quantity); if (_aux_comp_data.at(min_quoter_leg_quantity_index).quoter_leg_quantity.value() <= quoter_leg_quantity.value()) @@ -443,12 +415,19 @@ Price SingleLegQuoter::_compute_leg_price(const std::vector& leg_values) { if (idx != _this_leg_index) { - LegData& leg_data = _leg_data.at(idx); - sum += it->leg_price.value() * leg_data.price_ratio(); + const LegPropertyData& leg_data = _order_bridge.get_leg_data (idx); + sum += it->leg_price.value() * leg_data.price_multiplier(); } } double rv = _price_quantity_state.target_spread_price().value() - sum; /// TODO, needs a divisor return Price(rv); } +double SingleLegQuoter::_get_equivelant_quantity(size_t leg_index, Quantity quantity) +{ + const LegPropertyData& leg_data = _order_bridge.get_leg_data(leg_index); + const LegPropertyData& this_leg_data = _order_bridge.get_leg_data(_this_leg_index); + return static_cast (quantity.value() * this_leg_data.leg_contract.quantity() / leg_data.leg_contract.quantity()); +} + }} \ No newline at end of file diff --git a/src/server/sparkd/spreader/SingleLegQuoter.h b/src/server/sparkd/spreader/SingleLegQuoter.h index 2acf2ed57..7d9158831 100644 --- a/src/server/sparkd/spreader/SingleLegQuoter.h +++ b/src/server/sparkd/spreader/SingleLegQuoter.h @@ -3,16 +3,16 @@ #include #include "SpreaderBase.h" #include "QuoteLegPriceQuantityState.h" +#include "LegPropertyData.h" #include namespace bts { namespace spreader { -class ISpreaderInternalOrderBridge; - +class ISpreaderManager; class SingleLegQuoter -{ +{ // this represents all signals generated // esternally that the quoter is interested in enum class ExternalEvents @@ -34,7 +34,6 @@ class SingleLegQuoter // leg price changes from the user LegPriceChange, }; - // the states of the quoter state machine enum class QuoterState { @@ -72,54 +71,42 @@ class SingleLegQuoter { public: ExternalEvents external_event; - OrderState& order_state; + const OrderState* order_state; size_t book_leg_index; - Book& book; Price new_spread_price; Quantity new_leg_quantity; Quantity other_leg_filled_quanity; - - EventData() - : order_state (*(new OrderState())), - book (*(new Book())) + + EventData(ExternalEvents external_event_args) + : + external_event(external_event_args) + {} + EventData (const OrderState& order_state_arg) + : + external_event(ExternalEvents::OrderStateUpdate), + order_state (&order_state_arg) + {} + EventData(size_t book_leg_index_arg) + : + external_event(ExternalEvents::MDUpdate), + book_leg_index(book_leg_index_arg) + {} + EventData(Price new_spread_price_arg) + : + external_event(ExternalEvents::SpreadPriceChange), + new_spread_price(new_spread_price_arg) + {} + EventData(Quantity new_leg_quantity_arg) + : + external_event(ExternalEvents::SpreadQuantityChange), + new_leg_quantity(new_leg_quantity_arg) + {} + EventData(Quantity filled_quantity, ExternalEvents external_event_args) { - external_event = ExternalEvents::MDUpdate; - } - - void set_order_event(const OrderState& order_state_arg) - { - external_event = ExternalEvents::OrderStateUpdate; - order_state = order_state_arg; - } - - void set_md_event(size_t leg_index_arg, const Book& book_arg) - { - external_event = ExternalEvents::MDUpdate; - book_leg_index = leg_index_arg; - book = book_arg; - } - - void set_other_leg_quoting_fill(Quantity other_leg_filled_quanity_arg) - { - external_event = ExternalEvents::OtherLegQuotingFill; - other_leg_filled_quanity = other_leg_filled_quanity_arg; - } - - void set_new_spread_price(Price new_spread_price_arg) - { - external_event = ExternalEvents::SpreadPriceChange; - new_spread_price = new_spread_price_arg; - } - - void set_new_leg_quantity(Quantity new_leg_quantity_arg) - { - external_event = ExternalEvents::SpreadQuantityChange; - new_leg_quantity = new_leg_quantity_arg; - } - - void set_cancel_order() - { - external_event = ExternalEvents::CancelOrder; + if (external_event_args == ExternalEvents::SpreadQuantityChange) + new_leg_quantity = filled_quantity; + else if (external_event_args == ExternalEvents::OtherLegQuotingFill) + other_leg_filled_quanity = filled_quantity; } }; @@ -141,58 +128,22 @@ class SingleLegQuoter quoter_leg_quantity = new_quoter_leg_quantity; } }; - - struct LegData - { - public: - const bts::api::ContractLeg& contract; - const bts::spark::LegSpreaderParams& params; - Book& book; - // lean ratio of this leg (l2) wrt to the quoter's leg (l1). - // in other words, to price 1 lot of l1, we have to look - // into to l2's book with a target qty of lean ratio. - const double lean_ratio; - const double equivelant_quoter_leg; - - LegData(bts::api::ContractLeg& leg_contract, - bts::spark::LegSpreaderParams& leg_params, - Book& leg_book, - double leg_lean_ratio) - : contract(leg_contract), - params(leg_params), - book(leg_book), - lean_ratio(leg_lean_ratio), - equivelant_quoter_leg(1.0 / leg_lean_ratio) - {} - - double price_ratio() { return contract.price_multiplier(); } - }; - private: const double _tick_size; - const double _size_ratio; - const bts::api::Security& _spread_security; - const bts::api::ContractLeg& _contract_leg; - ISpreaderInternalOrderBridge* _order_bridge; - const int _bridge_client_id; - const api::BuySell _side; - const api::BuySell _quote_side; + ISpreaderManager& _order_bridge; + const OrderTemplate& _order_template; + const LegPropertyData& _this_leg_data; const size_t _this_leg_index; - const bts::spark::QuoteParams& _quote_params; - boost::container::flat_map _key_index_map; - std::vector _leg_data; std::vector _aux_comp_data; - EventData _event_data; QuoterState _state; QuoteLegPriceQuantityState _price_quantity_state; + bts::orderman::OrderKey _order_key; public: - SingleLegQuoter(ISpreaderInternalOrderBridge* order_bridge, - api::Security const& spread_security, - bts::api::ContractLeg const& this_leg, - const bts::spark::ExecutionStrategy& execution_strategy, - bts::Price spread_order_price, - bts::Quantity spread_order_quantity, - api::BuySell side); + SingleLegQuoter(ISpreaderManager& order_bridge, + const OrderTemplate& order_template, + size_t this_leg_index, + bts::Price spread_order_price, + bts::Quantity spread_order_quantity); ~SingleLegQuoter() { @@ -200,20 +151,20 @@ public: // true if the quoter has an active working order. the order can // be in an unknown state, but as long as an order has been sent // and it has not reached a terminal state, its considered "active" - bool is_active(); + bool is_active() const; // the quoter returns true if it is in a state where orders // can be modified - bool accept_modifications(); + bool accept_modifications() const; // called by the spreader a change in order status (or fills) is // reported by the exchange void update_order_status(OrderState const& state); // called when the market data associated // with this security is changed - void update_md(api::Security const&s, Book const&b); + void update_md(size_t leg_index); // this is called by the spreader when a quoting fill // (ie not hedging fill) happens on one of the quoting // legs - void update_other_leg_fills(api::Security const& other_leg_security, Quantity filled_quantity, Price filled_price); + void update_other_leg_fills(size_t leg_index, Quantity filled_quantity); // called when the user modified the spreader order price void modify_order_price(Price new_spread_price); // called when the user modifies the quantity @@ -250,16 +201,10 @@ private: void _fire_event(const EventData& event_data); // using the size ratios returns the size of this leg, corresponding // to the size of an other leg. - double _get_equivelant_quantity(size_t leg_index, Quantity quantity) - { - bts_assert(leg_index < _leg_data.size()); - const LegData& leg_data = _leg_data.at(leg_index); - const LegData& this_leg_data = _leg_data.at(_this_leg_index); - return static_cast (quantity.value() * this_leg_data.contract.quantity() / leg_data.contract.quantity()); - } + double _get_equivelant_quantity(size_t leg_index, Quantity quantity); // using the market of the other legs, computes the // quoting price and quantity, and if the quantity > 0 void _compute_price_quantity(Price& price, Quantity& quantity); Price _compute_leg_price(const std::vector& leg_values); }; -}} +}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/SpreaderBase.h b/src/server/sparkd/spreader/SpreaderBase.h index b98bf2a9d..9df4f315f 100644 --- a/src/server/sparkd/spreader/SpreaderBase.h +++ b/src/server/sparkd/spreader/SpreaderBase.h @@ -7,6 +7,7 @@ #include "lib/api/services/OrderService.pb.h" #include "lib/utils/bts_chrono.h" #include "lib/sparkproto/SparkProtos.pb.h" +#include "server/sparkd/orderman/md/Book.h" namespace bts { namespace spreader { @@ -16,37 +17,40 @@ namespace spreader { class OrderState { public: orderman::OrderKey key; - api::orderman::OrderStatus status; + api::orderman::OrderStatus status; Quantity filled_quantity; Quantity remaining_quantity; std::string error_msg; }; -// a market data update -class Book { -public: - size_t n_levels() const { return 0; } - Price settlement() const { return Price(0.0); } - std::tuple level(api::BuySell, size_t) const { return std::make_tuple(Price(0.0), Quantity(0)); } -}; - -class ChildFill { -public: - Price price; - Quantity quantity; -}; - // a class used to speed up order generation. it will include // pre-generated FIX for parts of the order that are known ahead of // time. -class OrderTemplate ; +class OrderTemplate +{ +}; // whatever the spreader needs to operate. this must include all the // elements used in make_order_template() -class SpreaderCreate {}; +class SpreaderCreate { +public: + const bts::spark::Order& order; + SpreaderCreate(bts::spark::Order& order_arg) + : order(order_arg) + {} +}; // whatever is supported for spreader changes -class SpreaderUpdate {}; +class SpreaderUpdate +{ +public: + const Price price; + const Quantity quantity; + SpreaderUpdate(Price new_price, Quantity new_quantity) + : price(new_price), + quantity(new_quantity) + {} +}; struct SpreaderSubscriptions { @@ -78,11 +82,11 @@ public: // securites returned in the init() will be forwarded. Market data // subscriptionsa are automatically canceled when the spreader // transitions to a terminal state. - virtual void on_md(api::Security const&s, Book const&b) = 0; + virtual void on_md(const orderman::Book& book) = 0; // called whenever a child order updates, as long as the spreader // is not in a terminal state. - virtual void on_child_order ( OrderState const&state, std::vector const&fills) = 0; + virtual void on_child_order (OrderState const&state) = 0; // called at an unspecified rate as long as the spreader is not in // a terminal state @@ -103,26 +107,35 @@ public: protected: // call this whenever the Spreader changes its OrderState - void report_state(OrderState const&); + void report_state(OrderState const&) {} // call this when spining a new order. for speed create a template // object before with the things that do not commonly change. - orderman::OrderKey create_child(OrderTemplate const&t, Price price, Quantity quantity); + orderman::OrderKey create_child(OrderTemplate const&, Price, Quantity) + { + orderman::OrderKey k(0); + return k; + } // call this to update an order you previously created - void update_child(orderman::OrderKey, Price price, Quantity quantity); + void update_child(orderman::OrderKey, Price, Quantity) + { + } // call this to cancel an order you previously created - void cancel_child(orderman::OrderKey); + void cancel_child(orderman::OrderKey) {} // use this to accelarate the creation of new orders OrderTemplate const& make_order_template(api::Security const&, orderman::AccountName const &, orderman::OperatorID const &, - api::BuySell , - api::orderman::CustomerOrFirm , - api::orderman::CTICode , - UserLogin const&); + api::BuySell, + api::orderman::CustomerOrFirm, + api::orderman::CTICode, + UserLogin const&) + { + return *new OrderTemplate(); + } }; }} diff --git a/src/server/sparkd/spreader/SpreaderBookkeepingData.h b/src/server/sparkd/spreader/SpreaderBookkeepingData.h new file mode 100644 index 000000000..24995bdce --- /dev/null +++ b/src/server/sparkd/spreader/SpreaderBookkeepingData.h @@ -0,0 +1,122 @@ +#pragma once +#include +#include "LegPropertyData.h" +#include "SingleLegQuoter.h" +#include "SingleFillHedger.h" +#include + +namespace bts{ +namespace spreader { +// encapsulates, organizes and provides easy access and lookups +// for data needed by the spreader +class SpreaderBookkeepingData +{ +public: + // includes hedger, order the hedger is working + // on and order price/quantity + class HedgerData + { + public: + SingleFillHedger* hedger; + orderman::OrderKey order_key; + Quantity quotes_filled; + Price average_filled_price; + HedgerData(SingleFillHedger* hedger_arg) + { + hedger = hedger_arg; + quotes_filled = Quantity(0); + } + void update_fill(Quantity total_filled_arg) { quotes_filled = total_filled_arg; } + }; + + // all the data for a leg, mainly + // 1. immutable property data + // 2. market data (book) + // 3. quoter + // 4. order key + // 5. order price and quantity + // 6. all the hedgers for this leg (ie when fills happens + // on other legs, and they are hedged in this leg) + class LegData + { + public: + const LegPropertyData leg_shared_data; + orderman::Book book; + SingleLegQuoter* quoter; + Quantity filled_quantity; + orderman::OrderKey order_key; + std::vector hedger_data_vector; + + LegData(const LegPropertyData& leg_shared_data_arg) + : + leg_shared_data(leg_shared_data_arg), + filled_quantity (Quantity (0)) + { + } + + void set_book(const orderman::Book& book_arg) + { + // copying by value here + book = book_arg; + } + + bool find_hedger(orderman::OrderKey order_key, HedgerData& hedger_data_out) + { + for (auto it = hedger_data_vector.begin(); it < hedger_data_vector.end(); it++) + if (it->order_key == order_key) + { + hedger_data_out = *it; + return true; + } + return false; + } + }; + +private: + std::vector _leg_data; + boost::container::flat_map _sec_key_to_index; +public: + SpreaderBookkeepingData(const std::vector& leg_data) + : + _leg_data (leg_data) + { + for (auto it = leg_data.begin(); it != leg_data.end(); ++it) + _sec_key_to_index.insert(std::pair(it->leg_shared_data.security_key(), it->leg_shared_data.leg_index)); + } + bool get_index(SecurityKey sec_key, size_t& index) + { + boost::container::flat_map::const_iterator it = _sec_key_to_index.find(sec_key.value()); + if (it != _sec_key_to_index.end()) + { + index = it->second; + return true; + } + else + return false; + } + LegData& get_leg_data(SecurityKey security_key) + { + boost::container::flat_map::const_iterator it = _sec_key_to_index.find(security_key.value()); + return _leg_data[it->second]; + } + LegData& get_leg_data(size_t index) + { + bts_assert(index < _leg_data.size()); + return _leg_data[index]; + } + size_t count() { return _leg_data.size(); } + + bool find_quoter_from_orderkey(orderman::OrderKey orderkey, size_t& index) + { + index = 0; + for (std::vector::iterator it = _leg_data.begin(); it != _leg_data.end(); ++it) + { + if (it->order_key.operator== (orderkey)) + return true; + index++; + } + return false; + } +}; + +}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/SpreaderOrderUpdateMessage.h b/src/server/sparkd/spreader/SpreaderOrderUpdateMessage.h new file mode 100644 index 000000000..0f3464227 --- /dev/null +++ b/src/server/sparkd/spreader/SpreaderOrderUpdateMessage.h @@ -0,0 +1,45 @@ +#pragma once + +#include "lib/domain_model/Security.pb.h" +#include "server/sparkd/orderman/utils/orderman_utils.h" +#include "lib/api/services/OrderService.pb.h" +#include "lib/sparkproto/SparkProtos.pb.h" + +namespace bts { +namespace spreader { +// message class (should not be cached) to pass orderevents +// from the spreader to the quoter and hedger (unused) +class SpreaderOrderUpdateMessage +{ +public: + // original order_state passed from the engine infrastructure + // (do not cache it) + const OrderState& order_state; + // indicates if this update has a fill or not + const bool has_fill; + // the following 2 will be populated if has_fill == true + const Price this_fill_price; + const Quantity this_fill_quantity; + SpreaderOrderUpdateMessage(const OrderState& order_state_arg, + bool has_fill_arg, + Price this_fill_price_arg, + Quantity this_fill_quantity_arg) + : + order_state(order_state_arg), + has_fill(has_fill_arg), + this_fill_price(this_fill_price_arg), + this_fill_quantity(this_fill_quantity_arg) + { + } + bool terminal_status() + { + return order_state.status == api::orderman::OrderStatus::OS_CANCELED || + order_state.status == api::orderman::OrderStatus::OS_DONE || + order_state.status == api::orderman::OrderStatus::OS_EXPIRED || + order_state.status == api::orderman::OrderStatus::OS_FILLED || + order_state.status == api::orderman::OrderStatus::OS_REJECTED || + order_state.status == api::orderman::OrderStatus::OS_STOPPED; + } + bool has_error() { return !order_state.error_msg.empty(); } +}; +}} \ No newline at end of file diff --git a/src/server/sparkd/spreader/SpreaderTests.cpp b/src/server/sparkd/spreader/SpreaderTests.cpp new file mode 100644 index 000000000..2694fd7f5 --- /dev/null +++ b/src/server/sparkd/spreader/SpreaderTests.cpp @@ -0,0 +1,37 @@ +#include "catch/catch.hpp" + +#include "../risk_limits/RiskLimitManager.h" +#include "../risk_limits/SharedRiskLimiter.h" +#include "../risk_limits/RiskLimiter.h" +#include "../risk_limits/RiskLimitState.h" +#include "../risk_limits/IRiskLimitObserver.h" + +#include "server/sparkd/orderman/utils/orderman_utils.h" + +#include "lib/config/config.h" +#include "lib/config/protos/Account.pb.h" +#include "lib/config/protos/User.pb.h" +#include "lib/domain_model/Security.pb.h" +#include "lib/utils/helper_macros.h" + +#include +#include + +using namespace bts::orderman; + +namespace bts{ +namespace spreader{ + + TEST_CASE("Simple Test", "[spreader]") + { + SECTION("nothing_really") + { + std::vector v; + for (int i = 0; i < 100; i++) + v.push_back(i); + REQUIRE(v.size() == 100); + } + } +}} + + diff --git a/src/server/sparkd/spreader/SpreaderUtils.h b/src/server/sparkd/spreader/SpreaderUtils.h index 09fff2dd6..e2faa95ac 100644 --- a/src/server/sparkd/spreader/SpreaderUtils.h +++ b/src/server/sparkd/spreader/SpreaderUtils.h @@ -3,7 +3,11 @@ #include #include "SpreaderBase.h" #include "QuoteLegPriceQuantityState.h" +#include "LegPropertyData.h" #include +#include "lib/config/protos/MarketData.pb.h" +#include "lib/md/Structure/PriceSize.h" +#include "../src/server/sparkd/orderman/md/Book.h" namespace bts { namespace spreader { @@ -46,6 +50,28 @@ public: return true; } } + static void fill_leg_shared_data(const bts::api::Security& sec, const bts::spark::ExecutionStrategy& execution_strategy, api::BuySell order_side, + std::vector& out_v) + { + bts_assert(sec.has_synthetic()); + size_t index = 0; + for (auto it = sec.synthetic().legs().begin(); it != sec.synthetic().legs().end(); ++it) + { + uint32_t sec_key = it->security().id(); + auto st_it = execution_strategy.leg_params_map().find(sec_key); + bts_assert(st_it != execution_strategy.leg_params_map().end()); + const bts::api::ContractLeg& leg = *it; + api::BuySell leg_order_side = get_leg_side(order_side, leg); + out_v.push_back(LegPropertyData(index, sec, leg, st_it->second, leg_order_side)); + } + } + const static bts::spark::LegSpreaderParams& find_spread_params(const bts::spark::ExecutionStrategy& exec_strategy, + const bts::api::Security& leg_security) + { + auto it = exec_strategy.leg_params_map().find(leg_security.id()); + bts_assert(it != exec_strategy.leg_params_map().end()); + return it->second; + } // inverts the buy/sell side api::BuySell static invert_side(api::BuySell side) { @@ -89,24 +115,25 @@ public: // this traverses the depth of the book, accumulating the quantity, // till the target quantity is reached. if the target quantity is not // reached the out_quantity < target_quantity - void static traverse_depth_for_quantity(const Book& leg_book, const api::BuySell book_side, Quantity target_quantity, + void static traverse_depth_for_quantity(const orderman::Book& leg_book, const api::BuySell book_side, Quantity target_quantity, Price& out_price, Quantity& out_quantity) { double out_price_d = 0.0; uint32_t out_quantity_u = 0; const size_t n_levels = leg_book.n_levels(); + const orderman::BookSide& book_depth = leg_book.side(book_side); for (size_t level = 0; level < n_levels; level++) { - std::tuple level_price_qty = leg_book.level(book_side, level); - Quantity level_qty = std::get<1>(level_price_qty); - out_price = std::get<0>(level_price_qty); - out_quantity_u += level_qty.value(); + md2::PriceSize level_price_qty = book_depth[level]; + md2::Size level_qty = level_price_qty.size(); + out_price_d = level_price_qty.price(); + out_quantity_u += level_qty; if (out_quantity_u >= target_quantity.value()) { out_quantity_u = target_quantity.value(); break; } - if (level_qty.value() == 0) + if (level_qty == 0) break; } out_price = Price(out_price_d);