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.
This commit is contained in:
1 parent
042c451bd6
commit
82332bf92f
29 files changed
+995
-249
No files matched your search
@@ -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()));
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#include "Trace.h"
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
template <class TracedOrders, class TracedEvents, class IgnoredEvents>
|
||||
inline Trace Trace::create(
|
||||
const TracedOrders &traced_orders,
|
||||
const TracedEvents &traced_events,
|
||||
const IgnoredEvents &ignored_events) {
|
||||
std::map<OrderKey, bool> traced_orders_map;
|
||||
std::map<size_t, bool> traced_events_map;
|
||||
std::map<size_t, bool> 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
|
||||
@@ -3,12 +3,22 @@
|
||||
#include "domain/order/OrderKey.h"
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
class Trace {
|
||||
public:
|
||||
bool log(OrderKey key, std::size_t eid = 0) const;
|
||||
template <
|
||||
class TracedOrders = std::vector<std::uint64_t>,
|
||||
class TracedEvents = std::vector<std::size_t>,
|
||||
class IgnoredEvents = std::vector<std::size_t>>
|
||||
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"
|
||||
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <CLI11/CLI11.hpp>
|
||||
|
||||
namespace bts::spartan::cmds {
|
||||
|
||||
struct MatcherCmd : public CLI::App {
|
||||
MatcherCmd();
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::cmds
|
||||
@@ -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 <boost/container/small_vector.hpp>
|
||||
|
||||
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<std::string> assets;
|
||||
std::vector<std::string> 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
|
||||
@@ -1,16 +0,0 @@
|
||||
#pragma once
|
||||
#include <CLI11/CLI11.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace bts::spartan::cmds {
|
||||
|
||||
struct SimBooks : public CLI::App {
|
||||
SimBooks();
|
||||
~SimBooks();
|
||||
|
||||
private:
|
||||
struct Args;
|
||||
std::unique_ptr<Args> _args;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::cmds
|
||||
@@ -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 <memory>
|
||||
|
||||
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<std::string> assets;
|
||||
std::vector<std::string> security_groups;
|
||||
std::vector<std::uint64_t> security_ids;
|
||||
std::vector<std::uint64_t> trace_orders;
|
||||
std::vector<std::size_t> trace_events;
|
||||
std::vector<cli::RangeArg> 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: <x>, or in range form: <start-stop> or <start:length>)");
|
||||
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<mdp3::EventRange> 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<mdp3::MatcherRecorder>(
|
||||
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
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include <CLI11/CLI11.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace bts::spartan::cmds::matcher::cmds {
|
||||
|
||||
struct BooksCmd : public CLI::App {
|
||||
BooksCmd();
|
||||
~BooksCmd();
|
||||
|
||||
private:
|
||||
struct Args;
|
||||
std::unique_ptr<Args> _args;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::cmds::matcher::cmds
|
||||
@@ -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 <optional>
|
||||
#include <unordered_map>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include "domain/SecurityDefinition.h"
|
||||
#include "market_data/feed_observers/IcebergFinder.h"
|
||||
#include <unordered_map>
|
||||
|
||||
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<mdp3::SecurityID, mdp3::SecurityDefinition> definitions;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::cmds::matcher
|
||||
@@ -0,0 +1,38 @@
|
||||
#include "Range.h"
|
||||
|
||||
namespace bts::spartan {
|
||||
|
||||
template <class NumericT>
|
||||
Range<NumericT>::Range() : _start(0), _length(0) {}
|
||||
|
||||
template <class NumericT>
|
||||
Range<NumericT>::Range(NumericT start, NumericT length)
|
||||
: _start(start), _length(length) {}
|
||||
|
||||
template <class NumericT>
|
||||
inline constexpr const NumericT &Range<NumericT>::start() const {
|
||||
return _start;
|
||||
}
|
||||
|
||||
template <class NumericT>
|
||||
inline constexpr NumericT &Range<NumericT>::start() {
|
||||
return _start;
|
||||
}
|
||||
|
||||
template <class NumericT>
|
||||
inline constexpr const NumericT &Range<NumericT>::length() const {
|
||||
return _length;
|
||||
}
|
||||
|
||||
template <class NumericT>
|
||||
inline constexpr NumericT &Range<NumericT>::length() {
|
||||
return _length;
|
||||
}
|
||||
|
||||
template <class NumericT>
|
||||
std::ostream &operator<<(std::ostream &out, const Range<NumericT> &rhs) {
|
||||
out << rhs.start() << "(" << rhs.length() << ")";
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::spartan
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
#include <ostream>
|
||||
|
||||
namespace bts::spartan {
|
||||
|
||||
template <class NumericT>
|
||||
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 <class NumericT>
|
||||
std::ostream &operator<<(std::ostream &, const Range<NumericT> &);
|
||||
|
||||
} // namespace bts::spartan
|
||||
|
||||
#include "Range.cc"
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "RangeArg.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
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<std::uint64_t> &RangeArg::result() { return _result; }
|
||||
|
||||
} // namespace bts::spartan::cli
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include "../Range.h"
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace bts::spartan::cli {
|
||||
|
||||
struct RangeArg {
|
||||
RangeArg();
|
||||
RangeArg(const std::string &);
|
||||
|
||||
const Range<std::uint64_t> &result();
|
||||
|
||||
private:
|
||||
Range<std::uint64_t> _result;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -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<std::size_t>;
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "SecurityCriteria.h"
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
template <class Venues, class SecurityTypes, class Assets, class SecurityGroups, class SecurityIDs>
|
||||
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
|
||||
@@ -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
|
||||
@@ -31,10 +31,26 @@ struct SecurityCriteria {
|
||||
bool includes(const SecurityDefinition &instrument) const;
|
||||
};
|
||||
|
||||
template <
|
||||
class Venues = std::vector<api::Venue>,
|
||||
class SecurityTypes = std::vector<api::SecurityType>,
|
||||
class Assets = std::vector<std::string>,
|
||||
class SecurityGroups = std::vector<std::string>,
|
||||
class SecurityIDs = std::vector<SecurityID>>
|
||||
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<Clause, 1> clauses;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
|
||||
#include "SecurityCriteria.cc"
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include "domain/EventID.h"
|
||||
#include <boost/container/flat_map.hpp>
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
using EventRangeMap = boost::container::flat_map<EventID, std::size_t>;
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
@@ -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
|
||||
@@ -0,0 +1,35 @@
|
||||
#include "EventRangeMonitor.h"
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
EventRangeMonitor::EventRangeMonitor() : _event(0), _observed_events() {}
|
||||
|
||||
EventRangeMonitor::EventRangeMonitor(
|
||||
boost::container::flat_map<EventID, std::size_t> 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
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
#include "server/sparkd/cmds/spartan/domain/EventID.h"
|
||||
#include <boost/container/flat_map.hpp>
|
||||
|
||||
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<EventID, std::size_t> 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<EventID, std::size_t> _observed_events;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
|
||||
#include "EventRangeMonitor.cc"
|
||||
@@ -0,0 +1,46 @@
|
||||
#include "CompositeObserver.h"
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
CompositeObserver::CompositeObserver() {}
|
||||
|
||||
CompositeObserver::CompositeObserver(
|
||||
const std::initializer_list<IMDP3FeedObserver *> &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
|
||||
@@ -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 <vector>
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
/**
|
||||
* A single observer that represents a group of observers
|
||||
*/
|
||||
struct CompositeObserver : IMDP3FeedObserver {
|
||||
CompositeObserver();
|
||||
CompositeObserver(const std::initializer_list<IMDP3FeedObserver *> &);
|
||||
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<IMDP3FeedObserver *> _observers;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
+17
-116
@@ -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 <iomanip>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#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<const SecuritySnapshot *> &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 <class SnapshotContainer>
|
||||
inline void _process_changes(
|
||||
static void _write_rows(
|
||||
const std::vector<std::variant<SimBookUpdate, SimOrderUpdate>> &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<MatchEffect> effects;
|
||||
std::unordered_set<SecurityID> 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<SimBookUpdate>(eff)) {
|
||||
const auto &up = std::get<SimBookUpdate>(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<MDP3Order> 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<const SecuritySnapshot *> &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<MatchEffect> 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
|
||||
+5
-23
@@ -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 <memory>
|
||||
#include <ostream>
|
||||
#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<const SecuritySnapshot *> &) override;
|
||||
void on_event_end(std::ostream &, const MDP3Event &) override;
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> _me;
|
||||
void on_recovery_complete(RecoveryCompleteArgs &) override;
|
||||
void on_event_end(EventEndArgs &) override;
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
+276
@@ -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 <string>
|
||||
|
||||
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<EventRange> 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 <class SnapshotContainer>
|
||||
static inline MatcherRecorder::MatcherProcResults process_changes(
|
||||
const SnapshotContainer &snaps,
|
||||
const SecurityCriteria &security_criteria,
|
||||
PCapOrderChangeBootstrapper &bootstrapper,
|
||||
MergedMatcher &matcher,
|
||||
const IcebergMap &icebergs,
|
||||
std::vector<MatchEffect> &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<std::nano>().count()};
|
||||
}
|
||||
|
||||
static void reset_books(
|
||||
MergedMatcher &matcher,
|
||||
PCapOrderChangeBootstrapper &bootstrapper,
|
||||
const IcebergMap &icebergs,
|
||||
const std::unordered_map<SecurityID, const SecuritySnapshot *> &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<MatcherRecorder> recorder;
|
||||
PCapOrderChangeBootstrapper bootstrapper;
|
||||
EventRangeMonitor event_monitor;
|
||||
std::uint16_t max_aggressors;
|
||||
bool verbose;
|
||||
std::unordered_map<SecurityID, const SecuritySnapshot *> 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<const SecuritySnapshot *> &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<MatchEffect> 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<MatchEffect> 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
|
||||
@@ -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 <memory>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace bts::spartan::mdp3 {
|
||||
|
||||
class MatcherRecorder {
|
||||
public:
|
||||
struct MatcherProcResults {
|
||||
bool mbp_correct;
|
||||
std::int64_t proc_time_nanos;
|
||||
};
|
||||
|
||||
struct RecoveryCompleteArgs {
|
||||
const std::vector<const SecuritySnapshot *> initial_snapshot;
|
||||
MergedMatcher &matcher;
|
||||
MatcherProcResults matcher_proc_results;
|
||||
std::ostream &out;
|
||||
const std::vector<MatchEffect> *effects;
|
||||
};
|
||||
|
||||
struct EventEndArgs {
|
||||
const MDP3Event &mdp3_event;
|
||||
MergedMatcher &matcher;
|
||||
MatcherProcResults matcher_proc_results;
|
||||
std::ostream &out;
|
||||
const std::vector<std::variant<SimBookUpdate, SimOrderUpdate>> *effects;
|
||||
};
|
||||
|
||||
struct BooksResetArgs {
|
||||
const MDP3Event &mdp3_event;
|
||||
MergedMatcher &matcher;
|
||||
std::ostream &out;
|
||||
const std::vector<std::variant<SimBookUpdate, SimOrderUpdate>> *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<MatcherRecorder> recorder;
|
||||
SecurityCriteria security_criteria{};
|
||||
std::vector<EventRange> observed_events{};
|
||||
std::uint16_t max_aggressors = 0;
|
||||
bool verbose = false;
|
||||
};
|
||||
|
||||
Curry();
|
||||
Curry(Args);
|
||||
~Curry();
|
||||
|
||||
void on_recovery_complete(
|
||||
const std::vector<const SecuritySnapshot *> &s) override;
|
||||
|
||||
void on_event_end(MDP3Event const &ev) override;
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> _me;
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace bts::spartan::mdp3
|
||||
Reference in new issue
Block a user