From 82332bf92ff5a0edb7b170003cedf162e3dc03bd Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 19 Jan 2021 15:23:10 -0600 Subject: [PATCH] refactor: Replace SimBooks cmd with Matcher->BooksCmd This is in anticipation of adding a similar subcommand to record fills, and proc times. Basic functionality expected to be shared by these three commands is abstracted out of the former SimBooks command into common classes. --- src/server/sparkd/cmds/Spartan.cpp | 4 +- .../cmds/spartan/back_testing/common/Trace.cc | 22 ++ .../cmds/spartan/back_testing/common/Trace.h | 14 +- .../sparkd/cmds/spartan/cmds/MatcherCmd.cpp | 12 + .../sparkd/cmds/spartan/cmds/MatcherCmd.h | 10 + .../sparkd/cmds/spartan/cmds/SimBooks.cpp | 91 ------ .../sparkd/cmds/spartan/cmds/SimBooks.h | 16 - .../spartan/cmds/matcher/cmds/BooksCmd.cpp | 115 ++++++++ .../cmds/spartan/cmds/matcher/cmds/BooksCmd.h | 16 + .../spartan/cmds/matcher/common/InitData.cpp | 39 +++ .../spartan/cmds/matcher/common/InitData.h | 33 +++ .../sparkd/cmds/spartan/common/Range.cc | 38 +++ src/server/sparkd/cmds/spartan/common/Range.h | 27 ++ .../cmds/spartan/common/cli/RangeArg.cpp | 31 ++ .../sparkd/cmds/spartan/common/cli/RangeArg.h | 18 ++ .../sparkd/cmds/spartan/domain/EventRange.h | 9 + .../cmds/spartan/domain/SecurityCriteria.cc | 29 ++ .../cmds/spartan/domain/SecurityCriteria.cpp | 4 + .../cmds/spartan/domain/SecurityCriteria.h | 16 + .../market_data/common/EventRangeMap.h | 9 + .../market_data/common/EventRangeMonitor.cc | 9 + .../market_data/common/EventRangeMonitor.cpp | 35 +++ .../market_data/common/EventRangeMonitor.h | 53 ++++ .../feed_observers/CompositeObserver.cpp | 46 +++ .../feed_observers/CompositeObserver.h | 33 +++ .../recorders/MatcherBookRecorder.cpp | 133 ++------- .../recorders/MatcherBookRecorder.h | 28 +- .../recorders/MatcherRecorder.cpp | 276 ++++++++++++++++++ .../recorders/MatcherRecorder.h | 78 +++++ 29 files changed, 995 insertions(+), 249 deletions(-) create mode 100644 src/server/sparkd/cmds/spartan/back_testing/common/Trace.cc create mode 100644 src/server/sparkd/cmds/spartan/cmds/MatcherCmd.cpp create mode 100644 src/server/sparkd/cmds/spartan/cmds/MatcherCmd.h delete mode 100644 src/server/sparkd/cmds/spartan/cmds/SimBooks.cpp delete mode 100644 src/server/sparkd/cmds/spartan/cmds/SimBooks.h create mode 100644 src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.cpp create mode 100644 src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.h create mode 100644 src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.cpp create mode 100644 src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.h create mode 100644 src/server/sparkd/cmds/spartan/common/Range.cc create mode 100644 src/server/sparkd/cmds/spartan/common/Range.h create mode 100644 src/server/sparkd/cmds/spartan/common/cli/RangeArg.cpp create mode 100644 src/server/sparkd/cmds/spartan/common/cli/RangeArg.h create mode 100644 src/server/sparkd/cmds/spartan/domain/EventRange.h create mode 100644 src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cc create mode 100644 src/server/sparkd/cmds/spartan/market_data/common/EventRangeMap.h create mode 100644 src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cc create mode 100644 src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cpp create mode 100644 src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.h create mode 100644 src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.cpp create mode 100644 src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.h create mode 100644 src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.cpp create mode 100644 src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.h diff --git a/src/server/sparkd/cmds/Spartan.cpp b/src/server/sparkd/cmds/Spartan.cpp index b94b61095..78b0f92be 100644 --- a/src/server/sparkd/cmds/Spartan.cpp +++ b/src/server/sparkd/cmds/Spartan.cpp @@ -7,9 +7,9 @@ #include "cmds/Json.h" #include "cmds/ListSec.h" #include "cmds/PolygonBooks.h" +#include "cmds/MatcherCmd.h" #include "cmds/SQL.h" #include "cmds/Sim.h" -#include "cmds/SimBooks.h" #include "cmds/Stats.h" #include "cmds/ValidateFifo.h" #include "cmds/ValuePolys.h" @@ -29,8 +29,8 @@ Spartan::Spartan() : CLI::App("Futures trading system for devs", "spartan") { add_subcommand(CLI::App_p(new Json())); add_subcommand(CLI::App_p(new ListSec())); add_subcommand(CLI::App_p(new PolygonBooks())); + add_subcommand(CLI::App_p(new MatcherCmd())); add_subcommand(CLI::App_p(new Sim())); - add_subcommand(CLI::App_p(new SimBooks())); add_subcommand(CLI::App_p(new SQL())); add_subcommand(CLI::App_p(new Stats())); add_subcommand(CLI::App_p(new ValidateFifo())); diff --git a/src/server/sparkd/cmds/spartan/back_testing/common/Trace.cc b/src/server/sparkd/cmds/spartan/back_testing/common/Trace.cc new file mode 100644 index 000000000..36ddd437b --- /dev/null +++ b/src/server/sparkd/cmds/spartan/back_testing/common/Trace.cc @@ -0,0 +1,22 @@ +#include "Trace.h" + +namespace bts::spartan::mdp3 { + +template +inline Trace Trace::create( + const TracedOrders &traced_orders, + const TracedEvents &traced_events, + const IgnoredEvents &ignored_events) { + std::map traced_orders_map; + std::map traced_events_map; + std::map ignored_events_map; + for (auto o : traced_orders) + traced_orders_map.emplace(o, true); + for (auto e : traced_events) + traced_events_map.emplace(e, true); + for (auto e : ignored_events) + ignored_events_map.emplace(e, true); + return {traced_orders_map, traced_events_map, ignored_events_map}; +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/back_testing/common/Trace.h b/src/server/sparkd/cmds/spartan/back_testing/common/Trace.h index 1dcb194f9..48ff6736e 100644 --- a/src/server/sparkd/cmds/spartan/back_testing/common/Trace.h +++ b/src/server/sparkd/cmds/spartan/back_testing/common/Trace.h @@ -3,12 +3,22 @@ #include "domain/order/OrderKey.h" #include #include +#include namespace bts::spartan::mdp3 { class Trace { public: - bool log(OrderKey key, std::size_t eid = 0) const; + template < + class TracedOrders = std::vector, + class TracedEvents = std::vector, + class IgnoredEvents = std::vector> + static Trace create( + const TracedOrders & = {}, + const TracedEvents & = {}, + const IgnoredEvents & = {}); + + bool log(OrderKey key, size_t eid = 0) const; bool log(size_t eid) const; bool is_ignored_event(std::size_t eid) const; void log_incoming_change(const SmallOrderChange &); @@ -20,3 +30,5 @@ class Trace { }; } // namespace bts::spartan::mdp3 + +#include "Trace.cc" diff --git a/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.cpp b/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.cpp new file mode 100644 index 000000000..bae33a180 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.cpp @@ -0,0 +1,12 @@ +#include "MatcherCmd.h" +#include "matcher/cmds/BooksCmd.h" + +namespace bts::spartan::cmds { + +MatcherCmd::MatcherCmd() + : CLI::App("Record data produced by the matcher", "matcher") { + require_subcommand(); + add_subcommand(CLI::App_p(new matcher::cmds::BooksCmd())); +} + +} // namespace bts::spartan::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.h b/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.h new file mode 100644 index 000000000..a6f1a613e --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/MatcherCmd.h @@ -0,0 +1,10 @@ +#pragma once +#include + +namespace bts::spartan::cmds { + +struct MatcherCmd : public CLI::App { + MatcherCmd(); +}; + +} // namespace bts::spartan::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/SimBooks.cpp b/src/server/sparkd/cmds/spartan/cmds/SimBooks.cpp deleted file mode 100644 index 9ee1a3804..000000000 --- a/src/server/sparkd/cmds/spartan/cmds/SimBooks.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "SimBooks.h" -#include "back_testing/matcher/Matcher.h" -#include "back_testing/matcher/validation/iceberg_file_cache.h" -#include "domain/SecurityCriteria.h" -#include "market_data/feed_observers/DefinitionCollector.h" -#include "market_data/feed_observers/IcebergFinder.h" -#include "market_data/feed_observers/recorders/MatcherBookRecorder.h" -#include "market_data/utils/mdp3_utils.h" -#include "utils/FileUtils.h" -#include - -namespace bts::spartan::cmds { - -#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__) -#define INFO(...) _LOG(Info, __VA_ARGS__) - -struct SimBooks::Args { - std::string pcap; - std::string out; - std::vector assets; - std::vector security_groups; - mdp3::SecurityCriteria security_criteria; -}; - -SimBooks::SimBooks() - : CLI::App( - "Generate a csv file of book updates by feeding deduced orders from " - "a pcap file to the simulation matcher", - "sim-books"), - _args(new SimBooks::Args()) { - add_option("pcap,--pcap", _args->pcap)->required(); - add_option("out,--out", _args->out); - add_option( - "--assets", _args->assets, - "Specify asset(s) to filter the set of securities for which books are " - "generated"); - add_option( - "--security-groups", _args->security_groups, - "Specify security group(s) to filter the set of securities for which " - "books are generated"); - callback([&] { - // Validate args - bts_assert(_args->pcap.size()); - if (_args->out.empty()) - _args->out = - FileUtils::change_file_ext(_args->pcap, "sim_books.csv", "pcap.xz"); - bts_assert(_args->out.size()); - // Sweep pcap for securityies and icebergs - mdp3::DefinitionCollector dc; - // mdp3::IcebergFinder ice_finder; - INFO( - "Begin observe '{}' (1/2): detect all securityies and iceberg orders", - _args->pcap); - mdp3::observe_channel(_args->pcap, dc); - auto ibs = mdp3::iceberg_file_cache::find_icebergs(_args->pcap); - INFO( - "End observe '{}' (1/2): detected {} securities, and {} iceberg " - "orders", - _args->pcap, dc.result.size(), ibs.size()); - // Init MergedMatcher - mdp3::MergedMatcher matcher; - for (auto p : dc.result) - matcher.add_def(p.second); - // Init MatcherBookRecorder - mdp3::SecurityCriteria security_criteria; - if (_args->assets.size() || _args->security_groups.size()) { - // assets - auto &assets = security_criteria.clauses.emplace_back().assets; - assets.insert( - assets.end(), _args->assets.begin(), _args->assets.end()); - // security groups - auto &security_groups = - security_criteria.clauses.emplace_back().assets; - security_groups.insert( - security_groups.end(), _args->security_groups.begin(), - _args->security_groups.end()); - } - mdp3::MatcherBookRecorder rec({matcher, ibs, security_criteria, true}); - // Init FeedRecorderWrapper and observe pcap to generate the csv - std::ofstream out(_args->out); - mdp3::FeedRecorderWrapper rec_wrap(out, &rec); - INFO("Begin observe '{}' (2/2): record matcher books", _args->pcap); - mdp3::observe_channel(_args->pcap, rec_wrap); - INFO("End observe '{}' (2/2): recorded matcher book", _args->pcap); - out.flush(); - }); -} - -SimBooks::~SimBooks() {} - -} // namespace bts::spartan::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/SimBooks.h b/src/server/sparkd/cmds/spartan/cmds/SimBooks.h deleted file mode 100644 index d2fa7c07e..000000000 --- a/src/server/sparkd/cmds/spartan/cmds/SimBooks.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include - -namespace bts::spartan::cmds { - -struct SimBooks : public CLI::App { - SimBooks(); - ~SimBooks(); - - private: - struct Args; - std::unique_ptr _args; -}; - -} // namespace bts::spartan::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.cpp b/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.cpp new file mode 100644 index 000000000..866709ed6 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.cpp @@ -0,0 +1,115 @@ +#include "BooksCmd.h" +#include "back_testing/common/Trace.h" +#include "back_testing/matcher/Matcher.h" +#include "cmds/matcher/common/InitData.h" +#include "common/cli/RangeArg.h" +#include "domain/SecurityCriteria.h" +#include "market_data/feed_observers/recorders/MatcherBookRecorder.h" +#include "market_data/feed_observers/recorders/MatcherRecorder.h" +#include "market_data/utils/mdp3_utils.h" +#include "utils/FileUtils.h" +#include + +namespace bts::spartan::cmds::matcher::cmds { + +#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__) +#define INFO(...) _LOG(Info, __VA_ARGS__) + +struct BooksCmd::Args { + // options + std::string pcap; + std::string out; + std::vector assets; + std::vector security_groups; + std::vector security_ids; + std::vector trace_orders; + std::vector trace_events; + std::vector observed_events; + std::uint16_t max_aggressors; + // flags + bool sweep_definitions; + bool sweep_icebergs; + bool verbose; +}; + +BooksCmd::BooksCmd() + : CLI::App( + "Generate a csv file of book updates by feeding deduced orders from " + "a pcap file to the simulation matcher", + "books"), + _args(new BooksCmd::Args()) { + add_option("pcap,--pcap", _args->pcap)->required(); + add_option("out,--out", _args->out); + add_option( + "--assets", _args->assets, + "Specify asset(s) to filter the set of securities for which books are " + "generated"); + add_option( + "--security-groups", _args->security_groups, + "Specify security group(s) to filter the set of securities for which " + "books are generated"); + add_option( + "--security-ids", _args->security_ids, + "Specify security ids to filter the set of securities for which books " + "are generated"); + add_option( + "--trace-orders", _args->trace_orders, + "Orders to trace (specify one or more order ids)"); + add_option( + "--trace-events", _args->trace_events, + "Events to trace (specify one or more event ids)"); + add_option( + "--events", _args->observed_events, + "Specify the events for which books are generated (can be listed " + "individually: , or in range form: or )"); + add_option( + "--max-aggressors", _args->max_aggressors, + "Specify a maximum number of securities with aggressor orders (per " + "event) to filter the events for which books are generated"); + add_flag( + "--sweep-definitions", _args->sweep_definitions, + "Sweep the pcap to determine securities, and establish the implied " + "matching graph before processing books with the matcher"); + add_flag( + "--sweep-icebergs", _args->sweep_icebergs, + "Sweep the pcap to determine icebergs"); + add_flag("-v,--verbose", _args->verbose); + callback([&] { + // Validate args + bts_assert(_args->pcap.size()); + if (_args->out.empty()) + _args->out = FileUtils::change_file_ext( + _args->pcap, "matcher_books.csv", "pcap.xz"); + bts_assert(_args->out.size()); + + auto init = InitData::init( + _args->pcap, _args->sweep_definitions, _args->sweep_icebergs); + // matcher + mdp3::MergedMatcher matcher( + {mdp3::Trace::create(_args->trace_orders, _args->trace_events)}); + for (const auto &p : init.definitions) + matcher.add_def(p.second); + // security criteria + auto security_criteria = mdp3::SecurityCriteria::create( + {}, {}, _args->assets, _args->security_groups); + // observed events + std::vector observed_events; + for (auto r : _args->observed_events) + observed_events.emplace_back(r.result()); + // Init MatcherBookRecorder and observe pcap to generate the csv + std::ofstream out(_args->out); + mdp3::MatcherRecorder::Curry rec_curry( + {out, matcher, init.icebergs, + std::unique_ptr( + new mdp3::MatcherBookRecorder()), + security_criteria, observed_events, _args->max_aggressors, + _args->verbose}); + INFO("Begin recording matcher books for '{}'", _args->pcap); + mdp3::observe_channel(_args->pcap, rec_curry); + INFO("End recording matcher books for '{}'", _args->pcap); + }); +} + +BooksCmd::~BooksCmd() {} + +} // namespace bts::spartan::cmds::matcher::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.h b/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.h new file mode 100644 index 000000000..7672fe30b --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/matcher/cmds/BooksCmd.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include + +namespace bts::spartan::cmds::matcher::cmds { + +struct BooksCmd : public CLI::App { + BooksCmd(); + ~BooksCmd(); + + private: + struct Args; + std::unique_ptr _args; +}; + +} // namespace bts::spartan::cmds::matcher::cmds diff --git a/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.cpp b/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.cpp new file mode 100644 index 000000000..f5217e043 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.cpp @@ -0,0 +1,39 @@ +#include "InitData.h" +#include "back_testing/matcher/common/IcebergFileCache.h" +#include "domain/SecurityDefinition.h" +#include "market_data/feed_observers/CompositeObserver.h" +#include "market_data/feed_observers/DefinitionCollector.h" +#include "market_data/feed_observers/IcebergFinder.h" +#include "market_data/utils/mdp3_utils.h" +#include +#include + +namespace bts::spartan::cmds::matcher { + +InitData InitData::init( + const std::string &pcap, bool sweep_definitions, bool sweep_icebergs) { + InitData rv; + LOG(OrderMan, Info, + "Gathering initialization data for {}. Securities: {}. Definitions: {}", + pcap, std::string(sweep_definitions ? "Yes" : "No"), + std::string(sweep_icebergs ? "Yes" : "No")); + + mdp3::DefinitionCollector dc; + mdp3::IcebergFinder ice_finder; + mdp3::CompositeObserver obs; + if (sweep_definitions) + obs.append(&dc); + if (sweep_icebergs) + obs.append(&ice_finder); + if (sweep_definitions || sweep_icebergs) + mdp3::observe_channel(pcap, obs); + rv.icebergs = sweep_icebergs ? ice_finder.result + : mdp3::IcebergFileCache::find_icebergs(pcap); + if (sweep_definitions) + rv.definitions = std::move(dc.result); + LOG(OrderMan, Info, "Gathered {} securities, and {} icebergs", + rv.definitions.size(), rv.icebergs.size()); + return rv; +} + +} // namespace bts::spartan::cmds::matcher diff --git a/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.h b/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.h new file mode 100644 index 000000000..83abdc269 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/cmds/matcher/common/InitData.h @@ -0,0 +1,33 @@ +#pragma once +#include "domain/SecurityDefinition.h" +#include "market_data/feed_observers/IcebergFinder.h" +#include + +namespace bts::spartan::cmds::matcher { +/** + * Contains data required for (or at least relevant to) matcher/pcap + * observation. As the name 'InitData' suggests, this class is intended for + * data that is gathered before pcap observation begins. + */ +struct InitData { + /** + * Gathers data in preparation of matcher/pcap observation. + * + * @param[in] pcap The pcap file to be observed + * @param[in] sweep_definitions Whether or not to sweep the pcap file for + * security definitions. The matcher must have an index of securities + * for implied matching purposes. It is capable of indexing security + * definitions as they are observed in the pcap, but indexing them + * beforehand may offer performance benefits (though probably negligible). + * @param[in] sweep_icebergs Whether or not to sweep the pcap file for + * icebergs. If this is false, the icebergs are generated via + * @see bts::spartan::mdp3::iceberg_file_cache::find_icebergs(). + */ + static InitData init( + const std::string &pcap, bool sweep_definitions, bool sweep_icebergs); + + mdp3::IcebergMap icebergs; + std::unordered_map definitions; +}; + +} // namespace bts::spartan::cmds::matcher diff --git a/src/server/sparkd/cmds/spartan/common/Range.cc b/src/server/sparkd/cmds/spartan/common/Range.cc new file mode 100644 index 000000000..f74862996 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/common/Range.cc @@ -0,0 +1,38 @@ +#include "Range.h" + +namespace bts::spartan { + +template +Range::Range() : _start(0), _length(0) {} + +template +Range::Range(NumericT start, NumericT length) + : _start(start), _length(length) {} + +template +inline constexpr const NumericT &Range::start() const { + return _start; +} + +template +inline constexpr NumericT &Range::start() { + return _start; +} + +template +inline constexpr const NumericT &Range::length() const { + return _length; +} + +template +inline constexpr NumericT &Range::length() { + return _length; +} + +template +std::ostream &operator<<(std::ostream &out, const Range &rhs) { + out << rhs.start() << "(" << rhs.length() << ")"; + return out; +} + +} // namespace bts::spartan diff --git a/src/server/sparkd/cmds/spartan/common/Range.h b/src/server/sparkd/cmds/spartan/common/Range.h new file mode 100644 index 000000000..15d5337ea --- /dev/null +++ b/src/server/sparkd/cmds/spartan/common/Range.h @@ -0,0 +1,27 @@ +#pragma once +#include + +namespace bts::spartan { + +template +struct Range { + Range(); + Range(NumericT start, NumericT length); + + constexpr const NumericT &start() const; + constexpr NumericT &start(); + + constexpr const NumericT &length() const; + constexpr NumericT &length(); + + private: + NumericT _start; + NumericT _length; +}; + +template +std::ostream &operator<<(std::ostream &, const Range &); + +} // namespace bts::spartan + +#include "Range.cc" diff --git a/src/server/sparkd/cmds/spartan/common/cli/RangeArg.cpp b/src/server/sparkd/cmds/spartan/common/cli/RangeArg.cpp new file mode 100644 index 000000000..9b9b36a3b --- /dev/null +++ b/src/server/sparkd/cmds/spartan/common/cli/RangeArg.cpp @@ -0,0 +1,31 @@ +#include "RangeArg.h" +#include +#include + +namespace bts::spartan::cli { + +RangeArg::RangeArg() : _result() {} + +RangeArg::RangeArg(const std::string &arg) { + // absolute range + auto split_pos = arg.find('-'); + if (split_pos == 0 || split_pos == arg.length() - 1) + return; + if (split_pos != std::string::npos) { + _result.start() = std::stoi(arg.substr(0, split_pos)); + _result.length() = std::stoi(arg.substr(split_pos + 1)) - _result.start(); + return; + } + // relative range + split_pos = arg.find(':'); + if (split_pos == 0 || split_pos == arg.length() - 1) + return; + if (split_pos != std::string::npos) { + _result.start() = std::stoi(arg.substr(0, split_pos)); + _result.length() = std::stoi(arg.substr(split_pos + 1)); + } +} + +const Range &RangeArg::result() { return _result; } + +} // namespace bts::spartan::cli diff --git a/src/server/sparkd/cmds/spartan/common/cli/RangeArg.h b/src/server/sparkd/cmds/spartan/common/cli/RangeArg.h new file mode 100644 index 000000000..e349be511 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/common/cli/RangeArg.h @@ -0,0 +1,18 @@ +#pragma once +#include "../Range.h" +#include +#include + +namespace bts::spartan::cli { + + struct RangeArg { + RangeArg(); + RangeArg(const std::string &); + + const Range &result(); + + private: + Range _result; + }; + +} diff --git a/src/server/sparkd/cmds/spartan/domain/EventRange.h b/src/server/sparkd/cmds/spartan/domain/EventRange.h new file mode 100644 index 000000000..317e241ac --- /dev/null +++ b/src/server/sparkd/cmds/spartan/domain/EventRange.h @@ -0,0 +1,9 @@ +#pragma once +#include "server/sparkd/cmds/spartan/common/Range.h" +#include "server/sparkd/cmds/spartan/domain/EventID.h" + +namespace bts::spartan::mdp3 { + +using EventRange = Range; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cc b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cc new file mode 100644 index 000000000..b60f64fcf --- /dev/null +++ b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cc @@ -0,0 +1,29 @@ +#include "SecurityCriteria.h" + +namespace bts::spartan::mdp3 { + +template +inline SecurityCriteria SecurityCriteria::create( + const Venues &exchanges, + const SecurityTypes &security_types, + const Assets &assets, + const SecurityGroups &security_groups, + const SecurityIDs &security_ids) { + SecurityCriteria criteria; + Clause& clause = criteria.clauses.emplace_back(); + for (auto exch : exchanges) + clause.exchanges.emplace_back(exch); + for (auto sec_type : security_types) + clause.security_types.emplace_back(sec_type); + for (const auto &ass : assets) + clause.assets.emplace_back(ass); + for (const auto &sec_group : security_groups) + clause.security_groups.emplace_back(sec_group); + for (auto sec_id : security_ids) + clause.security_ids.emplace(sec_id); + if (!clause.is_defined()) + criteria.clauses.clear(); + return criteria; +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cpp b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cpp index f71d8ccf4..8d84ca405 100644 --- a/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cpp +++ b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.cpp @@ -40,4 +40,8 @@ bool SecurityCriteria::includes(const SecurityDefinition &def) const { return false; } +bool SecurityCriteria::includes_or_undefined(const SecurityDefinition &def) const { + return includes(def) || !is_defined(); +} + } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.h b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.h index 07eef2618..6e1917fbd 100644 --- a/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.h +++ b/src/server/sparkd/cmds/spartan/domain/SecurityCriteria.h @@ -31,10 +31,26 @@ struct SecurityCriteria { bool includes(const SecurityDefinition &instrument) const; }; + template < + class Venues = std::vector, + class SecurityTypes = std::vector, + class Assets = std::vector, + class SecurityGroups = std::vector, + class SecurityIDs = std::vector> + static SecurityCriteria create( + const Venues &exchanges = {}, + const SecurityTypes &security_types = {}, + const Assets &assets = {}, + const SecurityGroups &security_groups = {}, + const SecurityIDs &security_ids = {}); + bool is_defined() const; bool includes(const SecurityDefinition &instrument) const; + bool includes_or_undefined(const SecurityDefinition &) const; boost::container::small_vector clauses; }; } // namespace bts::spartan::mdp3 + +#include "SecurityCriteria.cc" diff --git a/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMap.h b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMap.h new file mode 100644 index 000000000..7a2520df8 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMap.h @@ -0,0 +1,9 @@ +#pragma once +#include "domain/EventID.h" +#include + +namespace bts::spartan::mdp3 { + +using EventRangeMap = boost::container::flat_map; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cc b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cc new file mode 100644 index 000000000..d0154dd2e --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cc @@ -0,0 +1,9 @@ +#include "EventRangeMonitor.h" + +namespace bts::spartan::mdp3 { + +constexpr EventID &EventRangeMonitor::event() { return _event; } + +constexpr const EventID &EventRangeMonitor::event() const { return _event; } + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cpp b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cpp new file mode 100644 index 000000000..f3101a948 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.cpp @@ -0,0 +1,35 @@ +#include "EventRangeMonitor.h" + +namespace bts::spartan::mdp3 { + +EventRangeMonitor::EventRangeMonitor() : _event(0), _observed_events() {} + +EventRangeMonitor::EventRangeMonitor( + boost::container::flat_map observed_events) + : _event(0), _observed_events(observed_events) {} + +EventRangeMonitor::State EventRangeMonitor::state() const { + return peek(event()); +} + +EventRangeMonitor::State EventRangeMonitor::peek(EventID event_id) const { + // + if (_observed_events.empty()) + return EventRangeMonitor::State::None; + auto it = _observed_events.upper_bound(event_id); + if (it == _observed_events.end()) { + it--; + return event_id < (it->first + it->second) + ? EventRangeMonitor::State::Listening + : EventRangeMonitor::State::Done; + } else if (it == _observed_events.begin()) { + return EventRangeMonitor::State::Idle; + } else { + it--; + return event_id >= it->first && event_id < (it->first + it->second) + ? EventRangeMonitor::State::Listening + : EventRangeMonitor::State::Idle; + } +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.h b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.h new file mode 100644 index 000000000..a36acf311 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/common/EventRangeMonitor.h @@ -0,0 +1,53 @@ +#pragma once +#include "server/sparkd/cmds/spartan/domain/EventID.h" +#include + +namespace bts::spartan::mdp3 { + +/** + * Signals callers when events falls within one or more particular event + * ranges + */ +class EventRangeMonitor { + public: + EventRangeMonitor(); + EventRangeMonitor( + boost::container::flat_map observed_events); + + enum class State { + None, + Idle, + Listening, + Done + }; + + /** + * Gets the state associated with the current event + * + * @see event + */ + State state() const; + + /** + * Gets the state associated with a particular event + */ + State peek(EventID) const; + + /** + * Gets the current event + */ + constexpr EventID &event(); + + /** + * Gets the current event + */ + constexpr const EventID &event() const; + + private: + EventID _event; + boost::container::flat_map _observed_events; +}; + +} // namespace bts::spartan::mdp3 + +#include "EventRangeMonitor.cc" diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.cpp b/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.cpp new file mode 100644 index 000000000..9bb5884f3 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.cpp @@ -0,0 +1,46 @@ +#include "CompositeObserver.h" + +namespace bts::spartan::mdp3 { + +CompositeObserver::CompositeObserver() {} + +CompositeObserver::CompositeObserver( + const std::initializer_list &init) + : _observers(init) {} + +void CompositeObserver::init() { + for (auto *o : _observers) + o->init(); +} + +void CompositeObserver::finit() { + for (auto *o : _observers) + o->finit(); +} + +void CompositeObserver::on_recovery_complete(InitialSnapshot const &s) { + for (auto *o : _observers) + o->on_recovery_complete(s); +} + +void CompositeObserver::on_packet_begin(MDP3PacketView const &pv) { + for (auto *o : _observers) + o->on_packet_begin(pv); +} + +void CompositeObserver::on_event_end(MDP3Event const &ev) { + for (auto *o : _observers) + o->on_event_end(ev); +} + +void CompositeObserver::append(IMDP3FeedObserver *observer) { + bts_assert(observer != nullptr); + _observers.push_back(observer); +} + +void CompositeObserver::safe_append(IMDP3FeedObserver *observer) { + if (observer != nullptr) + _observers.push_back(observer); +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.h b/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.h new file mode 100644 index 000000000..5c68cf3e3 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/CompositeObserver.h @@ -0,0 +1,33 @@ +#pragma once +#include "server/sparkd/cmds/spartan/domain/SecurityDefinition.h" +#include "server/sparkd/cmds/spartan/market_data/common/mdp3_common.h" +#include "server/sparkd/cmds/spartan/market_data/handler/IMDP3FeedObserver.h" +#include + +namespace bts::spartan::mdp3 { + +/** + * A single observer that represents a group of observers + */ +struct CompositeObserver : IMDP3FeedObserver { + CompositeObserver(); + CompositeObserver(const std::initializer_list &); + void init() override; + void finit() override; + void on_recovery_complete(InitialSnapshot const &) override; + void on_packet_begin(MDP3PacketView const &) override; + void on_event_end(MDP3Event const &) override; + /** + * Asserts that the observer isn't a nullptr before appending it + */ + void append(IMDP3FeedObserver *); + /** + * Appends the observer if it isn't a nullptr + */ + void safe_append(IMDP3FeedObserver *); + + private: + std::vector _observers; +}; + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.cpp b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.cpp index 7f618a5b9..6b95ecb3e 100644 --- a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.cpp +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.cpp @@ -1,39 +1,19 @@ #include "MatcherBookRecorder.h" -#include "server/sparkd/cmds/spartan/back_testing/sim/pcap/PCapOrderChangeBootstrapper.h" -#include "server/sparkd/cmds/spartan/domain/SecuritySnapshot.h" -#include -#include -#include +#include "domain/EventID.h" +#include "domain/book/Book.h" +#include "lib/utils/bts_assert.h" +#include "market_data/common/mdp3_common.h" namespace bts::spartan::mdp3 { -#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__) -#define INFO(...) _LOG(Info, __VA_ARGS__) -#define WARN(...) _LOG(Warn, __VA_ARGS__) - -bool book_equals( - const SecuritySnapshot *snap, MergedMatcher &matcher, Side side) { - auto exch_books = snap->book_side(side); - auto match_books = matcher.book(snap->security_id(), side); - for (uint32_t i = 0; i < exch_books.size(); i++) { - if (match_books[i].quantity != exch_books[i].quantity) - return false; - if (match_books[i].quantity == 0) - return true; - if (match_books[i].price != exch_books[i].price) - return false; - } - return true; -} - -void _write_book(std::ostream &out, const BookSide &book) { +static void _write_book(std::ostream &out, const BookSide &book) { for (const auto &l : book) out << "," << l.price << "," << l.quantity << "," << l.n_orders; } -void _write_row( +static void _write_row( std::ostream &out, - size_t event_id, + EventID event_id, SecurityID sec_id, const BookSide &bids, const BookSide &asks) { @@ -43,107 +23,28 @@ void _write_row( out << "\n"; } -void _write_rows( - std::ostream &out, - size_t event_id, - const std::vector &snaps, - MergedMatcher &matcher) { - for (const auto *s : snaps) { - auto bids = matcher.book(s->security_id(), Side::Buy); - auto asks = matcher.book(s->security_id(), Side::Sell); - _write_row(out, event_id, s->security_id(), bids, asks); - } -} +MatcherBookRecorder::MatcherBookRecorder() {} -SmallOrderChangeVec to_small_change_vec( - const OrderChanges &changes, const IcebergMap &icebergs, size_t event_id) { - SmallOrderChangeVec rv; - for (const auto &ch : changes) { - auto &sch = rv.emplace_back(ch, true); - auto ib_it = icebergs.find(ch.order.key); - if (ib_it != icebergs.end()) - iceberg_helper::add_iceberg_annotation( - sch.order, sch.change, ib_it->second, event_id, false); - } - return rv; -} - -template -inline void _process_changes( +static void _write_rows( + const std::vector> &effects, std::ostream &out, - const SnapshotContainer &snaps, - const SecurityCriteria &instrument_criteria, - PCapOrderChangeBootstrapper &bootstrapper, - MergedMatcher &matcher, - const IcebergMap &icebergs, - bool reset_after_mismatch, - size_t event_id) { - std::vector effects; - std::unordered_set processed_secs; - for (const auto *s : snaps) { - if (instrument_criteria.is_defined() && - !instrument_criteria.includes(s->definition())) - continue; - auto changes = bootstrapper.deduced_order_changes(s, event_id); - if (changes.empty()) - continue; - auto schanges = to_small_change_vec(changes, icebergs, event_id); - matcher.match( - MergedMatcher::ChangeSrc::SIMULATOR_INPUT, schanges, &effects); - processed_secs.insert(s->security_id()); - } + EventID event_id) { for (const auto &eff : effects) { if (std::holds_alternative(eff)) { const auto &up = std::get(eff); _write_row(out, event_id, up.security_id, up.mbp_buy, up.mbp_sell); } } - if (reset_after_mismatch) { - for (const auto *s : snaps) { - if (!processed_secs.count(s->security_id())) - continue; - if (!book_equals(s, matcher, Side::Buy) || - !book_equals(s, matcher, Side::Sell)) { - WARN( - "Discrepancy between matcher books and actual books detected " - "for [{}]{} on event {}. Resetting matcher to exchange state", - s->security_id(), s->symbol(), event_id); - std::vector resting_orders; - for (const auto &p : s->orders()) - resting_orders.emplace_back(p.second); - matcher.reset(s->security_id(), resting_orders); - } - } - } } -struct MatcherBookRecorder::PImpl { - MergedMatcher &matcher; - const IcebergMap &icebergs; - const SecurityCriteria &instrument_criteria; - bool reset_after_mismatch; - PCapOrderChangeBootstrapper bootstrapper; -}; - -MatcherBookRecorder::MatcherBookRecorder(Args args) - : _me(new MatcherBookRecorder::PImpl{ - args.matcher, args.icebergs, args.instrument_criteria, - args.reset_after_mismatch, PCapOrderChangeBootstrapper()}) {} - -MatcherBookRecorder::~MatcherBookRecorder() {} - -void MatcherBookRecorder::on_recovery_complete( - std::ostream &out, const std::vector &snaps) { - _process_changes( - out, snaps, _me->instrument_criteria, _me->bootstrapper, _me->matcher, - _me->icebergs, _me->reset_after_mismatch, 0); +void MatcherBookRecorder::on_recovery_complete(RecoveryCompleteArgs &args) { + bts_assert(args.effects != nullptr); + _write_rows(*args.effects, args.out, 0); } -void MatcherBookRecorder::on_event_end(std::ostream &out, const MDP3Event &ev) { - std::vector effects; - _process_changes( - out, ev.secs(), _me->instrument_criteria, _me->bootstrapper, - _me->matcher, _me->icebergs, _me->reset_after_mismatch, ev.event_id); +void MatcherBookRecorder::on_event_end(EventEndArgs &args) { + bts_assert(args.effects != nullptr); + _write_rows(*args.effects, args.out, args.mdp3_event.event_id); } } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.h b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.h index 4fd744765..90c5e20ab 100644 --- a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.h +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherBookRecorder.h @@ -1,32 +1,14 @@ #pragma once #include "FeedRecorder.h" -#include "server/sparkd/cmds/spartan/back_testing/matcher/Matcher.h" -#include "server/sparkd/cmds/spartan/back_testing/matcher/iceberg_helper.h" -#include "server/sparkd/cmds/spartan/domain/SecurityCriteria.h" -#include "server/sparkd/cmds/spartan/market_data/common/mdp3_common.h" -#include -#include +#include "MatcherRecorder.h" namespace bts::spartan::mdp3 { -struct MatcherBookRecorder : public IFeedRecorder { - struct Args { - MergedMatcher &matcher; - const IcebergMap &icebergs; - const SecurityCriteria &instrument_criteria; - bool reset_after_mismatch; - }; +struct MatcherBookRecorder : public MatcherRecorder { + MatcherBookRecorder(); - MatcherBookRecorder(Args); - ~MatcherBookRecorder(); - - void on_recovery_complete( - std::ostream &, const std::vector &) override; - void on_event_end(std::ostream &, const MDP3Event &) override; - - private: - struct PImpl; - std::unique_ptr _me; + void on_recovery_complete(RecoveryCompleteArgs &) override; + void on_event_end(EventEndArgs &) override; }; } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.cpp b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.cpp new file mode 100644 index 000000000..812188a35 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.cpp @@ -0,0 +1,276 @@ +#include "MatcherRecorder.h" +#include "back_testing/sim/pcap/PCapOrderChangeBootstrapper.h" +#include "common/Stopwatch.h" +#include "domain/SecuritySnapshot.h" +#include "market_data/common/EventRangeMap.h" +#include "market_data/common/EventRangeMonitor.h" +#include "market_data/gen/src/SecurityTradingStatus.h" +#include + +namespace bts::spartan::mdp3 { + +#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__) +#define DIAG(...) _LOG(Diag, __VA_ARGS__) +#define INFO(...) _LOG(Info, __VA_ARGS__) +#define WARN(...) _LOG(Warn, __VA_ARGS__) + +static EventRangeMap event_range_map(const std::vector events) { + EventRangeMap erm; + for (auto ev_range : events) + erm[ev_range.start()] = ev_range.length(); + return erm; +} + +/** + * Determines if the matcher's mbp equals that of the SecuritySnapshot (n_orders + * at price levels is ignored) + */ +static bool +mbp_equals(const SecuritySnapshot *snap, MergedMatcher &matcher, Side side) { + auto exch_books = snap->book_side(side); + auto match_books = matcher.book(snap->security_id(), side); + for (uint32_t i = 0; i < exch_books.size(); i++) { + if (match_books[i].quantity != exch_books[i].quantity) + return false; + if (match_books[i].quantity == 0) + return true; + if (match_books[i].price != exch_books[i].price) + return false; + } + return true; +} + +static SmallOrderChangeVec to_small_change_vec( + const OrderChanges &changes, const IcebergMap &icebergs, size_t event_id) { + SmallOrderChangeVec rv; + for (const auto &ch : changes) { + auto &sch = rv.emplace_back(ch, true); + iceberg_helper::add_iceberg_annotation( + sch.order, sch.change, icebergs, event_id, false); + } + return rv; +} + +static bool is_security_active( + const SecuritySnapshot *security, + const SecurityCriteria &security_criteria) { + return security->trading_status() == + ::mdp3::SecurityTradingStatus::ReadyToTrade && + security_criteria.includes_or_undefined(security->definition()); +} + +static std::uint16_t count_aggressor_secs(const MDP3Event::SecContainer &secs) { + std::uint16_t num_aggs = 0; + for (const auto *s : secs) { + for (const auto &f : s->fills()) { + if (f.is_aggressor()) { + num_aggs++; + break; + } + } + } + return num_aggs; +} + +template +static inline MatcherRecorder::MatcherProcResults process_changes( + const SnapshotContainer &snaps, + const SecurityCriteria &security_criteria, + PCapOrderChangeBootstrapper &bootstrapper, + MergedMatcher &matcher, + const IcebergMap &icebergs, + std::vector &effects, + size_t event_id) { + Stopwatch stopwatch; + for (const auto *s : snaps) { + if (!is_security_active(s, security_criteria)) + continue; + auto changes = bootstrapper.deduced_order_changes(s, event_id); + auto schanges = to_small_change_vec(changes, icebergs, event_id); + stopwatch.start(); + matcher.match( + MergedMatcher::ChangeSrc::SIMULATOR_INPUT, schanges, &effects); + stopwatch.stop(); + } + bool mbp_correct = true; + for (const auto *s : snaps) { + if (!is_security_active(s, security_criteria)) + continue; + if (!mbp_equals(s, matcher, Side::Buy) || + !mbp_equals(s, matcher, Side::Sell)) { + WARN( + "[event {}] Discrepancy between matcher books and actual books " + "detected for [{}] {}", + event_id, s->security_id(), s->symbol()); + mbp_correct = false; + } + } + return {mbp_correct, stopwatch.elapsed().count()}; +} + +static void reset_books( + MergedMatcher &matcher, + PCapOrderChangeBootstrapper &bootstrapper, + const IcebergMap &icebergs, + const std::unordered_map &securities, + EventID event_id) { + INFO( + "[event {}] MatcherRecorder initializing matcher with resting orders", + event_id); + // Reset all security's books because implied matching could have corrupted + // any of them. Clear the matcher before adding the resting orders so they + // don't inadvertantly cross a corrupt implied market. + matcher.clear(); + for (const auto &sec_p : securities) { + auto resting_orders = bootstrapper.init_orders(sec_p.second, event_id); + for (auto &o : resting_orders) + iceberg_helper::add_iceberg_annotation( + o, OrderChange::ChangeType::added, icebergs, event_id, true); + matcher.reset(sec_p.second->security_id(), resting_orders); + } +} + +struct MatcherRecorder::Curry::PImpl { + std::ostream &out; + MergedMatcher &matcher; + const IcebergMap &icebergs; + SecurityCriteria security_criteria; + std::unique_ptr recorder; + PCapOrderChangeBootstrapper bootstrapper; + EventRangeMonitor event_monitor; + std::uint16_t max_aggressors; + bool verbose; + std::unordered_map securities{}; + bool is_listening = true; + bool done = false; +}; + +MatcherRecorder::Curry::Curry(MatcherRecorder::Curry::Args args) + : _me(new MatcherRecorder::Curry::PImpl{ + args.out, args.matcher, args.icebergs, args.security_criteria, + std::move(args.recorder), PCapOrderChangeBootstrapper(), + event_range_map(args.observed_events), args.max_aggressors, + args.verbose}) {} + +MatcherRecorder::Curry::~Curry() {} + +void MatcherRecorder::Curry::on_recovery_complete( + const std::vector &snaps) { + if (_me->done) + return; + INFO("[event 0, on_recovery_complete] MatcherRecorder resetting all state"); + _me->securities.clear(); + _me->matcher.clear(); + _me->bootstrapper.reset(); + _me->event_monitor.event() = 0; + _me->is_listening = true; + // Add defs to the matcher to build implied matching index + for (const auto *s : snaps) + if (_me->security_criteria.includes_or_undefined(s->definition()) && + _me->securities.emplace(s->security_id(), s).second) + _me->matcher.add_def(s->definition()); + // Add resting orders + std::vector effects; + auto proc_res = process_changes( + snaps, _me->security_criteria, _me->bootstrapper, _me->matcher, + _me->icebergs, effects, 0); + MatcherRecorder::RecoveryCompleteArgs args{ + snaps, _me->matcher, proc_res, _me->out, &effects}; + _me->recorder->on_recovery_complete(args); +} + +void MatcherRecorder::Curry::on_event_end(const MDP3Event &ev) { + if (_me->done) + return; + // Add resting orders + _me->event_monitor.event() = ev.event_id; + bool was_listening = _me->is_listening; + switch (_me->event_monitor.state()) { + case EventRangeMonitor::State::Idle: + _me->is_listening = false; + break; + case EventRangeMonitor::State::Done: + _me->is_listening = false; + if (!_me->done) { + INFO("[event {}] MatcherRecorder finished observation.", ev.event_id); + _me->done = true; + } + return; + case EventRangeMonitor::State::Listening: + case EventRangeMonitor::State::None: + _me->is_listening = true; + break; + default: + bts_assert(false); + break; + } + // 'skip_this_event_only' has a different meaning than '!_me->listening.' + // If the former is true, the matcher is reset with the current resting + // orders, so incremental changes may be processed on the next update (if it + // isn't ignored/skipped). However, if the latter is false, the matcher is + // cleared, and is not initialized with resting orders until the next event + // where '_me->is_listening' is true (this means the matcher won't process + // incremental changes on that update either, as it won't already have been + // bootstrapped). + // + // Note that 'skip_this_event_only' doesn't affect state beyond this call. + // Predicates (other than the event range filter) should flip + // 'skip_this_event_only' to true if they evaluate to false. + bool skip_this_event_only = false; + if (_me->is_listening && _me->max_aggressors > 0) { + auto num_aggs = count_aggressor_secs(ev.secs()); + if (num_aggs > _me->max_aggressors) { + INFO( + "[event {}] MatcherRecorder ignoring event: too many securities " + "with aggressor orders ({}, max is {})", + ev.event_id, num_aggs, _me->max_aggressors); + skip_this_event_only = true; + } + } + if (skip_this_event_only) { + // This event falls within an observed range, but another predicate + // evaluated to false, indicating this event's incremental changes should + // not be processed. Reset the matcher with resting orders so it is + // prepared to process incremental changes on the next update. + reset_books( + _me->matcher, _me->bootstrapper, _me->icebergs, _me->securities, + ev.event_id); + } else if (!_me->is_listening) { + if (was_listening) { + // This event is ignored, but the previous event was observed. + // Clear the matcher and reset the bootstrapper (the latter is reset to + // ensure securities are bootstrapped on their next update) + INFO("[event {}] MatcherRecorder clearing all books", ev.event_id); + _me->bootstrapper.reset(); + _me->matcher.clear(); + } + } else if (!was_listening) { + // This event is observed, but the previous event was ignored. Bootstrap + // the matcher with resting orders + reset_books( + _me->matcher, _me->bootstrapper, _me->icebergs, _me->securities, + ev.event_id); + } else { + // This event is observed, as was the previous event. Process incremental + // changes and reconcile the matcher's results with those of the exchange. + std::vector effects; + if (_me->verbose) + DIAG( + "[event {}] MatcherRecorder processing order changes", + ev.event_id); + auto proc_res = process_changes( + ev.secs(), _me->security_criteria, _me->bootstrapper, _me->matcher, + _me->icebergs, effects, ev.event_id); + MatcherRecorder::EventEndArgs args{ + ev, _me->matcher, proc_res, _me->out, &effects}; + _me->recorder->on_event_end(args); + if (!proc_res.mbp_correct) { + // Reset the books to avoid compounding errors on subsequent events + reset_books( + _me->matcher, _me->bootstrapper, _me->icebergs, _me->securities, + ev.event_id); + } + } +} + +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.h b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.h new file mode 100644 index 000000000..1de8770e8 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/market_data/feed_observers/recorders/MatcherRecorder.h @@ -0,0 +1,78 @@ +#pragma once +#include "FeedRecorder.h" +#include "back_testing/matcher/Matcher.h" +#include "back_testing/matcher/iceberg_helper.h" +#include "domain/EventRange.h" +#include "domain/SecurityCriteria.h" +#include "market_data/common/mdp3_common.h" +#include +#include +#include + +namespace bts::spartan::mdp3 { + +class MatcherRecorder { + public: + struct MatcherProcResults { + bool mbp_correct; + std::int64_t proc_time_nanos; + }; + + struct RecoveryCompleteArgs { + const std::vector initial_snapshot; + MergedMatcher &matcher; + MatcherProcResults matcher_proc_results; + std::ostream &out; + const std::vector *effects; + }; + + struct EventEndArgs { + const MDP3Event &mdp3_event; + MergedMatcher &matcher; + MatcherProcResults matcher_proc_results; + std::ostream &out; + const std::vector> *effects; + }; + + struct BooksResetArgs { + const MDP3Event &mdp3_event; + MergedMatcher &matcher; + std::ostream &out; + const std::vector> *effects; + }; + + virtual ~MatcherRecorder() {} + + virtual void on_recovery_complete(RecoveryCompleteArgs &) {} + virtual void on_event_end(EventEndArgs &) {} + virtual void on_books_reset(BooksResetArgs &) {} + + class Curry : public IMDP3FeedObserver { + public: + struct Args { + std::ostream &out; + MergedMatcher &matcher; + const IcebergMap &icebergs; + std::unique_ptr recorder; + SecurityCriteria security_criteria{}; + std::vector observed_events{}; + std::uint16_t max_aggressors = 0; + bool verbose = false; + }; + + Curry(); + Curry(Args); + ~Curry(); + + void on_recovery_complete( + const std::vector &s) override; + + void on_event_end(MDP3Event const &ev) override; + + private: + struct PImpl; + std::unique_ptr _me; + }; +}; + +} // namespace bts::spartan::mdp3