Files
spark/src/server/sparkd/cmds/Spartan.cpp
T

334 lines
12 KiB
C++

#include "Spartan.h"
#include "server/sparkd/cmds/spartan/algo/tas/RunTAS.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/jetfix/codec/f_toa.h"
#include "lib/orderman/orderman_utils/Formatter.h"
#include "lib/utils/PBUtils.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/run/run_sim.h"
#include "server/sparkd/cmds/spartan/md/mdp3/back_testing/orchestrator/SimSessionOptions.pb.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 "server/sparkd/cmds/spartan/md/mdp3/utils/queries/SyntheticBookRecorder.h"
#include "server/sparkd/cmds/spartan/util/args_parser.h"
#include "server/sparkd/cmds/spartan/util/file_stream_utils.h"
#include "server/sparkd/cmds/spartan/util/sql/adapters/polygon_defs.h"
#include "server/sparkd/cmds/spartan/util/sql/sql_utils.h"
#include <Pcap++/PcapFileDevice.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fmt/format.h>
#include <fstream>
#include <iostream>
namespace bts {
namespace cmd {
#define INFO(...) LOG(OrderMan, Info, __VA_ARGS__)
#define WARN(...) LOG(OrderMan, Warn, __VA_ARGS__)
#define ERROR(...) LOG(OrderMan, Error, __VA_ARGS__)
using namespace spartan::mdp3;
auto drop_extensions = [](auto const &str) {
size_t lastindex = str.find_last_of(".");
return str.substr(0, lastindex);
};
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,def.ptr_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) {
char buffer[128];
for (auto level : b) {
d_toa(level.price.price(), buffer, sizeof(buffer), 0);
books << "," << buffer << "," << level.quantity.value() << ","
<< level.n_orders;
}
}
int icebergs_to_csv(const std::unordered_map<MDP3OrderKey, IcebergInput>& ibs, const std::string& out_csv) {
const char* eid_col = "eid";
const char* ok_col = "ok";
const char* total_col = "total";
const char* show_qty_col = "show_qty";
const char* fills_col = "aggr_fills";
//const char* log_header = "IcebergsCSV";
// the nth leg col denotes the last event in which the nth leg's book changed
// validate args
if (out_csv.empty())
return 1;
// write icebergs to csv
auto ofs = std::ofstream(out_csv);
// write cols
ofs << eid_col << "," << ok_col << "," << show_qty_col << "," << total_col << "," << fills_col;
// write rows
for (auto& p : ibs) {
for (auto [eid, show_qty] : p.second.show_quantities()) {
ofs << std::endl
<< eid << "," << p.first << "," << show_qty << "," << p.second.total_qty()
<< "," << p.second.count_fills_by(eid);
}
}
ofs.flush();
return 0;
}
int polygon_books(const std::string& pcap, const std::string& db, const std::string& id_string, const std::string& out_csv) {
const char* eid_col = "eid";
const char* pid_col = "pid";
const char* log_header = "PolygonBookCSV";
// the nth leg col denotes the last event in which the nth leg's book changed
const int num_leg_cols = 10;
// validate args
if (out_csv.empty())
return 1;
auto ids = bts::cmd::args::parse_set<int>(id_string, [](const std::string& s) { return std::stoi(s); });
if (ids.empty())
return 1;
INFO("generating polygon books for pids: {}", orderman::Formatter::fmt_values(ids));
SyntheticBookRecorder sbr(spartan::sql::adapters::polygon_defs::read_sql(db.c_str(), ids));
observe_channel(pcap, sbr);
// don't prepend a comma before calling 'append_book' (it does that internally)
auto append_book = [](std::ofstream& out, const SmallBook& bk) -> std::ofstream& {
uint32_t i = 0;
bts_assert(bk.size() <= 10);
for (; i < bk.size(); i++)
out << "," << bk[i].price << "," << bk[i].quantity.value();
while (i++ < MDP3_MAX_BOOK_DEPTH)
out << ",NaN,0";
return out;
};
auto append_leg_book_eids = [&](std::ostream& out, const SyntheticMBPUpdate& upd) -> std::ostream& {
int lcount = 0;
for (const auto& p : upd.leg_book_eids) {
out << "," << p.second;
if (++lcount == num_leg_cols) {
WARN(
"{} processing book update for polygon with more than {} legs ({} "
"'leg-book-event-id' columns are accounted for in the csv, event "
"ids for susbequent legs will be discarded).",
*log_header, num_leg_cols, num_leg_cols);
break;
}
}
while (lcount++ < num_leg_cols)
out << ",0";
return out;
};
// write polygon books to csv
auto ofs = std::ofstream(out_csv);
// add cols
ofs << eid_col << "," << pid_col;
for (int i = 0; i < num_leg_cols; i++)
ofs << ",leg_" << i << "_eid";
auto add_bk_cols = [&](const char* side_prefix) {
for (int i = 0; i < 10; i++)
ofs << "," << side_prefix << "_p_" << i << "," << side_prefix << "_q_" << i;
};
add_bk_cols("bid");
add_bk_cols("ask");
for (const auto& p : sbr.result()) {
for (const auto& upd : p.second) {
ofs << std::endl;
ofs << p.first << "," << upd.synthetic_id.value();
append_leg_book_eids(ofs, upd);
append_book(ofs, upd.bids);
append_book(ofs, upd.asks);
}
}
ofs.flush();
return 0;
}
size_t total_orders = 0;
void stats(std::string const &pcap) {
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) {
total_orders += s->orders().size();
}
}
} stats{out_file};
observe_channel(pcap, stats);
std::cout << total_orders << std::endl;
}
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) {
run_sim(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) {
auto ibs = iceberg_file_cache::find_icebergs(args[1]);
return run(args[1], MatcherValidationObserver(ibs));
}},
};
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] == "icebergs_csv" && args.size() >= 2) {
auto out_csv = args.size() > 2 ? args[2]
: bts::spartan::file::change_file_ext(
args[1], "icebergs.csv", "pcap.xz");
auto ibs = iceberg_file_cache::find_icebergs(args[1]);
return icebergs_to_csv(ibs, out_csv);
} 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 (args[0] == "polygon_books" && args.size() >= 4) {
auto out_csv = args.size() > 4 ? args[4]
: bts::spartan::file::change_file_ext(
args[1], "polygon_books.csv", "pcap.xz");
error = polygon_books(args[1], args[2], args[3], out_csv);
}
else if (extensions.count(args[0]) && args.size() >= 2) {
return extensions[args[0]](args);
}
}
if (error)
std::cout << help();
return error;
}
std::string Spartan::help() {
auto str = fmt::format("\tjson <pcap>[.xz] [start_packet packet_count]\n"
"\tcompress <pcap>[.xz] <out-pcap>\n"
"\tpolygon_books <pcap>[.xz] <sqlite> <polygon_ids (delim ',')> [out-csv]\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