diff --git a/src/data_files/files/small_es.pcap.xz b/src/data_files/files/small_es.pcap.xz index fc2b287a0..4e9b6d8f8 100644 Binary files a/src/data_files/files/small_es.pcap.xz and b/src/data_files/files/small_es.pcap.xz differ diff --git a/src/data_files/files/spartan/md.sql b/src/data_files/files/spartan/md.sql index 73c312679..4895f035f 100644 --- a/src/data_files/files/spartan/md.sql +++ b/src/data_files/files/spartan/md.sql @@ -76,7 +76,7 @@ drop table if exists securities; CREATE TABLE securities( sid numeric, symbol TEXT, - "group" TEXT, + sec_group TEXT, asset TEXT, last_t numeric ); diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index 4287d3c1a..d9a2069dd 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1 +1 @@ -set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp;cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.cpp;cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.cpp;cmds/spartan/md/mdp3/back_testing/simulator/Sim.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file +set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/Matcher.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.cpp;cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/tests/test_simulator_core.cpp;cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file diff --git a/src/server/sparkd/cmds/QuickTest.cpp b/src/server/sparkd/cmds/QuickTest.cpp index a90b4bbfe..c71cbceea 100644 --- a/src/server/sparkd/cmds/QuickTest.cpp +++ b/src/server/sparkd/cmds/QuickTest.cpp @@ -29,71 +29,7 @@ namespace bts { namespace cmd { -int QuickTest::execute(std::vector const &args) { - - auto cfg = config::get(); - cfg.mutable_console()->set_default_level("Fatal"); - log::configure_logging(cfg); - - auto file = args[0]; - using namespace bts::spartan::mdp3; - - struct Obs : IChannelObserver { - - Orders previous_orders; - size_t event_id = 0; - - void on_recovery_complete( - std::vector const &secs) override { - previous_orders.clear(); - - for (auto s : secs) - for (auto const &o : s->orders()) - previous_orders[o.first] = o.second; - } - - void on_real_time_event(MDP3Event const &ev) override { - event_id++; - - for (auto s : ev.affected_securities) { - if (s->trading_status() == - ::mdp3::SecurityTradingStatus::ReadyToTrade) { - for (auto f : s->fills()) { - if (f.aggressor != MDP3Fill::THIS_BUY && - f.aggressor != MDP3Fill::THIS_SELL) { - auto it = previous_orders.find(f.key); - bts_assert(it != previous_orders.end()); - it->second.quantity.value() -= f.quantity.value(); - if (it->second.quantity.value() < 0) { - std::cout << " Hidden sizes in order. " - << " eid: " << event_id - << " Event: " << ev - << " Order: " << it->first - << " Fill tid: " << f.trade_entry_id - << std::endl; - } - } - } - } - for (auto const &ch : s->order_changes()) { - switch (ch.change) { - case OrderChange::added: - case OrderChange::updated: - previous_orders[ch.order.key] = ch.order; - break; - case OrderChange::removed: - previous_orders.erase(ch.order.key); - break; - } - } - } - } - void on_real_time_channel_loss() override { - std::cout << "Observed loss, resetting\n"; - } - } obs; - - spartan::mdp3::observe_channel(file, obs); +int QuickTest::execute(std::vector const &) { return 0; } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp index 7ba580c12..5c2636d10 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp @@ -67,6 +67,8 @@ FifoPriceLevelMatcher::_one_pass_cross_order(MDP3OrderKey cross_ord_key, o.total_qty().value() > 0 ? OrderUpdate::Status::PARTIALLY_FILLED : OrderUpdate::Status::FILLED, + MDP3SecurityID {0}, + api::SIDE_BUY, MDP3Quantity(filled), _price }; @@ -77,6 +79,8 @@ FifoPriceLevelMatcher::_one_pass_cross_order(MDP3OrderKey cross_ord_key, cross_ord_qty.value() > 0 ? OrderUpdate::Status::PARTIALLY_FILLED : OrderUpdate::Status::FILLED, + MDP3SecurityID {0}, + api::SIDE_BUY, MDP3Quantity(filled), _price }; @@ -200,7 +204,9 @@ void FifoPriceLevelMatcher::on_order_remove(MDP3OrderKey k, bts_assert(ord_p != nullptr); _logically_delete(*ord_p); _compress(); - OrderUpdate o = {k,OrderUpdate::Status::CANCELED,MDP3Quantity(0),_price}; + OrderUpdate o = {k,OrderUpdate::Status::CANCELED, + MDP3SecurityID{0},api::SIDE_BUY, + MDP3Quantity(0),_price}; if(res != nullptr) res->push_back(o); } @@ -215,4 +221,4 @@ MDP3Quantity FifoPriceLevelMatcher::on_new_opp_order( rv = _one_pass_cross_order(opp_ord_key, std::get<1>(rv), res); return std::get<1>(rv); } -} // namespace bts::spartan::mdp3 \ No newline at end of file +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp index 486d8443a..80dd3846f 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp @@ -224,8 +224,7 @@ void FifoSecurityMatcher::_on_order_remove(MDP3OrderKey key, /////////////////////////////////////////////////////////////////////////////// FifoSecurityMatcher::FifoSecurityMatcher(size_t event_id) : _bid_book(), _ask_book(), - _search_tok(md::IntPrice(), api::Side::SIDE_BUY, Trace()), _n_unique_ords(0), - _event_id(event_id), _trace() {} + _search_tok(md::IntPrice(), api::Side::SIDE_BUY, Trace()), _event_id(event_id), _trace() {} FifoSecurityMatcher::FifoSecurityMatcher(size_t event_id, Orders const &orders) : FifoSecurityMatcher(event_id) { diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.h index 253a4a804..6494913b8 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.h @@ -17,7 +17,6 @@ public: // are sorted lowest to highest boost::container::flat_set _bid_book, _ask_book; FifoPriceLevelMatcher _search_tok; - uint32_t _n_unique_ords; const size_t _event_id; const Trace _trace; private: diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoAction.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoAction.h index b98aa3595..0ab32cf4f 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoAction.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoAction.h @@ -9,7 +9,6 @@ struct AlgoRecord; struct AlgoAction { MDP3TimeStamp transact_time; - AlgoRecord *algo; OrderChange change; }; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEvent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEvent.h index 679a701f4..f436cb14e 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEvent.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEvent.h @@ -20,6 +20,8 @@ struct OrderUpdate { MDP3OrderKey key; enum Status { FILLED, PARTIALLY_FILLED, CANCELED }; Status status; + MDP3SecurityID security_id; + api::Side side; MDP3Quantity last_fills; md::IntPrice last_price; }; @@ -27,7 +29,7 @@ struct OrderUpdate { using MatchEffect = std::variant; -struct AlgoEvent { +struct AlgoNotification { MDP3TimeStamp transact_time; MDP3TimeStamp observable_time; std::variant event; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.cpp deleted file mode 100644 index 88b5a10a7..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "AlgoEventSequencer.h" -#include "AlgoEvent.h" - -#include - -namespace bts::spartan::mdp3 { - -struct AlgoEventSequencer::PImpl { - struct EventSort { - bool operator()(const AlgoEvent &l, const AlgoEvent &r) const { - return l.observable_time.value() < r.observable_time.value(); - } - }; - using AlgoEventQueue = - std::priority_queue, EventSort>; - - AlgoEventQueue order_updates; - AlgoEventQueue mbp_updates; -}; - -AlgoEventSequencer::AlgoEventSequencer() : me(new PImpl{}) {} - -AlgoEventSequencer::~AlgoEventSequencer() {} - -AlgoEventSequencer &AlgoEventSequencer::operator=(AlgoEventSequencer &&src) { - me = std::move(src.me); - return *this; -} - -void AlgoEventSequencer::push(AlgoEvent const &ev) { - std::visit( - overloaded{[&](OrderUpdate const &) { me->order_updates.push(ev); }, - [&](MBPUpdate const &) { me->mbp_updates.push(ev); }}, - ev.event); -} - -std::optional AlgoEventSequencer::pop() { - if (me->order_updates.empty() || - me->mbp_updates.empty()) - return {}; - else { - auto &mbp_update = me->mbp_updates.top(); - auto &order_update = me->order_updates.top(); - - if (mbp_update.observable_time.value() <= - order_update.observable_time.value()) { - auto ev = mbp_update; - me->mbp_updates.pop(); - return ev; - } - else { - auto ev = order_update; - me->order_updates.pop(); - return ev; - } - } -} - -} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.h deleted file mode 100644 index 05b294730..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -#include - -namespace bts::spartan::mdp3 { - -struct AlgoEvent; - -class AlgoEventSequencer { -public: - AlgoEventSequencer(); - AlgoEventSequencer& operator=(AlgoEventSequencer&&); - - ~AlgoEventSequencer(); - void push(AlgoEvent const&); - size_t size() const; - std::optional pop(); - -private: - struct PImpl; - std::unique_ptr me; -}; - -} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.cpp new file mode 100644 index 000000000..d6285a576 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.cpp @@ -0,0 +1,111 @@ +#include "ExchangeSim.h" +#include "agents/AlgoAgent.h" +#include "agents/GatewayAgent.h" +#include "agents/TimerAgent.h" +#include "core/Simulator.h" +#include + +namespace bts::spartan::mdp3 { + +struct ExchangeSim::RunState { + RunState(SimOptions const &o) + : simulator(), options(o), timer(), gateways(), algos() {} + + sim::Simulator simulator; + SimOptions options; + + // Agents: timer, gateways and algos + TimerAgent timer; + std::vector gateways; + std::vector algos; +}; + +struct ExchangeSim::PImpl { + PImpl(std::initializer_list i) + : inputs(i), max_order_id(0), run_state() { + + bts_assert(i.size()); + + for (auto &i : inputs) { + max_order_id.value() = std::max(i.max_order_id, max_order_id.value()); + for (auto &i : i.instruments) + all_definitions.push_back(&i); + } + bts_assert(all_definitions.size()); + } + std::vector inputs; + MDP3OrderKey max_order_id; + std::vector all_definitions; + std::optional run_state; +}; + +ExchangeSim::ExchangeSim(std::initializer_list inputs) + : me(new PImpl(inputs)) {} + +ExchangeSim::~ExchangeSim() {} + +double ExchangeSim::run(IAlgoModel &algo, const SimOptions &options) { + return run({&algo}, options)[0]; +} + +void ExchangeSim::prepare_run(std::vector const &algos, + const SimOptions &options) { + bts_assert(algos.size()); + + // Setup + me->run_state.emplace(options); + + // Add timer to simulator + me->run_state->simulator.add_agent(me->run_state->timer); + + // Init gateways, add them to the simulator + for (auto &i : me->inputs) { + me->run_state->gateways.emplace_back(i.instruments, options); + me->run_state->simulator.add_agent(me->run_state->gateways.back()); + } + + // Init algos, add them to simulator + for (auto algo : algos) { + me->run_state->algos.emplace_back(me->all_definitions, &me->max_order_id, + options, *algo); + me->run_state->simulator.add_agent(me->run_state->algos.back()); + } + + // Load up all the recorded events in the simulator + for (auto &i : me->inputs) + for (auto &rev : i.events) + me->run_state->simulator.emit_event( + rev.transact_time.value(), rev); + bts_assert(me->run_state->simulator.pending_events_count()); + + // Inject a single timer event so that the timer can get started + auto first_ev_ts = me->run_state->simulator.pending_event_time(); + bts_assert(first_ev_ts); + me->run_state->simulator.emit_event(first_ev_ts.value() - 1); +} + +std::vector ExchangeSim::run(std::vector const &algos, + const SimOptions &options) { + prepare_run(algos, options); + + while (has_work()) + do_work(); + + std::vector pandl; + for (auto &a : me->run_state->algos) + pandl.push_back(a.pandl()); + return pandl; +} + +bool ExchangeSim::has_work() const { + bts_assert(me->run_state); + return me->run_state->simulator.pending_events_count() > + 1; // There is always one timer event queued +} + +void ExchangeSim::do_work() { + bts_assert(me->run_state); + me->run_state->simulator.run_once(); +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.h new file mode 100644 index 000000000..1384ab4e9 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.h @@ -0,0 +1,42 @@ +#pragma once + +#include "../../common/mdp3_common.h" +#include "SimInput.h" +#include "SimOptions.h" +#include +#include + +namespace bts::spartan::mdp3 { + +struct SimInput; +class IAlgoModel; +struct AlgoRecord; + +class ExchangeSim { + public: + // Cache a set of recorded inputs to use for later running multiple + // algos. + ExchangeSim(std::initializer_list inputs); + ~ExchangeSim(); + + // Run a single algo through all the SimInput events and return its + // profit and loss. + double run(IAlgoModel &, const SimOptions & = SimOptions()); + + // Run a set of algos and return the corresponding the profit and + // loss. + std::vector run(std::vector const &, + const SimOptions & = SimOptions()); + + private: + struct PImpl; + struct RunState; + + void prepare_run(std::vector const &, const SimOptions &); + + bool has_work() const; + void do_work(); + std::unique_ptr me; +}; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.h index 6ec2a5c59..83d6db882 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.h @@ -11,7 +11,8 @@ class IAlgoModel { public: virtual ~IAlgoModel(); virtual void init(ISimServices &) = 0; - virtual void on_event(AlgoEvent const&) = 0; + virtual void on_time(MDP3TimeStamp) {} + virtual void on_notification(AlgoNotification const&) = 0; }; } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.h index 5e1ee82cd..2c1e60b73 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.h @@ -9,10 +9,11 @@ class InstrumentDefinition; class ISimServices { public: virtual ~ISimServices(); - virtual std::vector const &instruments() const = 0; - virtual MDP3TimeStamp time() const = 0; + virtual std::vector const &instruments() const = 0; virtual MDP3OrderKey generate_order_key() = 0; - virtual void send(OrderChange const &, size_t latency_ns = 0) = 0; + virtual MDP3TimeStamp now() const = 0; + virtual void wait(uint64_t ns) = 0; + virtual void send(OrderChange const &, uint64_t propagation_delay = 0) = 0; }; } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedInputEvent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedOrderChange.h similarity index 92% rename from src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedInputEvent.h rename to src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedOrderChange.h index eab5d3752..bf15d4f31 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedInputEvent.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/RecordedOrderChange.h @@ -4,7 +4,7 @@ namespace bts::spartan::mdp3 { -struct RecordedInputEvent { +struct RecordedOrderChange { size_t event_id; MDP3TimeStamp transact_time; MDP3TimeStamp first_packet_send_time; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.cpp deleted file mode 100644 index f9bedd78f..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.cpp +++ /dev/null @@ -1,160 +0,0 @@ -#include "Sim.h" -#include "../matcher/Matcher.h" -#include "AlgoEvent.h" -#include "AlgoEventSequencer.h" -#include "IAlgoModel.h" -#include "ISimServices.h" -#include "SimEventSequencer.h" -#include "SimInput.h" -#include "lib/utils/overloaded.h" - -#include - -namespace bts::spartan::mdp3 { - -struct Sim::PImpl { - PImpl(SimInput const &i) : input(i) { reset(RunOptions{}); } - - void reset(RunOptions const &o) { - last_order_key = input.max_order_id; - algos.clear(); - matcher = Matcher{input.instruments}; - order_owners = {}; - simulator_time = MDP3TimeStamp{0}; - options = o; - input_sequencer = SimEventSequencer{input}; - output_sequencer = {}; - } - - SimInput const &input; - size_t last_order_key; - std::vector> algos; - Matcher matcher; - std::unordered_map order_owners; - MDP3TimeStamp simulator_time; - RunOptions options; - SimEventSequencer input_sequencer; - AlgoEventSequencer output_sequencer; -}; - -struct AlgoRecord : ISimServices { - Sim &owner; - IAlgoModel &algo; - uint64_t pandl; - MDP3TimeStamp last_send_time; - std::unordered_set my_orders; - - AlgoRecord(Sim &owner, IAlgoModel &algo) - : owner(owner), algo(algo), pandl(0), last_send_time(0), my_orders{} { - algo.init(*this); - } - - std::vector const &instruments() const override { - return owner.me->input.instruments; - } - - MDP3OrderKey generate_order_key() override { - return MDP3OrderKey{++owner.me->last_order_key}; - } - - MDP3TimeStamp time() const override { return last_send_time; } - - void send(OrderChange const &change, size_t latency_ns) override { - my_orders.insert(change.order.key); - owner.me->input_sequencer.push(AlgoAction{ - MDP3TimeStamp{last_send_time.value() + - owner.me->options.base_algo_latency_ns + latency_ns}, - this, change}); - } - - void deliver(AlgoEvent const &algo_event) { - last_send_time = algo_event.observable_time; - std::visit( - overloaded{[&](const MBPUpdate &) { algo.on_event(algo_event); }, - [&](const OrderUpdate &update) { - if (my_orders.count(update.key)) - algo.on_event(algo_event); - }}, - algo_event.event); - } -}; - -Sim::Sim(SimInput const &input) : me(new PImpl{input}) {} - -Sim::~Sim() {} - -int64_t Sim::run(IAlgoModel &algo, const RunOptions &options) { - return run({&algo}, options)[0]; -} - -std::vector Sim::run(std::vector const &algos, - const RunOptions &options) { - me->reset(options); - for (auto algo : algos) - me->algos.push_back(std::make_unique(*this, *algo)); - - while (has_work()) - do_work(); - - std::vector pandl; - for (auto &ar : me->algos) - pandl.push_back(ar->pandl); - return pandl; -} - -bool Sim::has_work() const { return me->input_sequencer.size(); } - -void Sim::do_work() { - auto sim_event = me->input_sequencer.pop(); - if (sim_event) { - std::vector effects; - // Calculate the effects of the event - auto transact_time = std::visit( - overloaded{[&](RecordedInputEvent const &iev) { - me->matcher.match(Matcher::SIMULATOR_INPUT, - iev.order_changes, &effects); - - me->simulator_time.value() = - std::max(iev.last_packet_send_time.value(), - me->simulator_time.value() + 1); - return iev.transact_time; - }, - - [&](AlgoAction const &algo_action) { - me->matcher.match(Matcher::ALGO, {algo_action.change}, - &effects); - me->simulator_time.value() = - me->simulator_time.value() + - me->options.transaction_latency_ns; - return algo_action.transact_time; - }}, - sim_event.value()); - - // Calculate the algo event from the effects - for (auto const &ef : effects) { - std::visit( - overloaded{ - [&](MBPUpdate const &mbp) { - me->output_sequencer.push( - {transact_time, - MDP3TimeStamp{me->simulator_time.value() + - me->options.mbp_update_delay_ns}, - mbp}); - }, - [&](OrderUpdate const &update) { - me->output_sequencer.push( - {transact_time, - MDP3TimeStamp{me->simulator_time.value() + - me->options.order_update_delay_ns}, - update}); - }}, - ef); - } - } - - while (auto algo_event = me->output_sequencer.pop()) { - for (auto &a : me->algos) - a->deliver(algo_event.value()); - } -} -} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.h deleted file mode 100644 index 2e18a6cf5..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/Sim.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include "../../common/mdp3_common.h" -#include -#include - -namespace bts::spartan::mdp3 { - -struct SimInput; -class IAlgoModel; -struct AlgoRecord; - -class Sim { - public: - // Cache a set of recorded inputs to use for later running multiple - // algos. - Sim(SimInput const &); - ~Sim(); - - struct RunOptions { - RunOptions() - : base_algo_latency_ns(0), order_update_delay_ns(0), - mbp_update_delay_ns(0), transaction_latency_ns(0) {} - - // The base latency added to all algo actions - size_t base_algo_latency_ns = 0; - - // The extra time it takes for an order update to be observable - // by an algo after a sim transaction. - uint64_t order_update_delay_ns = 0; - - // The extra time it takes for a book update to be observable - // by an algo after a sim transaction. - uint64_t mbp_update_delay_ns = 0; - - // The latency we use to process algo actions - size_t transaction_latency_ns = 50000; - }; - - // Run a single algo through all the SimInput events and return its - // profit and loss. - int64_t run(IAlgoModel &, const RunOptions & = RunOptions()); - - // Run a set of algos and return the corresponding the profit and - // loss. - std::vector run(std::vector const &, - const RunOptions & = RunOptions()); - - private: - struct PImpl; - friend struct AlgoRecord; - bool has_work() const; - void do_work(); - std::unique_ptr me; -}; - -} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEvent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEvent.h deleted file mode 100644 index cecc3c1e2..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEvent.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "RecordedInputEvent.h" -#include "AlgoAction.h" - -namespace bts::spartan::mdp3 { - -using SimEvent = std::variant; - -} - diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.cpp deleted file mode 100644 index 07b07a5f1..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "SimEventSequencer.h" -#include "AlgoAction.h" -#include "SimInput.h" -#include "SimEvent.h" - -#include - -namespace bts::spartan::mdp3 { - -struct SimEventSequencer::PImpl { - SimInput const *input; - size_t next_input_event; - struct ActionSort { - bool operator()(const AlgoAction &l, const AlgoAction &r) const { - return l.transact_time.value() > r.transact_time.value(); - } - }; - std::priority_queue, ActionSort> - pending_algo_actions; -}; - -SimEventSequencer::SimEventSequencer() - : me() -{} - -SimEventSequencer::SimEventSequencer(SimInput const &input) - : me(new PImpl{&input, 0, {}}) {} - -SimEventSequencer&SimEventSequencer::operator= (SimEventSequencer&&rhs) { - me = std::move(rhs.me); - return *this; -} - -SimEventSequencer::~SimEventSequencer() {} - -size_t SimEventSequencer::size() const { - return - me->input->events.size() - me->next_input_event + - me->pending_algo_actions.size(); - -} -void SimEventSequencer::push(AlgoAction const &action) { - me->pending_algo_actions.push(action); -} - -std::optional SimEventSequencer::pop() { - if (me->next_input_event != me->input->events.size() && - me->pending_algo_actions.size()) { - - // Both input events and algo actions are available, pick the - // earliest - auto &top_input_event = me->input->events[me->next_input_event]; - auto &top_algo_action = me->pending_algo_actions.top(); - - if (top_input_event.last_packet_send_time.value() <= - top_algo_action.transact_time.value()) { - // Input queue has it - return SimEvent{me->input->events[me->next_input_event++]}; - } else { - auto result = SimEvent {top_algo_action}; - me->pending_algo_actions.pop(); - return result; - } - } else if (me->next_input_event != me->input->events.size()) { - // Only have simulator events - return SimEvent{me->input->events[me->next_input_event++]}; - } else if (me->pending_algo_actions.size()) { - // Only have algo actions - auto result = me->pending_algo_actions.top(); - me->pending_algo_actions.pop(); - return result; - } else - return {}; -} - -} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.h deleted file mode 100644 index 92cce1b33..000000000 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "../../common/mdp3_common.h" -#include "SimEvent.h" -#include - -namespace bts::spartan::mdp3 { - -struct SimInput; -struct AlgoAction; - -class SimEventSequencer { -public: - SimEventSequencer(); - SimEventSequencer(SimInput const&); - SimEventSequencer& operator=(SimEventSequencer &&); - - ~SimEventSequencer(); - - size_t size() const; - void push(AlgoAction const&); - std::optional pop(); - -private: - struct PImpl; - struct OrderChangeRec; - std::unique_ptr me; -}; - -} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp index d0e4de281..fcdfb4960 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp @@ -5,34 +5,13 @@ namespace bts::spartan::mdp3 { -void SimInput::merge_with(SimInput const &other) { - instruments.reserve(instruments.size() + other.instruments.size()); - instruments.insert(instruments.end(), other.instruments.begin(), - other.instruments.end()); - - events.reserve(events.size() + other.events.size()); - events.insert(events.end(), other.events.begin(), other.events.end()); - std::sort(events.begin(), events.end(), - [](auto const &ev1, auto const &ev2) { - return ev1.transact_time.value() < ev2.transact_time.value(); - }); - max_order_id = std::max(max_order_id, other.max_order_id); -} - -SimInput make_sim_input(std::vector const&pcaps) { - auto result = SimInput (); - for (auto const &f : pcaps) - result.merge_with(make_sim_input(f)); - return result; -} - SimInput make_sim_input(std::string const &pcap) { struct Obs : IChannelObserver { SimInput result; std::unordered_map instruments; - std::vector events; + std::vector events; std::unordered_set ready_secs; void on_recovery_complete( diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h index 07f06e361..f7361d8b5 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h @@ -1,19 +1,16 @@ #pragma once #include "../../common/InstrumentDefinition.h" -#include "RecordedInputEvent.h" +#include "RecordedOrderChange.h" namespace bts::spartan::mdp3 { struct SimInput { std::vector instruments; - std::vector events; + std::vector events; size_t max_order_id = 0; - - void merge_with(SimInput const&); }; SimInput make_sim_input(std::string const&pcap); -SimInput make_sim_input(std::vector const&); } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimOptions.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimOptions.h new file mode 100644 index 000000000..255fbfb63 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimOptions.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace bts::spartan::mdp3 { + +struct SimOptions { + SimOptions() + : base_algo_latency_ns(0), order_update_delay_ns(0), + mbp_update_delay_ns(0), transaction_latency_ns(0) {} + + // The base latency added to all algo actions + size_t base_algo_latency_ns = 0; + + // The extra time it takes for an order update to be observable + // by an algo after a sim transaction. + uint64_t order_update_delay_ns = 0; + + // The extra time it takes for a book update to be observable + // by an algo after a sim transaction. + uint64_t mbp_update_delay_ns = 0; + + // The latency we use to process algo actions + size_t transaction_latency_ns = 50000; +}; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.cpp new file mode 100644 index 000000000..3b4c470a5 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.cpp @@ -0,0 +1,82 @@ +#include "AlgoAgent.h" +#include "../IAlgoModel.h" +#include "../SimOptions.h" + +namespace bts::spartan::mdp3 { + +struct AlgoAgent::PImpl { + std::vector const &definitions; + MDP3OrderKey *last_order_key; + SimOptions options; + IAlgoModel &algo; + std::unordered_set my_orders = {}; + std::vector my_fills = {}; +}; + +AlgoAgent::AlgoAgent( + std::vector const &instruments, + MDP3OrderKey *next_order_key, SimOptions const &options, IAlgoModel &algo) + : me(new PImpl{instruments, next_order_key, options, algo}) {} + +AlgoAgent::AlgoAgent(AlgoAgent &&src) : me () { + operator=(std::move(src)); +} + +AlgoAgent& AlgoAgent::operator=(AlgoAgent &&src) { + me = std::move(src.me); + return *this; +} + +void AlgoAgent::init() { me->algo.init(*this); } + +double AlgoAgent::pandl() const { + double result = 0; + for (auto f : me->my_fills) { + auto flow = (f.last_fills.value() * f.last_price.price()); + if (f.side == api::SIDE_BUY) + result -= flow; + else + result += flow; + } + return result; +} + +void AlgoAgent::handle(sim::Event const &ev) { + if (dynamic_cast(&ev)) { + me->algo.on_time(MDP3TimeStamp{time()}); + } else if (auto n = dynamic_cast(&ev); n) { + std::visit(overloaded{[&](const MBPUpdate &) { + me->algo.on_notification(n->ev); + }, + [&](const OrderUpdate &update) { + if (me->my_orders.count(update.key)) { + if (update.last_fills.value()) + me->my_fills.push_back(update); + me->algo.on_notification(n->ev); + } + }}, + n->ev.event); + } +} + +AlgoAgent::~AlgoAgent() {} + +std::vector const &AlgoAgent::instruments() const { + return me->definitions; +} + +MDP3OrderKey AlgoAgent::generate_order_key() { + return MDP3OrderKey{++me->last_order_key->value()}; +} + +MDP3TimeStamp AlgoAgent::now() const { return MDP3TimeStamp{time()}; } + +void AlgoAgent::wait(uint64_t ns) { forward_clock_by(ns); } + +void AlgoAgent::send(OrderChange const &change, uint64_t propagation_delay) { + me->my_orders.insert(change.order.key); + emit_delayed_event( + propagation_delay, AlgoAction{MDP3TimeStamp{time()}, change}); +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.h new file mode 100644 index 000000000..2f1a79957 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.h @@ -0,0 +1,36 @@ +#pragma once + +#include "../core/AgentBase.h" +#include "../ISimServices.h" +#include "../events/SimEvents.h" +#include +#include + +namespace bts::spartan::mdp3 { + +struct SimOptions; +class InstrumentDefinition; + +class AlgoAgent : ISimServices, public sim::AgentBase { + public: + AlgoAgent(std::vector const &, + MDP3OrderKey *next_order, + SimOptions const&, + IAlgoModel &); + AlgoAgent(AlgoAgent &&); + ~AlgoAgent(); + AlgoAgent &operator=(AlgoAgent &&); + double pandl() const; + void init() override; + void handle(sim::Event const &) override; + private: + std::vector const &instruments() const override; + MDP3OrderKey generate_order_key() override; + MDP3TimeStamp now() const override ; + void wait (uint64_t ns) override; + void send(OrderChange const &, uint64_t propagation_delay) override; + struct PImpl; + std::unique_ptr me; +}; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.cpp new file mode 100644 index 000000000..02ba43990 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.cpp @@ -0,0 +1,116 @@ +#include "GatewayAgent.h" +#include "../../../common/InstrumentDefinition.h" +#include "../../../common/mdp3_common.h" +#include "../../matcher/Matcher.h" +#include "../events/SimEvents.h" +#include "../SimOptions.h" + +#include + +namespace bts::spartan::mdp3 { + +struct GatewayAgent::PImpl { + std::unordered_set my_securities; + SimOptions options; + Matcher matcher; +}; + +GatewayAgent::GatewayAgent(std::vector const &defs, + SimOptions const &options) + : me(new PImpl()) { + for (auto const &d : defs) + me->my_securities.insert(d.security_id()); + me->options = options; +} + +GatewayAgent::GatewayAgent(GatewayAgent&&src) : me () { + operator=(std::move(src)); +} + +GatewayAgent& GatewayAgent::operator=(GatewayAgent&&src) { + me = std::move(src.me); + return *this; +} + +GatewayAgent::~GatewayAgent() {} + +void GatewayAgent::handle(const sim::Event &ev) { + + // Recorded event + if (auto rec_ev = dynamic_cast(&ev); + rec_ev) + _handle(*rec_ev); + else if (auto aa = dynamic_cast(&ev); aa) + _handle(*aa); +} + + +// Handle a recorded order change, that is an order change we got from +// a pcap recording of the market data +void GatewayAgent::_handle(RecordedOrderChangeEvent const &e) { + auto const &ev = e.ev; + bts_assert(ev.order_changes.size()); + + auto &first_change = ev.order_changes[0]; + + if (me->my_securities.count(first_change.order.security)) { + + // Advance our clock either to the send time in the recording + // (unless we are already ahead of that time, possibly because + // we got delayed processing algo operations). + auto send_time = ev.last_packet_send_time.value(); + if (send_time > time()) + forward_clock_by(send_time - time()); + else + forward_clock_by(me->options.transaction_latency_ns); + + // Now match the recorded orders and send out their effects as + // algo notification events + std::vector effects; + me->matcher.match(Matcher::SIMULATOR_INPUT, ev.order_changes, &effects); + + for (auto const &ef : effects) + std::visit(overloaded{[&](MBPUpdate const &mbp) { + emit_delayed_event( + me->options.mbp_update_delay_ns, + AlgoNotification{ev.transact_time, + MDP3TimeStamp{time()}, + mbp}); + }, + [&](OrderUpdate const &order_update) { + emit_delayed_event( + me->options.order_update_delay_ns, + AlgoNotification{ev.transact_time, + MDP3TimeStamp{time()}, + order_update}); + }}, + ef); + } +} + +// Handle an algo order change, that is an order change requested by +// one of the algos under test. +void GatewayAgent::_handle(AlgoActionEvent const &e) { + auto const &algo_action = e.ev; + + std::vector effects; + me->matcher.match(Matcher::ALGO, {algo_action.change}, &effects); + for (auto const &ef : effects) + std::visit(overloaded{[&](MBPUpdate const &mbp) { + emit_delayed_event( + me->options.mbp_update_delay_ns, + AlgoNotification{algo_action.transact_time, + MDP3TimeStamp{time()}, + mbp}); + }, + [&](OrderUpdate const &order_update) { + emit_delayed_event( + me->options.order_update_delay_ns, + AlgoNotification{algo_action.transact_time, + MDP3TimeStamp{time()}, + order_update}); + }}, + ef); +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.h new file mode 100644 index 000000000..76cc01c4c --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.h @@ -0,0 +1,30 @@ +#pragma once + +#include "../core/AgentBase.h" +#include "../events/SimEvents.h" + +#include +#include + +namespace bts::spartan::mdp3 { + +struct SimOptions; +class InstrumentDefinition; + +class GatewayAgent : public sim::AgentBase { + public: + GatewayAgent(std::vector const &, SimOptions const &); + GatewayAgent(GatewayAgent&&); + GatewayAgent& operator=(GatewayAgent&&); + + ~GatewayAgent(); + void handle(sim::Event const &) override; + + private: + void _handle(RecordedOrderChangeEvent const&); + void _handle(AlgoActionEvent const&); + struct PImpl; + std::unique_ptr me; +}; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.cpp new file mode 100644 index 000000000..88ac8fbd3 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.cpp @@ -0,0 +1,16 @@ +#include "TimerAgent.h" +#include "../events/SimEvents.h" + +namespace bts::spartan::mdp3 { + +TimerAgent::TimerAgent (uint64_t period_ms) : _period_ms(period_ms) {} + +void TimerAgent::handle(sim::Event const &ev) { + if (dynamic_cast (&ev)) { + forward_clock_by(_period_ms * 1000 * 1000); + emit_event (); + } +} + + +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.h new file mode 100644 index 000000000..048199b54 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.h @@ -0,0 +1,16 @@ +#pragma once + +#include "../core/AgentBase.h" + +namespace bts::spartan::mdp3 { + +class TimerAgent : public sim::AgentBase { +public: + TimerAgent (uint64_t period_ms = 100); + void handle(sim::Event const &) override; + private: + uint64_t _period_ms; +}; + + +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp index 534a9aad9..52721aa0e 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp @@ -69,7 +69,8 @@ void SimSpreader::init(ISimServices& sim_services){ me->spreader.test_only_on_init_new (me->order_def, me->pao_services); } -void SimSpreader::on_event(AlgoEvent const& ev) { + +void SimSpreader::on_notification(AlgoNotification const& ev) { if(std::holds_alternative(ev.event)){ // book update const MBPUpdate& bk = std::get(ev.event); diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.h index 1ceee8bfd..68c92b319 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.h @@ -20,7 +20,7 @@ public: SimSpreader(const bts::api::orderman::OrderDefinition&, const bts::api::Security&); void init(ISimServices&) override; - void on_event(AlgoEvent const&) override; + void on_notification(AlgoNotification const&) override; }; -} \ No newline at end of file +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.cpp new file mode 100644 index 000000000..26b71cda2 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.cpp @@ -0,0 +1,60 @@ +#include "AgentBase.h" + +#include "lib/utils/bts_assert.h" +#include + +namespace bts::spartan::sim { + +struct AgentBase::Self { + Simulator *simulator = nullptr; + std::queue pending_events; + TimeStamp agent_time = 0; +}; + +AgentBase::AgentBase() : self(new Self {}) {} +AgentBase::~AgentBase() {} + +void AgentBase::init(Simulator &sim) { + bts_assert(self->simulator == nullptr); + self->simulator = ∼ +} + +void AgentBase::enqueue(Event const& e) { + bts_assert(self->simulator); + self->pending_events.push(&e); +} + +TimeStamp AgentBase::process(TimeStamp now) { + bts_assert(self->simulator); + + if (self->agent_time>now) + return self->agent_time; + else + self->agent_time = now; + + while (self->pending_events.size()) { + auto ev = self->pending_events.front(); + self->pending_events.pop(); + handle(*ev); + } + if (self->agent_time == now) + return EndOfTime; + else + return self->agent_time; + +} + +void AgentBase::forward_clock_by(TimeDelta delta) { + self->agent_time += delta; +} + +Simulator& AgentBase::simulator() { + bts_assert(self->simulator); + return *self->simulator; +} + +TimeStamp AgentBase::time() const { + return self->agent_time; +} + +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.h new file mode 100644 index 000000000..66746c5c7 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.h @@ -0,0 +1,40 @@ +#pragma once + +#include "IAgent.h" +#include "Simulator.h" +#include + +namespace bts::spartan::sim { + +class AgentBase : public IAgent { + protected: + AgentBase(); + ~AgentBase(); + + template + void emit_event(Args &&... args) { + emit_delayed_event(0,std::forward(args)...); + } + + template + void emit_delayed_event(TimeDelta delay,Args &&... args) { + simulator().emit_event(time()+delay,std::forward(args)...); + } + + void forward_clock_by(TimeDelta); + TimeStamp time() const; + + virtual void handle(Event const&) = 0; + virtual void init() {} + + private: + Simulator& simulator(); + void init(Simulator &) override; + void enqueue(Event const&) override; + TimeStamp process(TimeStamp now) override; + + struct Self; + std::unique_ptr self; +}; + +} // namespace bts::spartan::sim diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Event.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Event.h new file mode 100644 index 000000000..22aff69ac --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Event.h @@ -0,0 +1,13 @@ +#pragma once + +#include "simulator_common.h" + +namespace bts::spartan::sim { + +class Event { + public: + virtual ~Event() {} + TimeStamp observable_time; +}; + +} // namespace bts::spartan::sim diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/IAgent.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/IAgent.h new file mode 100644 index 000000000..296f4c114 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/IAgent.h @@ -0,0 +1,18 @@ +#pragma once + +#include "simulator_common.h" + +namespace bts::spartan::sim { + +class Simulator; +class Event; + +class IAgent { +public: + virtual ~IAgent() {}; + virtual void init(Simulator&) = 0; + virtual void enqueue(Event const&) = 0; + virtual TimeStamp process(TimeStamp now) = 0; +}; + +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.cpp new file mode 100644 index 000000000..eb01470e9 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.cpp @@ -0,0 +1,92 @@ +#include "Simulator.h" +#include "Event.h" +#include "IAgent.h" +#include "lib/utils/bts_assert.h" + +#include + +namespace bts::spartan::sim { + +struct EventSort { + bool operator()(Event const *l, Event const *r) const { + return l->observable_time < r->observable_time; + } +}; + +using FutureEventQueue = + std::priority_queue, EventSort>; + +struct Simulator::PImpl { + std::vector agents; + std::vector> events; + FutureEventQueue pending_events; + TimeStamp time = 0; +}; + +Simulator::Simulator() : me(new PImpl()) {} +Simulator::~Simulator() {} + +TimeStamp Simulator::simulation_time() { return me->time; } + +std::optional Simulator::pending_event_time() const { + if (me->pending_events.size()) + return me->pending_events.top()->observable_time; + else + return {}; +} + +size_t Simulator::pending_events_count() const { + return me->pending_events.size(); +} + +bool Simulator::run_once() { + prepare(); + if (me->pending_events.top()->observable_time <= me->time) { + auto current_ev = me->pending_events.top(); + me->pending_events.pop(); + for (auto &a : me->agents) + a->enqueue(*current_ev); + } + + // Give all agents a chance to process their queued events + auto next_agent_interesting_time = EndOfTime; + for (auto &a : me->agents) { + auto next_ready = a->process(me->time); + next_agent_interesting_time = + std::min(next_ready, next_agent_interesting_time); + } + + if (me->pending_events.empty()) + return false; + else { + me->time = std::min(next_agent_interesting_time, + me->pending_events.top()->observable_time); + return true; + } +} + +void Simulator::run() { + while (run_once()) + ; +} + +void Simulator::prepare() { + bts_assert(me->agents.size()); + bts_assert(me->events.size()); + if (me->time == 0) + me->time = me->pending_events.top()->observable_time; +} + +void Simulator::add_agent(IAgent &a) { + me->agents.emplace_back(&a); + a.init(*this); +} + +void Simulator::_emit_event(TimeStamp ts, Event *ev) { + bts_assert(ts >= simulation_time()); + ev->observable_time = ts; + me->events.emplace_back(ev); + me->pending_events.push(ev); +} + +} // namespace bts::spartan::sim diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.h new file mode 100644 index 000000000..cb383ad47 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include "simulator_common.h" + +namespace bts::spartan::sim { + +class IAgent; +class Event; + +class Simulator { +public: + Simulator(); + ~Simulator(); + + void add_agent(IAgent &); + + template + void emit_event(TimeStamp observable_time, + Args &&... args) { + _emit_event(observable_time,new EV(std::forward(args)...)); + } + + TimeStamp simulation_time(); + std::optional pending_event_time() const; + size_t pending_events_count() const; + + bool run_once(); + void run(); + +private: + void reset(); + void prepare(); + void _emit_event(TimeStamp,Event*); + struct PImpl; + std::unique_ptr me; +}; + + + +} + diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/simulator_common.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/simulator_common.h new file mode 100644 index 000000000..d8ba38cda --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/simulator_common.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +namespace bts::spartan::sim { + +using TimeStamp = uint64_t; +using TimeDelta = uint64_t; +inline const TimeStamp EndOfTime = std::numeric_limits::max(); +inline const TimeStamp BeginOfTime = 0; + +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/tests/test_simulator_core.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/tests/test_simulator_core.cpp new file mode 100644 index 000000000..47a47a71a --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/core/tests/test_simulator_core.cpp @@ -0,0 +1,77 @@ +// #include "../../RecordedInputEvent.h" +// #include "../../SimInput.h" +// #include "../AgentBase.h" +// #include "../Event.h" +// #include "../simulator_common.h" +// #include +// #include + +// namespace bts::spartan::sim::tests { + +// using namespace bts::spartan::mdp3; + +// struct TestEvent1 : Event { +// TestEvent1 (RecordedInputEvent const&e) : ev(e) {} +// RecordedInputEvent ev; +// }; + +// struct TestEvent2 : Event { +// TestEvent2 (RecordedInputEvent const&e) : ev(e) {} +// RecordedInputEvent ev; +// }; + +// struct RunOptions { +// RunOptions() +// : base_algo_latency_ns(0), order_update_delay_ns(0), +// mbp_update_delay_ns(0), transaction_latency_ns(0) {} + +// // The base latency added to all algo actions +// size_t base_algo_latency_ns = 0; + +// // The extra time it takes for an order update to be observable +// // by an algo after a sim transaction. +// uint64_t order_update_delay_ns = 0; + +// // The extra time it takes for a book update to be observable +// // by an algo after a sim transaction. +// uint64_t mbp_update_delay_ns = 0; + +// // The latency we use to process algo actions +// size_t transaction_latency_ns = 50000; +// }; + +// struct TestAgent : AgentBase { +// RunOptions options; + +// void handle(Event const&e) { +// auto recorded_ev = dynamic_cast(&e); +// if (recorded_ev) { +// auto send_time = recorded_ev->ev.last_packet_send_time.value(); +// if (send_time > time()) +// forward_clock_by(send_time - time()); +// else +// forward_clock_by(options.transaction_latency_ns); +// emit_event (recorded_ev->ev); +// } +// } +// }; + +// TEST_CASE("Simulator Core Tests", "[simcore]") { +// auto pcap = os::sparkd_wd() + "/data_files/small_es.pcap"; +// auto sim_input = make_sim_input(pcap); + +// SECTION("smoke_test") { +// REQUIRE(sim_input.events.size() > 0); + +// Simulator sim; +// for (auto &ev : sim_input.events) +// sim.emit_event (ev.transact_time.value(),ev); +// sim.add_agent(); + +// while (sim.run_once()) +// ; +// REQUIRE(sim.simulation_time()>0); +// } +// } + +// } // namespace bts::spartan::sim::tests diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.cpp new file mode 100644 index 000000000..ba5aa9c08 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.cpp @@ -0,0 +1,3 @@ +#include "SimEvents.h" + + diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.h new file mode 100644 index 000000000..ab72e35f3 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.h @@ -0,0 +1,21 @@ +#pragma once + +#include "../../../common/mdp3_common.h" +#include "../AlgoEvent.h" +#include "../AlgoAction.h" +#include "../RecordedOrderChange.h" +#include "../core/Event.h" + +namespace bts::spartan::mdp3 { + +template struct EventWrapper : sim::Event { + EventWrapper(EV const &e) : ev(e) {} + EV ev; +}; + +using RecordedOrderChangeEvent = EventWrapper; +using AlgoActionEvent = EventWrapper; +using AlgoNotificationEvent = EventWrapper; +struct TimerEvent : sim::Event {}; + +} // namespace bts::spartan::mdp3 diff --git a/tools/docker_tools/run_rc b/tools/docker_tools/run_rc new file mode 100755 index 000000000..532683f9c --- /dev/null +++ b/tools/docker_tools/run_rc @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR="$(dirname "$(readlink -f "$0")")" +COMPILE_CMDS=$DIR/../../compile_commands.json + +rc -J $COMPILE_CMDS +inotifywait -q -m -e close_write --format %e $COMPILE_CMDS | +while read events; do + echo Changed detected, running rc -J $COMPILE_CMDS + rc -J $COMPILE_CMDS +done