#include "Spartan.h" #include "server/sparkd/cmds/spartan/md/common/InstrumentSnapshot.h" #include "server/sparkd/cmds/spartan/md/feed_control/AB_Arbitrageur.h" #include "server/sparkd/cmds/spartan/md/feed_control/IFeedController.h" #include "server/sparkd/cmds/spartan/md/feed_control/PickedFeed.h" #include "server/sparkd/cmds/spartan/md/handler/ChannelHandler.h" #include "server/sparkd/cmds/spartan/md/handler/IChannelObserver.h" #include "server/sparkd/cmds/spartan/md/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/back_testing/run/run_sim.h" #include "server/sparkd/cmds/spartan/md/channel_observers/DefinitionCollector.h" #include "server/sparkd/cmds/spartan/md/channel_observers/FillCounter.h" #include "server/sparkd/cmds/spartan/md/channel_observers/PolygonFinder.h" #include "server/sparkd/cmds/spartan/md/channel_observers/PolygonOpportunityFinder.h" #include "server/sparkd/cmds/spartan/md/parsing/MDP3Parser.h" #include "server/sparkd/cmds/spartan/md/utils/polygon_utils.h" #include "server/sparkd/cmds/spartan/md/utils/queries/BookStatRecorder.h" #include "server/sparkd/cmds/spartan/back_testing/matcher/validation/iceberg_file_cache.h" #include "server/sparkd/cmds/spartan/back_testing/matcher/validation/matcher_validation_observer.h" #include "server/sparkd/cmds/spartan/md/channel_observers/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 #include #include #include #include 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); }; inline std::string output_path( const std::string &input_path, const char *output_ext, const char *input_ext = "") { return bts::spartan::file::change_file_ext( input_path, output_ext, input_ext); } void find_polys(std::vector 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 inline int run(const std::string &pcap, T obs) { observe_channel(pcap, obs); return 0; } void value_polys(std::vector 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 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 &ibs, const std::string &out_csv) { const char *ok_col = "ok"; const char *eid_col = "eid"; const char *total_col = "total_qty"; const char *show_qty_col = "show_qty"; const char *fills_col = "fill_qty"; // validate args if (out_csv.empty()) return 1; // write icebergs to csv auto ofs = std::ofstream(out_csv); // write cols ofs << ok_col << "," << eid_col << "," << total_col << "," << show_qty_col << "," << fills_col; // write rows for (auto &p : ibs) { for (auto [eid, show_qty] : p.second.show_quantities()) { ofs << std::endl << p.first << "," << eid << "," << p.second.total_qty() << "," << show_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( 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 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; }}, {"book_stats", [](const auto &args) { auto out_path = args.size() > 2 ? args[2] : spartan::file::change_file_ext( args[1], "book_stats.csv", "pcap.xz"); std::ofstream out_csv(out_path); int res = run(args[1], BookStatRecorder(out_csv)); return res; }}, {"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 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 = IcebergFinder::find_all(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 [.xz] [start_packet packet_count]\n" "\tcompress [.xz] \n" "\tpolygon_books [.xz] [out-csv]\n" "\tsql [.xz]\n" "\tcsv [.xz]\n"); for (auto const &p : extensions) str += fmt::format("\t{} [.xz] ...\n", p.first); return str; } } // namespace cmd } // namespace bts