diff --git a/src/data_files/files/spartan/sim_db.sql b/src/data_files/files/spartan/sim_db.sql index bc585dda5..8729a542b 100644 --- a/src/data_files/files/spartan/sim_db.sql +++ b/src/data_files/files/spartan/sim_db.sql @@ -10,6 +10,7 @@ create table run( market_date text, channel text, param_set_id numeric, + sim_start_stop_time text, base_algo_latency_ns numeric, transaction_latency_ns numeric, use_first_packet_st numeric, @@ -116,6 +117,7 @@ select param_set_id pset_id, base_algo_latency_ns s_latency, position_pandl ppandl, + run.sim_start_stop_time simt, sniper_run_stats.*, param1 p1, param2 p2, @@ -145,6 +147,7 @@ select sum(position_pandl) ppandl, param_set_id pset_id, base_algo_latency_ns s_latency, + sim_start_stop_time simt, param1 p1, param2 p2, param3 p3, @@ -163,6 +166,7 @@ group by run.session_id, param_set_id, base_algo_latency_ns, + sim_start_stop_time, param1, param2, param3, diff --git a/src/lib/jetfix/store/session_name.cpp b/src/lib/jetfix/store/session_name.cpp index c1a671959..81c965e05 100644 --- a/src/lib/jetfix/store/session_name.cpp +++ b/src/lib/jetfix/store/session_name.cpp @@ -1,6 +1,7 @@ #include "session_name.h" #include "lib/utils/bts_assert.h" #include +#include "lib/utils/datetime.h" namespace bts { namespace jetfix { @@ -19,18 +20,6 @@ boost::gregorian::greg_weekday parse_weekday (std::string weekday_str) return boost::gregorian::greg_weekday (0); } -boost::posix_time::time_duration parse_time (std::string const &time_str) -{ - try { - return boost::posix_time::duration_from_string (time_str); - } - catch (boost::bad_lexical_cast &) - { - bts_assert (false); - return boost::posix_time::time_duration (); - } -} - datetime::PTime closest_before (datetime::PTime const &ref_date, boost::gregorian::greg_weekday weekday, boost::posix_time::time_duration time_of_day) @@ -131,13 +120,13 @@ SessionName session_name (config::JetFIX::Connection const &session_cfg) bts_assert (session_cfg.has_end_day ()); return session_name (now, parse_weekday (session_cfg.start_day ()), - parse_time (session_cfg.start_time ()), + datetime::parse_duration (session_cfg.start_time ()), parse_weekday (session_cfg.end_day ()), - parse_time (session_cfg.end_time ())); + datetime::parse_duration (session_cfg.end_time ())); } else return session_name (now, - parse_time (session_cfg.start_time ()), - parse_time (session_cfg.end_time ())); + datetime::parse_duration (session_cfg.start_time ()), + datetime::parse_duration (session_cfg.end_time ())); } }} diff --git a/src/lib/jetfix/store/session_name.h b/src/lib/jetfix/store/session_name.h index 08a5da45d..1d1ad8c0b 100644 --- a/src/lib/jetfix/store/session_name.h +++ b/src/lib/jetfix/store/session_name.h @@ -18,8 +18,6 @@ namespace bts { namespace jetfix { boost::gregorian::greg_weekday parse_weekday(std::string weekday_str); -bool parse_time(std::string const &time_str, - boost::posix_time::time_duration *out); datetime::PTime closest_before(datetime::PTime const &ref_date, boost::gregorian::greg_weekday weekday, diff --git a/src/lib/utils/datetime.cpp b/src/lib/utils/datetime.cpp index 83eafe3fb..5c2d7b040 100755 --- a/src/lib/utils/datetime.cpp +++ b/src/lib/utils/datetime.cpp @@ -221,6 +221,17 @@ PTime parse_simple_date_time_string (std::string const &t) return boost::posix_time::time_from_string(t); } +PDuration parse_duration (std::string const &time_str) { + try { + return boost::posix_time::duration_from_string (time_str); + } + catch (boost::bad_lexical_cast &) + { + bts_assert (false); + return boost::posix_time::time_duration (); + } +} + std::string FIX_date_time_string (PTime const &t) { std::string result (strlen ("20121204-14:44:02"),' '); diff --git a/src/lib/utils/datetime.h b/src/lib/utils/datetime.h index 8cb63979d..72c2122d1 100755 --- a/src/lib/utils/datetime.h +++ b/src/lib/utils/datetime.h @@ -7,11 +7,13 @@ #include "windows_wrapper.h" // tick_count.h includes windows.h namespace boost {namespace posix_time {class ptime;}} +namespace boost {namespace posix_time {class time_duration;}} namespace bts {namespace utils {class TimeStamp;}} namespace bts { namespace datetime { typedef boost::posix_time::ptime PTime; +typedef boost::posix_time::time_duration PDuration; typedef unsigned long long LLDateTime; // Simple Date structure @@ -66,6 +68,7 @@ BTS_EXPORT std::string iso_date_time_string (PTime const &t); BTS_EXPORT PTime parse_iso_date_time_string (std::string const &t); BTS_EXPORT std::string simple_date_time_string (PTime const &t); BTS_EXPORT PTime parse_simple_date_time_string (std::string const &t); +BTS_EXPORT PDuration parse_duration (std::string const &time_str); BTS_EXPORT std::string FIX_date_time_string (PTime const &t); BTS_EXPORT PTime parse_FIX_timestamp (const std::string &ts); BTS_EXPORT std::string FIX_timestamp (PTime const &t); @@ -77,7 +80,6 @@ BTS_EXPORT bool is_at_least_mins_old (PTime const &time, uint64_t min); BTS_EXPORT bool is_at_least_hours_old (PTime const &time, uint64_t hour); BTS_EXPORT bool is_at_least_hours_old (PTime const &time, uint64_t hour); BTS_EXPORT bool is_at_least_days_old (PTime const &time, uint64_t days); - BTS_EXPORT LLDateTime ll_from_unix_epoch(long); BTS_EXPORT LLDateTime ll_from_unix_epoch_ms(long long); diff --git a/src/server/sparkd/cmds/QuickTest.cpp b/src/server/sparkd/cmds/QuickTest.cpp index 811ab6765..d5502cc57 100644 --- a/src/server/sparkd/cmds/QuickTest.cpp +++ b/src/server/sparkd/cmds/QuickTest.cpp @@ -3,27 +3,28 @@ #include "lib/utils/PBUtils.h" #include "lib/utils/bts_chrono.h" #include "lib/utils/datetime.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/Matcher.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimDB.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/sim_common.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/Matcher.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/iceberg_helper.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pcap/PCapEventSource.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/sim_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/handler/IChannelObserver.h" #include "server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h" #include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/IcebergFinder.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/iceberg_helper.h" #include +#include #include -#include +#include "server/sparkd/cmds/spartan/util/PCapReader.h" +#include namespace bts { namespace cmd { using namespace spartan::mdp3; - int QuickTest::execute(std::vector const &) { return 0; } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.cpp index 60f8bc15a..d78299958 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.cpp @@ -60,6 +60,7 @@ struct SniperModel::PImpl { double min_cumm_edge; size_t pay_up_ticks; size_t throttle_ns; + double max_shot_loss; EventHeader current_event; size_t streak_id = 0; @@ -102,7 +103,9 @@ void SniperModel::on_replay_start(EventHeader const &h, get_param(me->options, "min_cumm_qty"), get_param(me->options, "min_cumm_edge"), get_param(me->options, "pay_up_ticks"), - get_param(me->options, "throttle_ns"), h, streak_id}); + get_param(me->options, "throttle_ns"), + get_param(me->options, "max_shot_loss"), + h, streak_id}); for (auto &p : me->sim->polygons()) { auto desc = polygon_descriptor(p.second, me->sim->instruments()); @@ -240,49 +243,13 @@ void SniperModel::on_order_update(EventHeader const &h, } void SniperModel::on_time() { - auto ts = me->sim->time(); switch (me->state) { case State::WAIT_OPPORTUNITY: { break; } case State::WAIT_FILLS: { - bts_assert(me->current_shot); - auto shot_observed_ts = me->current_shot->observed.observable_time; - // bts_assert(ts.value() >= shot_observed_ts.value()); - auto shot_duration = ts.value() - shot_observed_ts.value(); - if (!me->current_shot->forced_completion && me->ms_to_work_shot && - shot_duration > 1000 * 1000 * me->ms_to_work_shot) { - me->current_shot->forced_completion = true; - - me->sim->log("forcing_fills", shot_observed_ts.value()); - - auto &in_flight = me->current_shot.value(); - for (auto &p : in_flight.working) { - auto &order = p.second.order; - auto &these_fills = p.second.fills; - auto total_fills = 0; - for (auto &f : these_fills) { - bts_assert(f.status != OrderUpdate::CANCELED); - total_fills += f.last_fills.value(); - } - if (order.order.quantity.value() > total_fills) { - md::IntPrice worst_price = order.order.price; - if (order.order.side == api::SIDE_BUY) - worst_price += me->sim->get_sec(order.order.security) - .min_price_increment_int_price() * - 100; - else - worst_price -= me->sim->get_sec(order.order.security) - .min_price_increment_int_price() * - 100; - order.change = OrderChange::updated; - order.order.quantity.value() -= total_fills; - order.order.price = worst_price; - me->sim->send(order); - } - } - } + maybe_force_fills(); break; } case State::PAUSED: @@ -291,6 +258,56 @@ void SniperModel::on_time() { } } +void SniperModel::maybe_force_fills() { + bts_assert(me->state == State::WAIT_FILLS); + bts_assert(me->current_shot); + auto ts = me->sim->time(); + auto shot_observed_ts = me->current_shot->observed.observable_time; + auto shot_duration = ts.value() - shot_observed_ts.value(); + + if (me->current_shot->forced_completion) + return; + + if (me->ms_to_work_shot) { + if (shot_duration > 1000 * 1000 * me->ms_to_work_shot) { + me->sim->log("forcing_fills_timeout", shot_observed_ts.value()); + me->current_shot->forced_completion = true; + } else if (me->current_shot->target.value < + -me->max_shot_loss) { + me->sim->log("forcing_fills_maxloss", shot_observed_ts.value()); + me->current_shot->forced_completion = true; + } + } + + if (!me->current_shot->forced_completion) + return; + + auto &in_flight = me->current_shot.value(); + for (auto &p : in_flight.working) { + auto &order = p.second.order; + auto &these_fills = p.second.fills; + auto total_fills = 0; + for (auto &f : these_fills) { + bts_assert(f.status != OrderUpdate::CANCELED); + total_fills += f.last_fills.value(); + } + if (order.order.quantity.value() > total_fills) { + md::IntPrice worst_price = order.order.price; + if (order.order.side == api::SIDE_BUY) + worst_price += me->sim->get_sec(order.order.security) + .min_price_increment_int_price() * + 100; + else + worst_price -= me->sim->get_sec(order.order.security) + .min_price_increment_int_price() * + 100; + order.change = OrderChange::updated_price; + order.order.price = worst_price; + me->sim->send(order); + } + } +} + void SniperModel::eval(std::vector const &targets) { for (auto &t : targets) { t->value = 0; @@ -527,6 +544,7 @@ SniperModel::fill_defaults(protos::SimRunOptions const &in) { set_param_if_empty(&result, "min_cumm_qty", 10); set_param_if_empty(&result, "pay_up_ticks", 10); set_param_if_empty(&result, "throttle_ns", 1000000); + set_param_if_empty(&result, "max_shot_loss", 200); return result; } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.h index 9b61b9a66..05e680205 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/SniperModel.h @@ -37,6 +37,7 @@ private: void fire(Shot const&); bool within_safety_margin(Target const&) const; void check_if_pause_over(); + void maybe_force_fills(); void transition(State); const char *state_name(State); std::unique_ptr me; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimDB.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimDB.cpp index 41204b0f5..3fe484a25 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimDB.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimDB.cpp @@ -96,6 +96,7 @@ SimDB::RunID SimDB::begin_run(SessionID sid, "market_date," "channel," "param_set_id," + "sim_start_stop_time," "base_algo_latency_ns," "transaction_latency_ns," "use_first_packet_st," @@ -125,6 +126,7 @@ SimDB::RunID SimDB::begin_run(SessionID sid, ":market_date," ":channel," ":param_set_id," + ":sim_start_stop_time," ":base_algo_latency_ns," ":transaction_latency_ns," ":use_first_packet_st," @@ -156,6 +158,7 @@ SimDB::RunID SimDB::begin_run(SessionID sid, statement.bind(":market_date", options.market_date()); statement.bind(":channel", options.channel()); statement.bind(":param_set_id", options.param_set_id()); + statement.bind(":sim_start_stop_time", options.sim_start_stop_time()); statement.bind(":base_algo_latency_ns", (long long)options.base_algo_latency_ns()); statement.bind(":transaction_latency_ns", 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 9dda85dad..888b24950 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 @@ -143,7 +143,8 @@ void FifoSecurityMatcher::_on_new_order(const MDP3Order &ord, } void FifoSecurityMatcher::_on_order_update(const MDP3Order &ord, - std::vector* res) { + bool price_only, + std::vector* res) { _log_trace_order(ord,"FifoSecurityMatcher::_on_order_update begin"); auto[price_level,curr_ord] = _find_order(ord.key); if(price_level == nullptr || curr_ord == nullptr){ @@ -175,6 +176,9 @@ void FifoSecurityMatcher::_on_order_update(const MDP3Order &ord, } new_ord.iceberg_quantity = curr_ord->ib; } + if (price_only) { + new_ord.quantity = curr_ord->quantity; + } // check for price change if (price_level->price() != new_ord.price) { // remove from current level and add to another @@ -380,8 +384,10 @@ void FifoSecurityMatcher::on_order_change(SmallOrderChange const &o, _on_new_order(o.order, res); break; case OrderChange::updated: + _on_order_update(o.order, false,res); + break; case OrderChange::updated_price: - _on_order_update(o.order, res); + _on_order_update(o.order, true,res); break; case OrderChange::removed: _on_order_remove(o.order.key, res); 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 e9d550de8..f02cad598 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 @@ -75,7 +75,7 @@ public: void _cleanup(); // order interaction void _on_new_order(const MDP3Order&, std::vector* = nullptr); - void _on_order_update(const MDP3Order&, std::vector* = nullptr); + void _on_order_update(const MDP3Order&, bool price_only = false,std::vector* = nullptr); void _on_order_remove(MDP3OrderKey, std::vector* = nullptr); void _on_order_not_affecting_books(const SmallOrderChange& o, diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/SimSessionOptions.proto b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/SimSessionOptions.proto index 7cc3d96f3..bc819dc9e 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/SimSessionOptions.proto +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/SimSessionOptions.proto @@ -30,12 +30,6 @@ message SimSessionOptions { // Wheter we should clear all previous runs before starting. False by default. bool clear_db = 11; - // The latest pcap event we will process before we terminate the - // simulation. This is usefull to speed initial prototyping of algos - // or analysis tools. Use 0 (the default) to indicate all events - // should be processed. - uint64 last_eid = 3; - // The max number of cores to use for the simulation. By default all // cores will be used. uint32 n_cores = 4 ; @@ -57,6 +51,10 @@ message SimSessionOptions { // times when calculating when an algo would see market data repeated bool use_first_packet_st = 9; + // The start and stop time for the simulation in the form: + // 23:00 04:000. Blank for whatever is in the pcap. + repeated string sim_start_stop_time = 12; + // Algo specific parameters used for this session. The simulation // wll run through all combinations of parameters, recording the // outcome of each. @@ -73,9 +71,8 @@ message SimRunOptions { string channel = 2; string market_date = 3; bool log_all_transactions = 9; - uint64 last_eid = 5; - uint32 param_set_id = 10; + string sim_start_stop_time = 11; bool use_first_packet_st = 8; uint64 base_algo_latency_ns = 4; uint64 transaction_latency_ns = 6; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/run_sim.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/run_sim.cpp index 586c5d092..fc41c307f 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/run_sim.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/run/run_sim.cpp @@ -36,6 +36,7 @@ calc_param_dimensions(protos::SimSessionOptions const &options) { dimensions.push_back(options.base_algo_latency_ns().size()); dimensions.push_back(options.transaction_latency_ns().size()); dimensions.push_back(options.use_first_packet_st().size()); + dimensions.push_back(options.sim_start_stop_time().size()); std::map param_dims; for (auto const &p : options.param()) param_dims[p.name()]++; @@ -80,18 +81,17 @@ gen_runs(protos::SimSessionOptions const &options) { auto combinations = gen_param_combinations(options); std::vector runs; for (auto &date : options.market_date()) { - size_t param_set_id=1; + size_t param_set_id = 1; for (auto &c : combinations) { auto &this_run = runs.emplace_back(); this_run.set_param_set_id(param_set_id++); this_run.set_algo(options.algo()); this_run.set_channel(options.channel()); - this_run.set_last_eid(options.last_eid()); this_run.set_log_all_transactions(options.log_all_transactions()); this_run.set_market_date(date); - + size_t param_idx = 0; // base algo latency @@ -118,6 +118,14 @@ gen_runs(protos::SimSessionOptions const &options) { options.use_first_packet_st(c[param_idx])); param_idx++; + // start/stop time + if (c[param_idx] == -1) + *(this_run.mutable_sim_start_stop_time()) = "21:45 21:00"; + else + *(this_run.mutable_sim_start_stop_time()) = + options.sim_start_stop_time(c[param_idx]); + param_idx++; + std::map> algo_params; for (auto const &p : options.param()) algo_params[p.name()].push_back(p.value()); @@ -213,9 +221,6 @@ void run_sim(std::string const &path_to_session_options) { std::istreambuf_iterator()); bts_assert(utils::pb::from_string(str, &options)); - if (options.last_eid() == 0) - options.set_last_eid(std::numeric_limits::max()); - SimDB db; auto sid = db.create_session(options.algo(), options.clear_db()); diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.cpp index 00ea29efe..02630241e 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.cpp @@ -1,20 +1,26 @@ #include "Sim.h" #include "lib/logging/logging.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/ISim.h" +#include "lib/utils/datetime.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimLogger.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/Matcher.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/iceberg_helper.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/run/SimSessionOptions.pb.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/sim_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/IAlgoModel.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pcap/PCapEventGenerator.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pcap/PCapEvent.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/ISim.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pandl/PandL.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimLogger.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pcap/PCapEvent.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pcap/PCapEventGenerator.h" +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/sim_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h" #include "server/sparkd/cmds/spartan/md/mdp3/utils/polygon_utils.h" +#include +#include +#include +#include +#include #include namespace bts::spartan::mdp3 { @@ -97,29 +103,53 @@ struct Sim::PImpl { MDP3TimeStamp next_time_event = MDP3TimeStamp{0}; std::queue pending_algo_actions = {}; size_t sim_seq = 0; - size_t next_mapped_key=1; + size_t next_mapped_key = 1; + TradingWindow trading_window = {}; }; Sim::Sim(IAlgoModel &algo, protos::SimRunOptions const &options, InstrumentMap const &instruments, IcebergMap const &ice, PolygonMap const &polys, PCapEventGenerator &gen, SimLogger const &l) : me(new PImpl{AlgoCBFilter{*this, algo}, options, instruments, ice, polys, - gen, l}) {} + gen, l}) { + me->trading_window = calculate_trading_window( + me->options.market_date(), me->options.sim_start_stop_time()); +} Sim::~Sim() {} PandLSummary Sim::run() { me->algo.init(*this, me->options); - me->algo.on_replay_start({}, {}); - while (me->event_generator.top() && - me->event_generator.top()->event_id < me->options.last_eid()) { + // Consume pcap events but do not send them to the algo up until + // trading window opens up + while (not_yet_in_trading_window()) { + if (!me->event_generator.top()) + return {}; + else { + auto const &ev = *me->event_generator.top(); + me->transact_time = ev.transact_time; + me->time = get_send_time(ev); + me->event_id.first = ev.event_id; + for (auto const &snap : ev.affected_securities) + me->snapshots[snap.security_id()].update_with(snap); + me->event_generator.move_next(); + } + } + // Now initialize the algo with whatever books we currently have + on_algo_replay_start(); + + // Extract events from the pcap and forward them to the algo while + // we are still in the trading window + while (me->event_generator.top() && still_in_trading_window()) { bts_assert(!has_pending_sim_op()); next_event(); if (has_pending_sim_op()) handle_pending_sim_op(); } + + // All done, log pandl and exit log_pandl(); return pnl(); } @@ -348,9 +378,11 @@ void Sim::_start_simulation() { if (snap.ready_to_trade()) { simulation.ready_secs.insert(sec_id); std::vector resting_orders; - for (const auto& p : snap.orders()) + for (const auto &p : snap.orders()) resting_orders.emplace_back( - correct_pcap_order({p.second, p.second, OrderChange::added}, true).order); + correct_pcap_order({p.second, p.second, OrderChange::added}, + true) + .order); std::vector effects; matcher.reset(sec_id, resting_orders, &effects); for (auto &ef : effects) @@ -378,7 +410,10 @@ void Sim::_stop_simulation() { me->pending_algo_actions = {}; me->state = State::REPLAY; me->event_id.second = 0; + on_algo_replay_start(); +} +void Sim::on_algo_replay_start() { std::vector collected_books; for (auto &[id, snap] : me->snapshots) if (snap.ready_to_trade()) { @@ -472,7 +507,7 @@ void Sim::clear_simulated_order_book(MDP3TimeStamp transact_time, match_and_send_effects(transact_time, matcher_input); } -SmallOrderChange Sim::correct_pcap_order(OrderChange const &o, bool ) { +SmallOrderChange Sim::correct_pcap_order(OrderChange const &o, bool) { bts_assert(me->state == State::SIM); bts_assert(me->simulation); auto &key_map = me->simulation->cme_key_map; @@ -506,7 +541,8 @@ SmallOrderChange Sim::correct_pcap_order(OrderChange const &o, bool ) { // auto ib_it = me->ib_map.find(result.original_key); // if (ib_it != me->ib_map.end()) // iceberg_helper::add_iceberg_annotation( - // result.order, result.change, ib_it->second, me->event_id.first, set_exact_ib_state); + // result.order, result.change, ib_it->second, me->event_id.first, + // set_exact_ib_state); // } return result; } @@ -660,6 +696,18 @@ void Sim::validate_matcher_books(api::Side side) { } } +bool Sim::still_in_trading_window() const { + if (me->state == State::REPLAY) { + return me->time.value() <= me->trading_window.stop.value(); + } else + return true; +} + +bool Sim::not_yet_in_trading_window() const { + bts_assert(me->state == State::REPLAY); + return me->time.value() < me->trading_window.start.value(); +} + bool Sim::has_pending_sim_op() const { return me->pending_sim_op != PendingSimOP::NONE; } @@ -675,4 +723,32 @@ MDP3TimeStamp Sim::get_send_time(PCapEvent const &ev) const { return ev.last_packet_send_time; } +Sim::TradingWindow +Sim::calculate_trading_window(std::string const &mkt_date, + std::string const &start_stop) const { + if (start_stop.empty()) { + return {MDP3TimeStamp{0}, + MDP3TimeStamp{std::numeric_limits::max()}}; + } else { + std::vector split_vec; + boost::algorithm::split(split_vec, start_stop, + boost::algorithm::is_any_of(" ")); + bts_assert(split_vec.size() == 2); + auto start = split_vec[0]; + auto stop = split_vec[1]; + auto day_start = datetime::parse_duration("21:45"); + auto adjust_day = [&](std::string const &time_str) { + auto dt = datetime::parse_simple_date_time_string(mkt_date); + auto t = datetime::parse_duration(time_str); + if (t < day_start) + dt += boost::gregorian::date_duration(1); + return datetime::PTime{dt.date(), t}; + }; + auto start_time = adjust_day(start); + auto stop_time = adjust_day(stop); + bts_assert(stop_time > start_time); + return {cme_ts_from_ptime(start_time), cme_ts_from_ptime(stop_time)}; + } +} + } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.h b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.h index 65d631608..1edf95bbd 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/Sim.h @@ -1,8 +1,8 @@ #pragma once +#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimLogger.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/ISim.h" #include "server/sparkd/cmds/spartan/md/mdp3/back_testing/sim/pandl/PandLSummary.h" -#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/db/SimLogger.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentMap.h" #include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/IcebergFinder.h" @@ -65,7 +65,8 @@ class Sim : ISim { void sim_log(std::string const &log_entry_type, std::vector const &log_args) const; - template void sim_log(std::string const &log_entry_type, T &&... args) const ; + template + void sim_log(std::string const &log_entry_type, T &&... args) const; void _log(std::string const &src, std::string const &log_entry_type, std::vector const &log_args) const; @@ -73,9 +74,18 @@ class Sim : ISim { void _stop_simulation(); void validate_matcher_books(api::Side); bool has_pending_sim_op() const; + void on_algo_replay_start(); + bool not_yet_in_trading_window() const; + bool still_in_trading_window() const; bool is_stopping_sim() const; MDP3TimeStamp get_send_time(PCapEvent const &) const; void handle_pending_sim_op(); + struct TradingWindow { + MDP3TimeStamp start; + MDP3TimeStamp stop; + }; + TradingWindow calculate_trading_window(std::string const &mkt_date, + std::string const &start_stop) const; enum class PendingSimOP; enum class State; struct Simulation;