Files
spark/src/server/sparkd/cmds/Spartan.cpp
T
2020-11-20 12:16:50 -05:00

306 lines
11 KiB
C++

#include "Spartan.h"
#include "server/sparkd/cmds/spartan/algo/tas/RunTAS.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h"
#include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h"
#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h"
#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/IFeedController.h"
#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h"
#include "server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h"
#include "server/sparkd/cmds/spartan/md/mdp3/handler/IChannelObserver.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h"
#include "server/sparkd/cmds/spartan/util/PCapReader.h"
#include "lib/utils/PBUtils.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/algos/Sniper.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/Matcher.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/validation/iceberg_file_cache.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/matcher/validation/matcher_validation_observer.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/orchestrator/SimOrchestrator.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/orchestrator/SimSessionOptions.pb.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/simulator/SimInput.h"
#include "server/sparkd/cmds/spartan/md/mdp3/parsing/MDP3Parser.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/polygon_utils.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/DefinitionCollector.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/FillCounter.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/PolygonFinder.h"
#include "server/sparkd/cmds/spartan/md/mdp3/utils/queries/PolygonOpportunityFinder.h"
#include <Pcap++/PcapFileDevice.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fmt/format.h>
#include <fstream>
#include <iostream>
namespace bts {
namespace cmd {
using namespace spartan::mdp3;
auto drop_extensions = [](auto const &str) {
size_t lastindex = str.find_last_of(".");
return str.substr(0, lastindex);
};
int gen_sim_input(std::string const &pcap) {
auto input_proto = to_proto(make_sim_input_from_pcap(pcap));
auto out_path = drop_extensions(drop_extensions(pcap)) + ".sim";
std::ofstream f(out_path,
std::ios::out | std::ios::trunc | std::ios::binary);
if (!input_proto.SerializeToOstream(&f)) {
std::cerr << "Failed to serialize simulator input to " << out_path
<< std::endl;
return -1;
}
return 0;
}
int load_sim_input(std::string const &sim_input) {
std::ifstream f(sim_input, std::ios::binary);
spartan::protos::SimInput input_proto;
if (!input_proto.ParseFromIstream(&f)) {
std::cerr << "Failed to deserialize simulator input from " << sim_input
<< std::endl;
return -1;
} else {
auto sim_input = make_sim_input_from_proto(input_proto);
std::cout << "\nInstruments: " << sim_input.instruments.size()
<< "\nPolygons: " << sim_input.polygons.size()
<< "\nTransactions: " << sim_input.transactions.size()
<< std::endl;
return 0;
}
}
int sim(std::string const &input_file) {
spartan::protos::SimSessionOptions options;
std::ifstream proto_in(input_file);
std::string str((std::istreambuf_iterator<char>(proto_in)),
std::istreambuf_iterator<char>());
bts_assert(utils::pb::from_string(str, &options));
SimOrchestrator(options).run();
return 0;
}
void find_polys(std::vector<std::string> const &args) {
PolygonFinder::Options options;
if (args.size() > 2)
options.active_threshold_fills = std::stoi(args[2]);
if (args.size() > 3)
options.max_vertices = std::stoi(args[3]);
if (args.size() > 4)
options.max_securities = std::stoi(args[4]);
DefinitionCollector def_collector;
PolygonFinder poly_finder(options);
observe_channel(args[1], {&poly_finder, &def_collector});
for (size_t id = 1; id <= poly_finder.result.size(); id++)
std::cout << id << " -> "
<< polygon_descriptor(poly_finder.result[id],
def_collector.ptr_result)
<< std::endl;
}
void list_sec(std::string const &input_file) {
DefinitionCollector def;
FillCounter fill_counter;
observe_channel(input_file, {&def, &fill_counter});
auto fill_counts = fill_counter.result_map();
for (auto const &s : def.result) {
std::cout << s.second.asset() << "|" << s.second.symbol() << "|"
<< fill_counts[s.second.security_id()];
for (auto const &l : s.second.legs()) {
std::cout << "|";
if (def.ptr_result[l.security_id])
std::cout << def.ptr_result[l.security_id]->symbol();
else
std::cout << "?" << l.security_id;
}
std::cout << std::endl;
}
}
template <class T> inline int run(const std::string &pcap, T obs) {
observe_channel(pcap, obs);
return 0;
}
void value_polys(std::vector<std::string> const &args) {
DefinitionCollector def;
PolygonFinder poly_finder;
// first pass, just identify the polygons
observe_channel(args[1], {&poly_finder, &def});
// second pass, value the polygons
PolygonOpportunityFinder op_finder{poly_finder.result};
observe_channel(args[1], {&op_finder});
auto poly_v =
std::ofstream(drop_extensions(args[1]) + ".polygon_values.csv");
for (auto &v : op_finder.result)
poly_v << v << std::endl;
auto poly_op =
std::ofstream(drop_extensions(args[1]) + ".polygon_opportunities.csv");
spartan::mdp3::poly_opportunities_to_csv(aggregate(op_finder.result),
poly_finder.result, def.ptr_result,
poly_op);
}
template <class B> void print_book(std::ostream &books, B const &b) {
for (auto level : b) {
books << ",";
books << level.price.price() << "," << level.quantity.value() << ","
<< level.n_orders;
}
}
void sim_books(std::string const &sim_file) {
using namespace bts::spartan::mdp3;
auto input = make_sim_input_from_proto(sim_file);
auto output = std::ofstream{sim_file + ".books.csv"};
std::vector<MDP3SecurityID> sec_ids;
for (auto const &p : input.instruments)
sec_ids.push_back(p.first);
DirectMatcher matcher(sec_ids);
std::vector<DirectMatcher::MatchEffect> effects;
for (auto &rev : input.transactions) {
effects.clear();
matcher.match(DirectMatcher::SIMULATOR_INPUT, rev.order_changes,
&effects);
std::unordered_map<MDP3SecurityID, MBPUpdate> updates;
for (auto &ef : effects)
std::visit(
overloaded{[&](MBPUpdate &mbp) { updates[mbp.security_id] = mbp; },
[&](OrderUpdate const &) {}},
ef);
for (auto const &[id, mbp] : updates) {
output << rev.event_id << "," << id.value();
print_book(output, mbp.mbp_buy);
print_book(output, mbp.mbp_sell);
output << std::endl;
}
}
}
void stats(std::string const &pcap) {
std::cout << "MDP3order: " << sizeof(MDP3Order) << std::endl;
return;
auto out_path = drop_extensions(drop_extensions(pcap)) + ".order_counts.csv";
auto out_file = std::ofstream{out_path};
out_file << "sid,n_orders" << std::endl;
struct StatPrinter : IChannelObserver {
StatPrinter(std::ostream &out) : out{out} {}
std::ostream &out;
void on_real_time_event(MDP3Event const &ev) override {
for (auto s : ev.affected_securities) {
out << s->security_id().value() << "," << s->orders().size()
<< std::endl;
}
}
} stats{out_file};
observe_channel(pcap, stats);
}
std::map<std::string, std::function<int(std::vector<std::string> const &)>>
extensions = {
{"stats",
[](auto const &args) {
stats(args[1]);
return 0;
}},
{"value_polys",
[](auto const &args) {
value_polys(args);
return 0;
}},
{"sim",
[](auto const &args) {
sim(args[1]);
return 0;
}},
{"sim_books",
[](auto const &args) {
sim_books(args[1]);
return 0;
}},
{"list_sec",
[](auto const &args) {
list_sec(args[1]);
return 0;
}},
{"find_polys",
[](auto const &args) {
find_polys(args);
return 0;
}},
{"value_polys",
[](auto const &args) {
value_polys(args);
return 0;
}},
{"validate_fifo",
[](auto const &args) {
return run(args[1],
MatcherValidationObserver(
iceberg_file_cache::find_icebergs(args[1])));
}},
{"load_sim_input",
[](auto const &args) { return load_sim_input(args[1]); }},
{"gen_sim_input",
[](auto const &args) { return gen_sim_input(args[1]); }},
};
int Spartan::execute(std::vector<std::string> const &args) {
auto error = 1;
if (args.size() > 0) {
if (args[0] == "json" && args.size() >= 2) {
if (args.size() == 2)
error = spartan::mdp3::to_json(args[1]);
else if (args.size() == 4)
error = spartan::mdp3::to_json(args[1], std::atoi(args[2].c_str()),
std::atoi(args[3].c_str()));
} else if (args[0] == "compress" && args.size() == 3)
error = spartan::mdp3::compress(args[1], args[2]);
else if (args[0] == "csv" && args.size() == 2)
error = spartan::mdp3::to_csv(args[1]);
else if (args[0] == "sql" && args.size() == 2)
error = spartan::mdp3::to_sql(args[1]);
else if (extensions.count(args[0]) && args.size() >= 2) {
return extensions[args[0]](args);
}
}
if (error)
std::cout << help();
return error;
} // namespace cmd
std::string Spartan::help() {
auto str = fmt::format("\tjson <pcap>[.xz] [start_packet packet_count]\n"
"\tcompress <pcap>[.xz] <out-pcap>\n"
"\tsql <pcap>[.xz]\n"
"\tcsv <pcap>[.xz]\n");
for (auto const &p : extensions)
str += fmt::format("\t{} <pcap>[.xz] ...\n", p.first);
return str;
}
} // namespace cmd
} // namespace bts