From 5c5bc243d2db445a5e2d0b0562be2f882edb9846 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Wed, 19 Aug 2020 16:29:49 -0400 Subject: [PATCH 1/5] Added new spartan command to clean up pcaps to just what we need. --- src/server/sparkd/cmds/QuickTest.cpp | 73 ++-- src/server/sparkd/cmds/Spartan.cpp | 29 +- .../cmds/spartan/analysis/RunAnalysis.cpp | 22 +- .../cmds/spartan/md/mdp3/common/mdp3_common.h | 7 + .../md/mdp3/feed_control/AB_Arbitrageur.h | 17 +- .../spartan/md/mdp3/feed_control/PickedFeed.h | 5 + .../md/mdp3/handler/ChannelHandler.cpp | 28 +- .../spartan/md/mdp3/handler/ChannelHandler.h | 22 +- .../spartan/md/mdp3/recovery/BookSnapshot.cpp | 2 +- .../md/mdp3/recovery/RecoveryHandler.cpp | 6 +- .../cmds/spartan/md/mdp3/utils/mdp3_utils.cpp | 314 ++++++++++++++---- .../cmds/spartan/md/mdp3/utils/mdp3_utils.h | 13 +- .../sparkd/cmds/spartan/util/PCapReader.cpp | 24 +- .../sparkd/cmds/spartan/util/PCapReader.h | 26 +- 14 files changed, 398 insertions(+), 190 deletions(-) create mode 100644 src/server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h diff --git a/src/server/sparkd/cmds/QuickTest.cpp b/src/server/sparkd/cmds/QuickTest.cpp index 29c2d103a..ca518c550 100644 --- a/src/server/sparkd/cmds/QuickTest.cpp +++ b/src/server/sparkd/cmds/QuickTest.cpp @@ -36,12 +36,9 @@ using namespace spartan; struct TimeWriter { mdp3::MDP3PacketView packet; void on_begin_packet(mdp3::MDP3PacketView const &p) { packet = p; } - void on_end_packet() { - std::cout << packet.sending_time() << std::endl; - } + void on_end_packet() { std::cout << packet.sending_time() << std::endl; } - template void operator()(M const &) { - } + template void operator()(M const &) {} }; void print_times(std::string const &file) { struct PacketBuffers { @@ -58,9 +55,9 @@ void print_times(std::string const &file) { if ((info.dst_ip == feed_map.incremental[0].ip && info.dst_port == feed_map.incremental[0].port)) { TimeWriter tw; - parse_packet(MDP3PacketView {payload},tw); + parse_packet(MDP3PacketView{payload}, tw); } - + return true; }; while (reader.read_next()) @@ -74,39 +71,55 @@ int QuickTest::execute(std::vector const &args) { log::configure_logging(cfg); auto file = args[0]; - print_times(file); - return 0; - using namespace bts::spartan::mdp3; struct Obs : IChannelObserver { + + Orders previous_orders; + size_t event_id = 0; + void on_recovery_complete( std::vector const &secs) override { - - for (auto s : secs) { - std::cout << "Bootstrap -----------------------------------------" - "------------------------------" - << std::endl; - std::cout << "Symbol: " << s->definition().symbol() << std::endl - << "Status: " << s->trading_status() << std::endl - << "Orders:\n" - << s->orders(); - } + previous_orders.clear(); + + for (auto s : secs) + for (auto const &o : s->orders()) + previous_orders[o.first] = o.second; } void on_real_time_event(MDP3Event const &ev) override { + event_id++; for (auto s : ev.affected_securities) { - if (s->order_changes().size() || s->fills().size()) { - std::cout << "Event " << ev.transact_time - << " -----------------------------" << std::endl; - std::cout << "Symbol: " << s->definition().symbol() << std::endl - << "Status: " << s->trading_status() << std::endl - << "Seq Num: " << ev.first_packet_sn << " to " - << ev.last_packet_sn << std::endl - << "Orders:\n" - << s->order_changes() << "Fills:\n" - << s->fills(); + if (s->trading_status() == + ::mdp3::SecurityTradingStatus::ReadyToTrade) { + for (auto f : s->fills()) { + if (f.aggressor != MDP3Fill::THIS_BUY && + f.aggressor != MDP3Fill::THIS_SELL) { + auto it = previous_orders.find(f.key); + bts_assert(it != previous_orders.end()); + it->second.quantity.value() -= f.quantity.value(); + if (it->second.quantity.value() < 0) { + std::cout << " Hidden sizes in order. " + << " eid: " << event_id + << " Event: " << ev + << " Order: " << it->first + << " Fill tid: " << f.trade_entry_id + << std::endl; + } + } + } + } + for (auto const &ch : s->order_changes()) { + switch (ch.change) { + case OrderChange::added: + case OrderChange::updated: + previous_orders[ch.order.key] = ch.order; + break; + case OrderChange::removed: + previous_orders.erase(ch.order.key); + break; + } } } } diff --git a/src/server/sparkd/cmds/Spartan.cpp b/src/server/sparkd/cmds/Spartan.cpp index 2889c2d1f..d151a2078 100644 --- a/src/server/sparkd/cmds/Spartan.cpp +++ b/src/server/sparkd/cmds/Spartan.cpp @@ -2,15 +2,26 @@ #include "server/sparkd/cmds/spartan/algo/RunTAS.h" #include "server/sparkd/cmds/spartan/analysis/RunAnalysis.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h" +#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/IFeedController.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 "server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h" +#include "server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h" +#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h" #include #include #include +#include namespace bts { namespace cmd { +int slim_pcap(std::string const &file, std::string const &out_dir) { + return !spartan::mdp3::slim_down_pcap(file, out_dir); +} + int export_tables(std::string const &file, std::string const &out_dir) { using namespace bts::spartan::mdp3; @@ -25,15 +36,12 @@ int export_tables(std::string const &file, std::string const &out_dir) { "first_st,last_st" << std::endl; - event_items - << "eid, t_time,sid,status,type," - "change,ok,side," - "pri,price,qty,tid,agg" - << std::endl; + event_items << "eid, t_time,sid,status,type," + "change,ok,side," + "pri,price,qty,tid,agg" + << std::endl; - securities - << "sid,symbol,group,asset,last_t" - << std::endl; + securities << "sid,symbol,group,asset,last_t" << std::endl; } std::ofstream events; @@ -155,8 +163,6 @@ int export_tables(std::string const &file, std::string const &out_dir) { << std::endl; - if (s->security_id().value() == 12181 && event_id == 1065) - std::cout << "There is" << std::endl; auto deduced_order = s->deduced_order_change(); if (deduced_order) { event_items << event_id << "," @@ -211,6 +217,8 @@ int Spartan::execute(std::vector const &args) { error = spartan::convert_pcap_to_json(args); else if (args[0] == "pcap_to_tables") error = export_tables(args[1], args[2]); + else if (args[0] == "slim_pcap") + error = slim_pcap(args[1],args[2]); } if (error) std::cout << help(); @@ -220,6 +228,7 @@ int Spartan::execute(std::vector const &args) { std::string Spartan::help() { return fmt::format("\tpcap_to_msgs pcap_file\n" "\tpcap_to_json pcap_file\n" + "\tslim_pcap in_pcap out_pcap\n" "\tpcap_to_tables pcap_file output_dir\n"); } diff --git a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp index ac6993f82..200dce8ad 100644 --- a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp +++ b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp @@ -25,24 +25,6 @@ struct PacketBuffers { mdp3::AB_Arbitrageur ab; -void cme_ts_to_str(uint64_t cme_ts, std::stringstream *out) { - auto one_billion = 1000000000; - time_t unix_ts = cme_ts / one_billion; - auto boost_ts = boost::posix_time::from_time_t(unix_ts); - auto year = boost_ts.date().year(); - auto month = boost_ts.date().month().as_number(); - auto day = boost_ts.date().day().as_number(); - int hours = boost_ts.time_of_day().hours(); - int minutes = boost_ts.time_of_day().minutes(); - int seconds = boost_ts.time_of_day().seconds(); - *out << year << "-" << std::setw(2) << std::setfill('0') << month << "-" - << std::setw(2) << std::setw(2) << std::setfill('0') << day << "." - << std::setw(2) << std::setw(2) << std::setfill('0') << hours << ":" - << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) - << std::setfill('0') << seconds << "." << std::setw(9) - << cme_ts - (unix_ts * one_billion); -} - struct JSON_Writer { std::stringstream json_buffer; @@ -112,10 +94,10 @@ struct CSVPrinter { template void print(M &m) { stime_buffer.str(""); stime_buffer.clear(); - cme_ts_to_str(packet.sending_time(), &stime_buffer); + mdp3::cme_ts_to_date_str(packet.sending_time(), &stime_buffer); ttime_buffer.str(""); ttime_buffer.clear(); - cme_ts_to_str(get_transact_time(m), &ttime_buffer); + mdp3::cme_ts_to_date_str(get_transact_time(m), &ttime_buffer); auto t = get_transact_time(m); std::cout << ttime_buffer.str() << "," << stime_buffer.str() << "," diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h b/src/server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h index 2a36532ca..9eec981af 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h @@ -35,6 +35,13 @@ class MDP3Event { } }; +inline std::ostream &operator<<(std::ostream &s, MDP3Event const &ev) { + s << " transact_time: " << ev.transact_time.value() + << " packets: " << ev.first_packet_sn + << " to " << ev.last_packet_sn; + return s; +} + using MDP3Quantity = utils::ValueWrapper; using MDP3OrderPriority = utils::ValueWrapper; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h b/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h index 2db7cd0bd..846d40720 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h @@ -1,5 +1,7 @@ #pragma once #include "../parsing/MDP3Parser.h" +#include "../feed_control/PickedFeed.h" + #include "lib/utils/bts_assert.h" namespace bts::spartan::mdp3 { @@ -17,6 +19,7 @@ class AB_Arbitrageur { struct Action { ActionCode action; + PickedFeed picked; MDP3PacketView const packet; }; @@ -28,13 +31,13 @@ class AB_Arbitrageur { auto action_a = try_one(a); if (action_a == ActionCode::APPLY) { _last_seqn = a.seq_num(); - return {action_a, a}; + return {action_a, PickedFeed::A, a}; } auto action_b = try_one(b); if (action_b == ActionCode::APPLY) { _last_seqn = b.seq_num(); - return {action_b, b}; + return {action_b, PickedFeed::B, b}; } // the first packet defines our starting sequence number, rather @@ -43,17 +46,17 @@ class AB_Arbitrageur { if (_last_seqn == 0) { if (!a.empty()) { _last_seqn = a.seq_num(); - return {ActionCode::APPLY, a}; + return {ActionCode::APPLY, PickedFeed::A, a}; } else { _last_seqn = a.seq_num(); - return {ActionCode::APPLY, a}; + return {ActionCode::APPLY, PickedFeed::A,a}; } } // Both feeds are either ahead or behind, if they are ahead we // return RECOVER, otherwise we return IGNORE. if (action_a == action_b) - return {action_a, a}; + return {action_a, PickedFeed::None, a}; // One of the feeds is ahead of us and the other is behind. Its // possible that we will recover eventually, that is the feed @@ -69,9 +72,9 @@ class AB_Arbitrageur { how_far_ahead = b.seq_num() - _last_seqn; if (how_far_ahead > 10) - return {ActionCode::RECOVER, a}; + return {ActionCode::RECOVER, PickedFeed::None, a}; else - return {ActionCode::IGNORE, a}; + return {ActionCode::IGNORE, PickedFeed::None, a}; } private: diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h b/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h new file mode 100644 index 000000000..2b89490ce --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h @@ -0,0 +1,5 @@ +#pragma once + +namespace bts::spartan { +enum class PickedFeed { A, B, None }; +} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.cpp index 0f973f3d2..ff01e9c35 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.cpp @@ -50,7 +50,7 @@ ChannelHandler::~ChannelHandler() {} void ChannelHandler::on_instrument_feed(MDP3PacketView const &pv) { switch (me->state) { case State::RECOVERY: { - RecoveryGuard g {*this}; + RecoveryGuard g{*this}; parse_packet(pv, me->recovery_handler.on_instrument_feed); break; } @@ -62,7 +62,7 @@ void ChannelHandler::on_instrument_feed(MDP3PacketView const &pv) { void ChannelHandler::on_snapshot_feed(MDP3PacketView const &pv) { switch (me->state) { case State::RECOVERY: { - RecoveryGuard g {*this}; + RecoveryGuard g{*this}; parse_packet(pv, me->recovery_handler.on_snapshot_feed); break; } @@ -71,16 +71,16 @@ void ChannelHandler::on_snapshot_feed(MDP3PacketView const &pv) { } } -void ChannelHandler::on_incremental_feed(MDP3PacketView const &a, - MDP3PacketView const &b) { +PickedFeed ChannelHandler::on_incremental_feed(MDP3PacketView const &a, + MDP3PacketView const &b) { + auto action = me->real_time_ab(a, b); + switch (me->state) { case State::RECOVERY: { - auto action = me->real_time_ab(a, b); switch (action.action) { case AB_Arbitrageur::APPLY: { - RecoveryGuard g {*this}; + RecoveryGuard g{*this}; parse_packet(action.packet, me->recovery_handler.on_incremental_feed); - break; } case AB_Arbitrageur::IGNORE: break; @@ -91,7 +91,6 @@ void ChannelHandler::on_incremental_feed(MDP3PacketView const &a, break; } case State::REALTIME: { - auto action = me->real_time_ab(a, b); switch (action.action) { case AB_Arbitrageur::APPLY: parse_packet(action.packet, me->real_time_handler); @@ -105,15 +104,21 @@ void ChannelHandler::on_incremental_feed(MDP3PacketView const &a, break; } } + + return action.picked; } void ChannelHandler::start_recovery() { switch (me->state) { case State::RECOVERY: + LOG(Spartan, Warn, "Restarting channel recovery."); me->real_time_ab = {}; me->recovery_handler.reset(); break; case State::REALTIME: + LOG(Spartan, Warn, + "Loss detected. Shutting down real-time handling and switching to " + "recovery feeds."); me->real_time_ab = {}; me->real_time_handler.reset(); me->feed_controller.start_instrument_feed(); @@ -128,15 +133,18 @@ void ChannelHandler::try_start_real_time() { bts_assert(me->state == State::RECOVERY); auto maybe_snaps = me->recovery_handler.try_build_snapshot_and_reset(); if (maybe_snaps) { + LOG(Spartan, Warn, "Recovery complete. Starting real time feed"); me->state = State::REALTIME; std::vector snap_ptrs; for (auto &p : maybe_snaps.value()) snap_ptrs.push_back(p.get()); me->real_time_handler.add_snapshots(maybe_snaps.value()); + me->feed_controller.stop_instrument_feed(); + me->feed_controller.stop_snapshot_feed(); me->observer.on_recovery_complete(snap_ptrs); for (auto s : snap_ptrs) { - const_cast(s)->clear_fills(); - const_cast(s)->clear_order_changes(); + const_cast(s)->clear_fills(); + const_cast(s)->clear_order_changes(); } } } diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h b/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h index 31d2d8e75..6b3ce5977 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h @@ -1,8 +1,10 @@ #pragma once -#include #include -#include "server/sparkd/cmds/spartan/md/mdp3/parsing/MDP3Parser.h" +#include + +#include "../feed_control/PickedFeed.h" +#include "../parsing/MDP3Parser.h" namespace bts::spartan::mdp3 { @@ -11,15 +13,16 @@ class IFeedController; class MDP3PacketView; class ChannelHandler { -public: - ChannelHandler(IChannelObserver&, IFeedController &); + public: + ChannelHandler(IChannelObserver &, IFeedController &); ~ChannelHandler(); - void on_instrument_feed(MDP3PacketView const&); - void on_snapshot_feed(MDP3PacketView const&); - void on_incremental_feed(MDP3PacketView const&a, MDP3PacketView const&b = {} ); + void on_instrument_feed(MDP3PacketView const &); + void on_snapshot_feed(MDP3PacketView const &); + PickedFeed on_incremental_feed(MDP3PacketView const &a, + MDP3PacketView const &b = {}); -private: + private: struct RecoveryGuard; void start_recovery(); void try_start_real_time(); @@ -28,5 +31,4 @@ private: std::unique_ptr me; }; -} - +} // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp index ced51c39b..2b0b59ce6 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp @@ -56,7 +56,7 @@ void BookSnapshot::operator()(::mdp3::SnapshotFullRefresh52 &book) { me->newest_snapshot_sn = std::max(book.lastMsgSeqNumProcessed(), me->newest_snapshot_sn); me->books.emplace_back(ib); - LOG(Spartan, Info, "Recovered book {}/{} from snapshot feed", + LOG(Spartan, Diag, "Recovered book {}/{} from snapshot feed", me->books.size(), book.totNumReports()); check_completion(); break; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp index a24ec9c51..5ddfad55d 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp @@ -165,7 +165,7 @@ RecoveryHandler::MaybeSnapshot RecoveryHandler::try_build_snapshot_and_reset() { auto &this_snapshot = *current_snapshot; if (this_snapshot.last_processed_sn == 0 || this_snapshot.last_processed_sn + 1 == pv.seq_num()) { - LOG(Spartan, Info, + LOG(Spartan, Diag, "Added snapshot with last update time {} for security {} with " "last processed sn {}", this_snapshot.snapshot->definition().last_update_time().value(), @@ -178,7 +178,7 @@ RecoveryHandler::MaybeSnapshot RecoveryHandler::try_build_snapshot_and_reset() { // Now parse the next packet - LOG(Spartan, Info, "Appplying queued packet with sequence number {}", + LOG(Spartan, Diag, "Appplying queued packet with sequence number {}", pv.seq_num()); parse_packet(pv, rt_handler); last_applied_packet = pv.seq_num(); @@ -187,7 +187,7 @@ RecoveryHandler::MaybeSnapshot RecoveryHandler::try_build_snapshot_and_reset() { for (; current_snapshot != sortable_snapshots.end(); current_snapshot++) { auto &this_snapshot = *current_snapshot; bts_assert(this_snapshot.last_processed_sn == last_applied_packet); - LOG(Spartan, Info, + LOG(Spartan, Diag, "Added snapshot with last update time {} for security {} with " "last processed sn {}", this_snapshot.snapshot->definition().last_update_time().value(), diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp index 4c47763ac..cd0e14eaa 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp @@ -1,96 +1,272 @@ #include "mdp3_utils.h" +#include "../../../util/PCapReader.h" +#include "../common/InstrumentSnapshot.h" +#include "../feed_control/AB_Arbitrageur.h" +#include "../feed_control/IFeedController.h" #include "../gen/MDIncrementalRefreshOrderBook47.h" #include "../gen/MDInstrumentDefinitionFuture54.h" #include "../gen/MDInstrumentDefinitionOption55.h" #include "../gen/MDInstrumentDefinitionSpread56.h" #include "../gen/SnapshotFullRefreshOrderBook53.h" +#include "../handler/ChannelHandler.h" +#include "../handler/IChannelObserver.h" #include "../parsing/MDP3Parser.h" -#include "server/sparkd/cmds/spartan/util/PCapReader.h" +#include "lib/utils/bts_chrono.h" #include "lib/utils/overloaded.h" +#include +#include +#include +#include +#include +#include + namespace bts::spartan::mdp3 { +struct Guesser { + FeedMap result; + PCapReader::PacketInfo current_packet; + + void on_begin_packet(MDP3PacketView const &) {} + void on_end_packet() {} + + void set_current_source(const PCapReader::PacketInfo &info) { + current_packet = info; + } + + template void operator()(M const &) { + if (result.incremental[0].port == 0) { + result.incremental[0].port = current_packet.dst_port; + result.incremental[0].ip = current_packet.dst_ip; + return; + } + if (result.incremental[0].port == current_packet.dst_port && + result.incremental[0].ip == current_packet.dst_ip) + return; + + if (result.incremental[1].port == 0) { + result.incremental[1].port = current_packet.dst_port; + result.incremental[1].ip = current_packet.dst_ip; + } + } + + void operator()(::mdp3::SnapshotFullRefresh52 const &) { + if (result.snapshot.port == 0) { + result.snapshot.port = current_packet.dst_port; + result.snapshot.ip = current_packet.dst_ip; + } + } + + void operator()(::mdp3::SnapshotFullRefreshOrderBook53 const &) { + if (result.snapshot.port == 0) { + result.snapshot.port = current_packet.dst_port; + result.snapshot.ip = current_packet.dst_ip; + } + } + + void operator()(::mdp3::MDInstrumentDefinitionFuture54 const &) { + on_definition(); + } + + void operator()(::mdp3::MDInstrumentDefinitionOption55 const &) { + on_definition(); + } + + void operator()(::mdp3::MDInstrumentDefinitionSpread56 const &) { + on_definition(); + } + + void on_definition() { + if (result.instrument.port) + return; + if (result.incremental[0].port == 0) + return; + if (result.incremental[1].port == 0) + return; + if (result.incremental[0].ip == current_packet.dst_ip && + result.incremental[0].port == current_packet.dst_port) + return; + if (result.incremental[1].ip == current_packet.dst_ip && + result.incremental[1].port == current_packet.dst_port) + return; + result.instrument.port = current_packet.dst_port; + result.instrument.ip = current_packet.dst_ip; + } +}; + FeedMap guess_feed_map(std::string const &pcap_path) { - - struct Guesser { - FeedMap result; - PCapReader::PacketInfo current_packet; - - void on_begin_packet(MDP3PacketView const&) {} - void on_end_packet() {} - - void set_current_source(const PCapReader::PacketInfo &info) { - current_packet = info; - } - - void operator()(::mdp3::MDIncrementalRefreshOrderBook47 const &) { - if (result.incremental[0].port == 0) { - result.incremental[0].port = current_packet.dst_port; - result.incremental[0].ip = current_packet.dst_ip; - return; - } - if (result.incremental[0].port == current_packet.dst_port && - result.incremental[0].ip == current_packet.dst_ip) - return; - - if (result.incremental[1].port == 0) { - result.incremental[1].port = current_packet.dst_port; - result.incremental[1].ip = current_packet.dst_ip; - } - } - - void operator()(::mdp3::SnapshotFullRefreshOrderBook53 const &) { - if (result.snapshot.port == 0) { - result.snapshot.port = current_packet.dst_port; - result.snapshot.ip = current_packet.dst_ip; - } - } - - void operator()(::mdp3::MDInstrumentDefinitionFuture54 const &) { - on_definition(); - } - - void operator()(::mdp3::MDInstrumentDefinitionOption55 const &) { - on_definition(); - } - - void operator()(::mdp3::MDInstrumentDefinitionSpread56 const &) { - on_definition(); - } - - void on_definition() { - if (result.instrument.port) - return; - if (result.incremental[0].port == 0) - return; - if (result.incremental[1].port == 0) - return; - if (result.incremental[0].ip == current_packet.dst_ip && - result.incremental[0].port == current_packet.dst_port) - return; - if (result.incremental[1].ip == current_packet.dst_ip && - result.incremental[1].port == current_packet.dst_port) - return; - result.instrument.port = current_packet.dst_port; - result.instrument.ip = current_packet.dst_ip; - } - } guesser; - + Guesser guesser; auto reader = PCapReader{pcap_path}; reader.on_packet() = [&](auto const &info, auto const &payload) { guesser.set_current_source(info); - parse_packet(MDP3PacketView {payload},guesser); - if (guesser.result) + parse_packet(MDP3PacketView{payload}, guesser); + if (guesser.result) return false; else return true; }; - + while (reader.read_next()) ; return guesser.result; } +std::ostream &operator<<(std::ostream &o, FeedMap const &fm) { + o << "IA:" << fm.incremental[0].ip << ":" << fm.incremental[0].port + << " IB:" << fm.incremental[1].ip << ":" << fm.incremental[1].port + << " N:" << fm.instrument.ip << ":" << fm.instrument.port + << " SMBO:" << fm.snapshot.ip << ":" << fm.snapshot.port; + return o; +} + +bool slim_down_pcap(std::string const &file, std::string const &out_file) { + using namespace bts::spartan; + using namespace bts::spartan::mdp3; + + struct Ctrl : IFeedController { + bool instrument_feed = false; + bool snapshot_feed = false; + bool incremental_feed = false; + + void start_instrument_feed() override { instrument_feed = true; } + void stop_instrument_feed() override { instrument_feed = false; } + void start_snapshot_feed() override { snapshot_feed = true; } + void stop_snapshot_feed() override { snapshot_feed = false; } + void start_incremental_feed() override { incremental_feed = true; } + void stop_incremental_feed() override { incremental_feed = false; } + } ctrl; + + struct Obs : IChannelObserver { + bool observed_loss = false; + bool recovery_complete = false; + + size_t previous_packet = 0; + size_t previous_send_ts = 0; + TimeStamp last_print; + + void on_recovery_complete( + std::vector const &) override { + recovery_complete = true; + } + + void on_real_time_event(MDP3Event const &ev) override { + if (ms_diff(Timer::now(), last_print) >= 1000) { + last_print = Timer::now(); + std::stringstream str; + cme_ts_to_time_str(ev.transact_time.value(), &str); + LOG(Spartan, Info, + "Time: {} -> {} pkt/sec at {}x real time", + str.str(), + (ev.first_packet_sn - previous_packet), + (ev.first_packet_send_time.value() - previous_send_ts) / 1000000000); + previous_packet = ev.first_packet_sn; + previous_send_ts = ev.first_packet_send_time.value(); + } + } + void on_real_time_channel_loss() override { observed_loss = true; } + } obs; + + struct IncrementalFeedBuffer { + bool written_once = false; + pcpp::RawPacket rp; + mdp3::MDP3Packet p; + }; + std::array inc_buffer; + + auto feed_map = mdp3::guess_feed_map(file); + bts_assert(feed_map); + auto reader = PCapReader{file}; + + mdp3::AB_Arbitrageur ab; + mdp3::ChannelHandler handler(obs, ctrl); + + pcpp::PcapNgFileWriterDevice writer(out_file.c_str()); + writer.open(); + reader.on_packet() = [&](auto const &info, auto const &payload) { + if ((info.dst_ip == feed_map.incremental[0].ip && + info.dst_port == feed_map.incremental[0].port)) { + inc_buffer[0].rp = *info.rp; + inc_buffer[0].p.set_bytes(payload); + } else if ((info.dst_ip == feed_map.incremental[1].ip && + info.dst_port == feed_map.incremental[1].port)) { + inc_buffer[1].rp = *info.rp; + inc_buffer[1].p.set_bytes(payload); + } else if (info.dst_ip == feed_map.instrument.ip && + info.dst_port == feed_map.instrument.port) { + if (ctrl.instrument_feed) { + handler.on_instrument_feed(mdp3::MDP3PacketView{payload}); + writer.writePacket(*info.rp); + } + return true; + } else if (info.dst_ip == feed_map.snapshot.ip && + info.dst_port == feed_map.snapshot.port) { + if (ctrl.snapshot_feed) { + handler.on_snapshot_feed(mdp3::MDP3PacketView{payload}); + writer.writePacket(*info.rp); + } + return true; + } else + return true; + + // Incremental feed handling + auto picked = handler.on_incremental_feed(inc_buffer[0].p.view(), + inc_buffer[1].p.view()); + if (picked == PickedFeed::A || + ((!inc_buffer[0].written_once || !obs.recovery_complete) && + !inc_buffer[0].p.view().empty())) { + inc_buffer[0].written_once = true; + writer.writePacket(inc_buffer[0].rp); + } + + if (picked == PickedFeed::B || + ((!inc_buffer[1].written_once || !obs.recovery_complete) && + !inc_buffer[1].p.view().empty())) { + inc_buffer[1].written_once = true; + writer.writePacket(inc_buffer[1].rp); + } + + return true; + }; + + while (reader.read_next()) + if (obs.observed_loss) { + LOG(Spartan, Error, "Observed loss in {}. Cannot slim it down", file); + return false; + }; + return true; +} + +void cme_ts_to_time_str(uint64_t cme_ts, std::stringstream *out) { + auto one_billion = 1000000000; + time_t unix_ts = cme_ts / one_billion; + auto boost_ts = boost::posix_time::from_time_t(unix_ts); + int hours = boost_ts.time_of_day().hours(); + int minutes = boost_ts.time_of_day().minutes(); + int seconds = boost_ts.time_of_day().seconds(); + *out << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) + << std::setfill('0') << minutes << ":" << std::setw(2) + << std::setfill('0') << seconds << "." << std::setw(9) + << cme_ts - (unix_ts * one_billion); +} + +void cme_ts_to_date_str(uint64_t cme_ts, std::stringstream *out) { + auto one_billion = 1000000000; + time_t unix_ts = cme_ts / one_billion; + auto boost_ts = boost::posix_time::from_time_t(unix_ts); + auto year = boost_ts.date().year(); + auto month = boost_ts.date().month().as_number(); + auto day = boost_ts.date().day().as_number(); + int hours = boost_ts.time_of_day().hours(); + int minutes = boost_ts.time_of_day().minutes(); + int seconds = boost_ts.time_of_day().seconds(); + *out << year << "-" << std::setw(2) << std::setfill('0') << month << "-" + << std::setw(2) << std::setw(2) << std::setfill('0') << day << "." + << std::setw(2) << std::setw(2) << std::setfill('0') << hours << ":" + << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) + << std::setfill('0') << seconds << "." << std::setw(9) + << cme_ts - (unix_ts * one_billion); +} + } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h index 4ba99175e..3888a81ca 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h @@ -23,15 +23,12 @@ struct FeedMap { snapshot.port; } }; - -inline std::ostream &operator<<(std::ostream &o, FeedMap const &fm) { - o << "IA:" << fm.incremental[0].ip << ":" << fm.incremental[0].port - << " IB:" << fm.incremental[1].ip << ":" << fm.incremental[1].port - << " N:" << fm.instrument.ip << ":" << fm.instrument.port - << " SMBO:" << fm.snapshot.ip << ":" << fm.snapshot.port; - return o; -} +std::ostream &operator<<(std::ostream &o, FeedMap const &fm); FeedMap guess_feed_map(std::string const &pcap_path); +bool slim_down_pcap(std::string const&in, std::string const &out); +void cme_ts_to_date_str(uint64_t cme_ts, std::stringstream *out); +void cme_ts_to_time_str(uint64_t cme_ts, std::stringstream *out); + } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/util/PCapReader.cpp b/src/server/sparkd/cmds/spartan/util/PCapReader.cpp index 2fea3af3c..a9bd43d76 100644 --- a/src/server/sparkd/cmds/spartan/util/PCapReader.cpp +++ b/src/server/sparkd/cmds/spartan/util/PCapReader.cpp @@ -1,11 +1,11 @@ #include "PCapReader.h" #include "lib/utils/bts_assert.h" -#include -#include -#include #include +#include #include +#include +#include #include namespace bts { @@ -14,10 +14,10 @@ namespace spartan { struct PCapReader::PImpl { PImpl(std::string const &file_path) : reader(pcpp::IFileReaderDevice::getReader(file_path.c_str())), - on_packet([](auto const&, auto const &) {return true;}) {} + on_packet([](auto const &, auto const &) { return true; }) {} std::unique_ptr reader; - std::function on_packet; + OnPacket on_packet; pcpp::RawPacket rawPacket; }; @@ -31,19 +31,18 @@ PCapReader::PCapReader(std::string const &file_path, std::string const &filter) PCapReader::~PCapReader() {} -std::function &PCapReader::on_packet() { - return me->on_packet; -} +PCapReader::OnPacket &PCapReader::on_packet() { return me->on_packet; } bool PCapReader::read_next() { if (me->reader->getNextPacket(me->rawPacket)) { pcpp::Packet parsedPacket(&me->rawPacket); PacketInfo info; - + info.rp = &me->rawPacket; + auto udp = parsedPacket.getLayerOfType(); if (udp) info.dst_port = udp->getUdpHeader()->portDst; - else { + else { auto tcp = parsedPacket.getLayerOfType(); info.dst_port = tcp->getTcpHeader()->portDst; } @@ -52,12 +51,13 @@ bool PCapReader::read_next() { info.dst_ip = ip->getDstIpAddress().toString(); auto payload = parsedPacket.getLayerOfType(pcpp::GenericPayload); if (payload) - return me->on_packet(info, {(const char *)payload->getData(), payload->getDataLen()}); + return me->on_packet( + info, {(const char *)payload->getData(), payload->getDataLen()}); else return true; } else return false; } -} // namespace utils +} // namespace spartan } // namespace bts diff --git a/src/server/sparkd/cmds/spartan/util/PCapReader.h b/src/server/sparkd/cmds/spartan/util/PCapReader.h index 7cbf04948..9fe6835fb 100644 --- a/src/server/sparkd/cmds/spartan/util/PCapReader.h +++ b/src/server/sparkd/cmds/spartan/util/PCapReader.h @@ -1,26 +1,32 @@ #pragma once -#include #include +#include +namespace pcpp { +class RawPacket; +} -namespace bts { -namespace spartan { - +namespace bts::spartan { class PCapReader { -public: - PCapReader(std::string const&file_path, - std::string const&filter = ""); + public: + PCapReader(std::string const &file_path, std::string const &filter = ""); ~PCapReader(); bool read_next(); + struct PacketInfo { std::string dst_ip; int dst_port; + pcpp::RawPacket *rp; }; - std::function &on_packet(); -private: + + using OnPacket = + std::function; + OnPacket &on_packet(); + + private: struct PImpl; std::unique_ptr me; }; -}} +} // namespace bts::spartan From 025625e0b94588a5311bfc44863232a8b85f0968 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Wed, 19 Aug 2020 21:15:40 -0400 Subject: [PATCH 2/5] Simplified console logging --- src/lib/logging/Sink.cpp | 111 ++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 61 deletions(-) diff --git a/src/lib/logging/Sink.cpp b/src/lib/logging/Sink.cpp index 1e81344a0..826e7cdc0 100644 --- a/src/lib/logging/Sink.cpp +++ b/src/lib/logging/Sink.cpp @@ -2,85 +2,79 @@ #include "lib/logging/logging.h" #include "lib/os/os.h" +#include "lib/utils/bts_assert.h" #include "lib/utils/datetime.h" #include "lib/utils/file_utils.h" -#include "lib/utils/bts_assert.h" +#include +#include +#include #include #include #include -#include -#include -#include #ifndef WIN32 #include #endif - namespace bts { namespace log { - struct InitSysLog { InitSysLog() { #ifndef WIN32 - openlog("spark",0,LOG_USER); + openlog("spark", 0, LOG_USER); #endif - } -} init; +} init; - -auto formatter(LoggingConfig const&cfg) { - return [cfg] (LogMsg const&m) { +auto formatter(LoggingConfig const &cfg) { + return [cfg](LogMsg const &m) { auto iso_date = datetime::iso_date_time_string(datetime::local_now()); - iso_date[sizeof("YYYY-MM-DD")-1] = ' '; + iso_date[sizeof("YYYY-MM-DD") - 1] = ' '; #ifdef _WIN32 - return fmt::format("{}|{}|{:<8}|{:<5}|{:<3}|{:<4}|{:<35}|{}|{} ", - iso_date, - m.ts, - m.subsystem_name, - m.level_name, - m.tid, - //m.thread_name, - os::process_id(), - fmt::format("{}:{}",boost::filesystem::path(m.file).filename().string() , m.line), - cfg.deployment_type, - m.msg); + return fmt::format( + "{}|{}|{:<8}|{:<5}|{:<3}|{:<4}|{:<35}|{}|{} ", iso_date, m.ts, + m.subsystem_name, m.level_name, m.tid, + // m.thread_name, + os::process_id(), + fmt::format("{}:{}", + boost::filesystem::path(m.file).filename().string(), + m.line), + cfg.deployment_type, m.msg); #else - return fmt::format("{}|{}|{:<8}|{:<5}|{:<3}|{:<16}|{:<4}|{:<35}|{}|{} ", - iso_date, - m.ts, - m.subsystem_name, - m.level_name, - m.tid, - m.thread_name, - os::process_id(), - fmt::format("{}:{}",boost::filesystem::path(m.file).filename().string() , m.line), - cfg.deployment_type, - m.msg); + return fmt::format( + "{}|{}|{:<8}|{:<5}|{:<3}|{:<16}|{:<4}|{:<35}|{}|{} ", iso_date, m.ts, + m.subsystem_name, m.level_name, m.tid, m.thread_name, + os::process_id(), + fmt::format("{}:{}", + boost::filesystem::path(m.file).filename().string(), + m.line), + cfg.deployment_type, m.msg); #endif }; } -Sink console_sink(LoggingConfig const&cfg) { - auto f = formatter(cfg); - return [f] (LogMsg const &m) {std::cout << f(m) << std::endl;}; +Sink console_sink(LoggingConfig const &) { + return [](LogMsg const &m) { + std::cout << fmt::format("{:<8} | {}", m.subsystem_name, m.msg) + << std::endl; + }; } -Sink syslog_sink(LoggingConfig const&cfg) { +Sink syslog_sink(LoggingConfig const &cfg) { #ifdef WIN32 return null_sink(); #else auto f = formatter(cfg); - return [f] (LogMsg const &m) {syslog (LOG_INFO | LOG_USER,"%s",f(m).c_str ());}; + return [f](LogMsg const &m) { + syslog(LOG_INFO | LOG_USER, "%s", f(m).c_str()); + }; #endif } -std::ifstream::pos_type filesize(std::string const&filename) -{ - if(!boost::filesystem::exists(filename)) +std::ifstream::pos_type filesize(std::string const &filename) { + if (!boost::filesystem::exists(filename)) return 0; else { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); @@ -88,24 +82,21 @@ std::ifstream::pos_type filesize(std::string const&filename) } } - - -Sink file_sink(LoggingConfig const&cfg) { +Sink file_sink(LoggingConfig const &cfg) { static std::ofstream stream; - static uint64_t bytes_written = 0; + static uint64_t bytes_written = 0; const auto max_sz = 120 * 1024 * 1024; - - auto f= formatter(cfg); + + auto f = formatter(cfg); auto path = log_path(); path /= "log"; - + auto parent = path.parent_path(); - - if (!boost::filesystem::is_directory(parent)) + if (!boost::filesystem::is_directory(parent)) bts_assert(boost::filesystem::create_directories(parent)); - if(boost::filesystem::exists(path)) { + if (boost::filesystem::exists(path)) { auto sz = boost::filesystem::file_size(path); if (sz > max_sz) { auto backup = boost::filesystem::path(path.string() + ".old"); @@ -113,10 +104,9 @@ Sink file_sink(LoggingConfig const&cfg) { } } - stream = std::ofstream(path.string(),std::ofstream::app); - - return [=] (LogMsg const &m) { + stream = std::ofstream(path.string(), std::ofstream::app); + return [=](LogMsg const &m) { auto msg = f(m); bytes_written += msg.size(); if (bytes_written >= max_sz) { @@ -124,16 +114,15 @@ Sink file_sink(LoggingConfig const&cfg) { stream.close(); auto backup = boost::filesystem::path(path.string() + ".old"); boost::filesystem::rename(path, backup); - stream = std::ofstream(path.string(),std::ofstream::app); + stream = std::ofstream(path.string(), std::ofstream::app); } stream << f(m) << std::endl; }; } Sink null_sink() { - return [](const LogMsg&) {}; + return [](const LogMsg &) {}; } - -}} - +} // namespace log +} // namespace bts From 6aec729b6aad767258c6cc4096e0fee28a1286b2 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Wed, 19 Aug 2020 21:16:54 -0400 Subject: [PATCH 3/5] Added prettier logging when observing spartan pcaps --- src/server/sparkd/cmds/Spartan.cpp | 162 ++++++------------ .../cmds/spartan/analysis/RunAnalysis.cpp | 39 ++++- 2 files changed, 89 insertions(+), 112 deletions(-) diff --git a/src/server/sparkd/cmds/Spartan.cpp b/src/server/sparkd/cmds/Spartan.cpp index d151a2078..af4cf607d 100644 --- a/src/server/sparkd/cmds/Spartan.cpp +++ b/src/server/sparkd/cmds/Spartan.cpp @@ -2,18 +2,18 @@ #include "server/sparkd/cmds/spartan/algo/RunTAS.h" #include "server/sparkd/cmds/spartan/analysis/RunAnalysis.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 "server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h" -#include "server/sparkd/cmds/spartan/md/mdp3/handler/ChannelHandler.h" -#include "server/sparkd/cmds/spartan/md/mdp3/feed_control/PickedFeed.h" +#include #include #include #include -#include namespace bts { namespace cmd { @@ -53,147 +53,93 @@ int export_tables(std::string const &file, std::string const &out_dir) { void on_recovery_complete( std::vector const &secs) override { for (auto s : secs) { - securities << s->security_id().value() << "," << s->symbol() << "," - << s->definition().security_group() << "," - << s->definition().asset() << "," - << s->definition().last_update_time() << std::endl; + securities << s->security_id().value() // security id + << "," << s->symbol() << "," // symbol + << s->definition().security_group() << "," // group + << s->definition().asset() << "," // asset + << s->definition().last_update_time() // last update time + << std::endl; for (auto const &[id, order] : s->orders()) - event_items << 0 << "," // event_id - - << 0 << "," // transact time - + event_items << 0 << "," // event_id + << 0 << "," // transact time << s->security_id().value() << "," // security id - - << s->trading_status() << "," // trading status - - << "order_change," // type - - << "init," // change - - << id << "," // order key - + << s->trading_status() << "," // trading status + << "order_change," // type + << "init," // change + << id << "," // order key << api::Side_Name(order.side) << "," // side - - << order.priority.value() << "," // priority - - << order.price.price() << "," // price - - << order.quantity.value() << "," // quantity - - << "," // trade_entry_id - + << order.priority.value() << "," // priority + << order.price.price() << "," // price + << order.quantity.value() << "," // quantity + << "," // trade_entry_id << "n/a" // aggressor - << std::endl; } } void on_real_time_event(MDP3Event const &ev) override { event_id++; - - events << event_id << "," - - << ev.transact_time << "," - - << ev.first_packet_sn << "," - - << ev.last_packet_sn << "," - - << ev.first_packet_send_time << "," - - << ev.last_packet_send_time << std::endl; + events << event_id << "," // event id + << ev.transact_time << "," // transactr time + << ev.first_packet_sn << "," // first packet_sn + << ev.last_packet_sn << "," // last_packet_sn + << ev.first_packet_send_time << "," // first packet send time + << ev.last_packet_send_time // last packet send time + << std::endl; for (auto s : ev.affected_securities) { for (auto const &change : s->order_changes()) - event_items << event_id << "," - - << ev.transact_time.value() << "," // transact time - + event_items << event_id << "," // event id + << ev.transact_time.value() // transact time + << "," // transact time << s->security_id().value() << "," // security id - - << s->trading_status() << "," // trading status - - << "order_change," // type - - << change_name(change.change) << "," - - << change.order.key.value() << "," // order key - + << s->trading_status() << "," // trading status + << "order_change," // type + << change_name(change.change) << "," // change type + << change.order.key.value() << "," // order key << api::Side_Name(change.order.side) << "," // side - << change.order.priority.value() << "," // priority - - << change.order.price.price() << "," // price - + << change.order.price.price() << "," // price << change.order.quantity.value() << "," // quantity - - << "," // trade_entry_id - + << "," // trade_entry_id << "n/a" // aggressor - << std::endl; for (auto const &f : s->fills()) - event_items << event_id << "," - + event_items << event_id << "," // event id << ev.transact_time.value() << "," // transact time - << s->security_id().value() << "," // security id - - << s->trading_status() << "," // trading status - - << "fill," // type - - << "," - - << f.key.value() << "," // order key - - << "," // side - - << "," // priority - - << f.price << "," // price - - << f.quantity << "," // quantity - - << f.trade_entry_id << "," // trade_entry_id - - << aggressor_name(f.aggressor) // aggressor - + << s->trading_status() << "," // trading status + << "fill," // type + << "," // null + << f.key.value() << "," // order key + << "," // side + << "," // priority + << f.price << "," // price + << f.quantity << "," // quantity + << f.trade_entry_id << "," // trade_entry_id + << aggressor_name(f.aggressor) // aggressor << std::endl; auto deduced_order = s->deduced_order_change(); if (deduced_order) { - event_items << event_id << "," - + event_items << event_id << "," // event id << ev.transact_time.value() << "," // transact time - << s->security_id().value() << "," // security id - - << s->trading_status() << "," // trading status - - << "deduced_order," // type - + << s->trading_status() << "," // trading status + << "deduced_order," // type << change_name(deduced_order->change) << "," - << deduced_order->order.key.value() << "," // order key - << api::Side_Name(deduced_order->order.side) << "," // side - << "," // priority - << deduced_order->order.price.price() << "," // price - << deduced_order->order.quantity.value() - << "," // quantity - - << "," // trade_entry_id - + << "," // quantity + << "," // trade_entry_id << "n/a" // aggressor - << std::endl; } } @@ -217,8 +163,8 @@ int Spartan::execute(std::vector const &args) { error = spartan::convert_pcap_to_json(args); else if (args[0] == "pcap_to_tables") error = export_tables(args[1], args[2]); - else if (args[0] == "slim_pcap") - error = slim_pcap(args[1],args[2]); + else if (args[0] == "slim_pcap") + error = slim_pcap(args[1], args[2]); } if (error) std::cout << help(); diff --git a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp index 200dce8ad..68fffc8c6 100644 --- a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp +++ b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp @@ -1,6 +1,7 @@ #include "server/sparkd/cmds/spartan/analysis/RunAnalysis.h" #include "../md/mdp3/parsing/MDP3Parser.h" #include "../util/PCapReader.h" +#include "lib/utils/bts_chrono.h" #include "lib/utils/overloaded.h" #include "lib/utils/stats.h" #include "lib/utils/type_name.h" @@ -9,6 +10,8 @@ #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/md/mdp3/common/mdp3_common.h" +#include "server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h" #include #include @@ -36,7 +39,7 @@ struct JSON_Writer { template void operator()(M const &m) { json_obj["SeqNum"] = packet.seq_num(); - json_obj["SendTime"] = packet.sending_time() ; + json_obj["SendTime"] = packet.sending_time(); json_obj["Size"] = packet.size(); json_buffer.str(""); @@ -177,6 +180,36 @@ int convert_pcap_to_csv_summary(std::vector const &args) { } void observe_channel(std::string const &file, mdp3::IChannelObserver &obs) { + struct ObsWrapper : mdp3::IChannelObserver { + ObsWrapper(mdp3::IChannelObserver &obs) : real_obs(obs) {} + IChannelObserver &real_obs; + size_t previous_packet = 0; + size_t previous_send_ts = 0; + TimeStamp last_print = Timer::now(); + + void on_recovery_complete( + std::vector const &s) override { + real_obs.on_recovery_complete(s); + } + void on_real_time_event(mdp3::MDP3Event const &ev) override { + if (ms_diff(Timer::now(), last_print) >= 1000) { + last_print = Timer::now(); + std::stringstream str; + mdp3::cme_ts_to_time_str(ev.transact_time.value(), &str); + LOG(Spartan, Info, "Packet time: {} ({} pkt/sec {}x real time)", + str.str(), (ev.first_packet_sn - previous_packet), + (ev.first_packet_send_time.value() - previous_send_ts) / + 1000000000); + previous_packet = ev.first_packet_sn; + previous_send_ts = ev.first_packet_send_time.value(); + } + real_obs.on_real_time_event(ev); + } + void on_real_time_channel_loss() override { + real_obs.on_real_time_channel_loss(); + } + } obs_wrapper(obs); + struct Ctrl : mdp3::IFeedController { void start_instrument_feed() override{}; void stop_instrument_feed() override{}; @@ -190,9 +223,7 @@ void observe_channel(std::string const &file, mdp3::IChannelObserver &obs) { auto feed_map = mdp3::guess_feed_map(file); bts_assert(feed_map); auto reader = PCapReader{file}; - - mdp3::AB_Arbitrageur ab; - mdp3::ChannelHandler handler(obs, ctrl); + mdp3::ChannelHandler handler(obs_wrapper, ctrl); reader.on_packet() = [&](auto const &info, auto const &payload) { if ((info.dst_ip == feed_map.incremental[0].ip && From b871cc4e09a558255cf8d29e32c212e339c70618 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Thu, 20 Aug 2020 09:16:12 -0400 Subject: [PATCH 4/5] Cleaned up code. --- src/server/sparkd/CMakeDeps.cmake | 2 +- src/server/sparkd/cmds/QuickTest.cpp | 37 +- src/server/sparkd/cmds/Spartan.cpp | 158 +-------- .../analysis/ActionableEventAnalyzer.cpp | 1 - .../analysis/ActionableEventAnalyzer.h | 59 ---- .../cmds/spartan/analysis/RunAnalysis.cpp | 251 -------------- .../cmds/spartan/analysis/RunAnalysis.h | 14 - .../sparkd/cmds/spartan/docs/recorder.org | 29 -- .../spartan/instruments/InstrumentStore.h | 29 -- .../md/mdp3/common/InstrumentSnapshot.h | 126 +++---- .../spartan/{sql_tools => md/mdp3/sql}/md.sql | 71 ++-- .../md/mdp3/tests/spartan_md_tests.cpp | 1 - .../cmds/spartan/md/mdp3/utils/mdp3_utils.cpp | 326 ++++++++++++++++-- .../cmds/spartan/md/mdp3/utils/mdp3_utils.h | 43 ++- 14 files changed, 419 insertions(+), 728 deletions(-) delete mode 100644 src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.cpp delete mode 100644 src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.h delete mode 100644 src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp delete mode 100644 src/server/sparkd/cmds/spartan/analysis/RunAnalysis.h delete mode 100644 src/server/sparkd/cmds/spartan/docs/recorder.org delete mode 100644 src/server/sparkd/cmds/spartan/instruments/InstrumentStore.h rename src/server/sparkd/cmds/spartan/{sql_tools => md/mdp3/sql}/md.sql (55%) diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index 7998d2477..afe9c05d9 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1 +1 @@ -set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/analysis/ActionableEventAnalyzer.cpp;cmds/spartan/analysis/RunAnalysis.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file +set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file diff --git a/src/server/sparkd/cmds/QuickTest.cpp b/src/server/sparkd/cmds/QuickTest.cpp index ca518c550..a90b4bbfe 100644 --- a/src/server/sparkd/cmds/QuickTest.cpp +++ b/src/server/sparkd/cmds/QuickTest.cpp @@ -10,7 +10,6 @@ #include "lib/domain_model/sod.h" #include "lib/logging/logging.h" #include "lib/utils/datetime.h" -#include "server/sparkd/cmds/spartan/analysis/RunAnalysis.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h" #include "server/sparkd/cmds/spartan/md/mdp3/common/mdp3_common.h" #include "server/sparkd/cmds/spartan/md/mdp3/feed_control/AB_Arbitrageur.h" @@ -29,40 +28,6 @@ namespace bts { namespace cmd { -using namespace bts::orderman; -using namespace spartan::mdp3; -using namespace spartan; - -struct TimeWriter { - mdp3::MDP3PacketView packet; - void on_begin_packet(mdp3::MDP3PacketView const &p) { packet = p; } - void on_end_packet() { std::cout << packet.sending_time() << std::endl; } - - template void operator()(M const &) {} -}; -void print_times(std::string const &file) { - struct PacketBuffers { - spartan::mdp3::MDP3Packet i; - spartan::mdp3::MDP3Packet n; - }; - auto feed_map = spartan::mdp3::guess_feed_map(file); - bts_assert(feed_map); - auto reader = PCapReader{file}; - - mdp3::AB_Arbitrageur ab; - - reader.on_packet() = [&](auto const &info, auto const &payload) { - if ((info.dst_ip == feed_map.incremental[0].ip && - info.dst_port == feed_map.incremental[0].port)) { - TimeWriter tw; - parse_packet(MDP3PacketView{payload}, tw); - } - - return true; - }; - while (reader.read_next()) - ; -} int QuickTest::execute(std::vector const &args) { @@ -128,7 +93,7 @@ int QuickTest::execute(std::vector const &args) { } } obs; - spartan::observe_channel(file, obs); + spartan::mdp3::observe_channel(file, obs); return 0; } diff --git a/src/server/sparkd/cmds/Spartan.cpp b/src/server/sparkd/cmds/Spartan.cpp index af4cf607d..04e33c57b 100644 --- a/src/server/sparkd/cmds/Spartan.cpp +++ b/src/server/sparkd/cmds/Spartan.cpp @@ -1,6 +1,5 @@ #include "Spartan.h" #include "server/sparkd/cmds/spartan/algo/RunTAS.h" -#include "server/sparkd/cmds/spartan/analysis/RunAnalysis.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" @@ -18,153 +17,15 @@ namespace bts { namespace cmd { -int slim_pcap(std::string const &file, std::string const &out_dir) { - return !spartan::mdp3::slim_down_pcap(file, out_dir); -} - -int export_tables(std::string const &file, std::string const &out_dir) { - using namespace bts::spartan::mdp3; - - struct Obs : IChannelObserver { - - Obs(std::string const &out_dir) - : events(out_dir + "/events.csv"), - event_items(out_dir + "/event_items.csv"), - securities(out_dir + "/securities.csv") { - - events << "eid, t_time,first_sn,last_sn," - "first_st,last_st" - << std::endl; - - event_items << "eid, t_time,sid,status,type," - "change,ok,side," - "pri,price,qty,tid,agg" - << std::endl; - - securities << "sid,symbol,group,asset,last_t" << std::endl; - } - - std::ofstream events; - std::ofstream event_items; - std::ofstream orders; - std::ofstream securities; - size_t event_id = 0; - - void on_recovery_complete( - std::vector const &secs) override { - for (auto s : secs) { - securities << s->security_id().value() // security id - << "," << s->symbol() << "," // symbol - << s->definition().security_group() << "," // group - << s->definition().asset() << "," // asset - << s->definition().last_update_time() // last update time - << std::endl; - - for (auto const &[id, order] : s->orders()) - event_items << 0 << "," // event_id - << 0 << "," // transact time - << s->security_id().value() << "," // security id - << s->trading_status() << "," // trading status - << "order_change," // type - << "init," // change - << id << "," // order key - << api::Side_Name(order.side) << "," // side - << order.priority.value() << "," // priority - << order.price.price() << "," // price - << order.quantity.value() << "," // quantity - << "," // trade_entry_id - << "n/a" // aggressor - << std::endl; - } - } - - void on_real_time_event(MDP3Event const &ev) override { - event_id++; - events << event_id << "," // event id - << ev.transact_time << "," // transactr time - << ev.first_packet_sn << "," // first packet_sn - << ev.last_packet_sn << "," // last_packet_sn - << ev.first_packet_send_time << "," // first packet send time - << ev.last_packet_send_time // last packet send time - << std::endl; - - for (auto s : ev.affected_securities) { - for (auto const &change : s->order_changes()) - event_items << event_id << "," // event id - << ev.transact_time.value() // transact time - << "," // transact time - << s->security_id().value() << "," // security id - << s->trading_status() << "," // trading status - << "order_change," // type - << change_name(change.change) << "," // change type - << change.order.key.value() << "," // order key - << api::Side_Name(change.order.side) << "," // side - << change.order.priority.value() << "," // priority - << change.order.price.price() << "," // price - << change.order.quantity.value() << "," // quantity - << "," // trade_entry_id - << "n/a" // aggressor - << std::endl; - - for (auto const &f : s->fills()) - event_items << event_id << "," // event id - << ev.transact_time.value() << "," // transact time - << s->security_id().value() << "," // security id - << s->trading_status() << "," // trading status - << "fill," // type - << "," // null - << f.key.value() << "," // order key - << "," // side - << "," // priority - << f.price << "," // price - << f.quantity << "," // quantity - << f.trade_entry_id << "," // trade_entry_id - << aggressor_name(f.aggressor) // aggressor - << std::endl; - - auto deduced_order = s->deduced_order_change(); - if (deduced_order) { - event_items << event_id << "," // event id - << ev.transact_time.value() << "," // transact time - << s->security_id().value() << "," // security id - << s->trading_status() << "," // trading status - << "deduced_order," // type - << change_name(deduced_order->change) << "," - << deduced_order->order.key.value() - << "," // order key - << api::Side_Name(deduced_order->order.side) - << "," // side - << "," // priority - << deduced_order->order.price.price() << "," // price - << deduced_order->order.quantity.value() - << "," // quantity - << "," // trade_entry_id - << "n/a" // aggressor - << std::endl; - } - } - } - - void on_real_time_channel_loss() override { - std::cout << "Observed loss, resetting\n"; - } - } obs(out_dir); - - spartan::observe_channel(file, obs); - return 0; -} - int Spartan::execute(std::vector const &args) { auto error = 1; if (args.size() > 0) { - if (args[0] == "pcap_to_msgs") - error = spartan::convert_pcap_to_csv_summary(args); - else if (args[0] == "pcap_to_json") - error = spartan::convert_pcap_to_json(args); - else if (args[0] == "pcap_to_tables") - error = export_tables(args[1], args[2]); - else if (args[0] == "slim_pcap") - error = slim_pcap(args[1], args[2]); + if (args[0] == "json" && args.size() == 2) + error = spartan::mdp3::to_json(args[1]); + else if (args[0] == "compress" && args.size() == 3) + error = spartan::mdp3::compress(args[1],args[2]); + else if (args[0] == "csv" && args.size() == 3) + error = spartan::mdp3::to_csv(args[1], args[2]); } if (error) std::cout << help(); @@ -172,10 +33,9 @@ int Spartan::execute(std::vector const &args) { } std::string Spartan::help() { - return fmt::format("\tpcap_to_msgs pcap_file\n" - "\tpcap_to_json pcap_file\n" - "\tslim_pcap in_pcap out_pcap\n" - "\tpcap_to_tables pcap_file output_dir\n"); + return fmt::format("\tjson \n" + "\tcompress \n" + "\tcsv "); } } // namespace cmd diff --git a/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.cpp b/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.cpp deleted file mode 100644 index 3c32c39d8..000000000 --- a/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "ActionableEventAnalyzer.h" diff --git a/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.h b/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.h deleted file mode 100644 index a2d70e437..000000000 --- a/src/server/sparkd/cmds/spartan/analysis/ActionableEventAnalyzer.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include "../md/mdp3/parsing/MDP3Parser.h" -#include "lib/utils/stats.h" -#include -#include - -namespace bts { -namespace spartan { - -struct ActionableEventAnalyzer { - - struct Event { - uint64_t transact_time; - uint64_t send_time; - uint64_t actionable_window; - uint64_t exchange_latency; - uint64_t time_from_last_transaction; - }; - std::vector events; - template void operator()(mdp3::MDP3PacketHeader const&ph,mdp3::MDP3MsgHeader const &, const M &m) { - Event e{m.transactTime(), ph.sending_time, 0, - ph.sending_time - m.transactTime(), 0}; - if (events.size()) { - auto &previous = events.back(); - previous.actionable_window = - std::max(0l, (int64_t)(previous.send_time - m.transactTime())); - previous.time_from_last_transaction = m.transactTime() - previous.transact_time; - } - events.push_back(e); - } - - std::string single_stat(uint64_t Event::*field) { - std::ostringstream str; - str.precision(0); - str << std::fixed << "\tmin: " - << stats::min(events, [field](auto const &ev) { return ev.*field; }) - << "\t\tmed: " - << stats::med(events, [field](auto const &ev) { return ev.*field; }) - << "\t\tmax: " - << stats::max(events, [field](auto const &ev) { return ev.*field; }); - return str.str(); - } - - ~ActionableEventAnalyzer() { - std::cout << "Data points:\n \t\t" << events.size() - - << "\nExchange Latency:\n" - << single_stat(&Event::exchange_latency) - - << "\nTransaction Gap:\n" - << single_stat(&Event::time_from_last_transaction) - - << "\nActionable Window:\n" - << single_stat(&Event::actionable_window) << "\n"; - } -}; - -} // namespace spartan -} // namespace bts diff --git a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp deleted file mode 100644 index 68fffc8c6..000000000 --- a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.cpp +++ /dev/null @@ -1,251 +0,0 @@ -#include "server/sparkd/cmds/spartan/analysis/RunAnalysis.h" -#include "../md/mdp3/parsing/MDP3Parser.h" -#include "../util/PCapReader.h" -#include "lib/utils/bts_chrono.h" -#include "lib/utils/overloaded.h" -#include "lib/utils/stats.h" -#include "lib/utils/type_name.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/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/md/mdp3/common/mdp3_common.h" -#include "server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h" - -#include -#include -#include -#include - -namespace bts { -namespace spartan { - -struct PacketBuffers { - mdp3::MDP3Packet i; - mdp3::MDP3Packet n; -}; - -mdp3::AB_Arbitrageur ab; - -struct JSON_Writer { - - std::stringstream json_buffer; - nlohmann::json json_obj; - mdp3::MDP3PacketView packet; - - void on_begin_packet(mdp3::MDP3PacketView const &p) { packet = p; } - void on_end_packet() {} - - template void operator()(M const &m) { - json_obj["SeqNum"] = packet.seq_num(); - json_obj["SendTime"] = packet.sending_time(); - json_obj["Size"] = packet.size(); - - json_buffer.str(""); - json_buffer.clear(); - json_buffer << m; - json_obj["Msg"] = nlohmann::json::parse(json_buffer.str()); - std::cout << json_obj.dump(4) << std::endl; - } -}; - -int convert_pcap_to_json(std::vector const &args) { - std::array buffers; - - auto reader = PCapReader{args[1]}; - JSON_Writer writer; - - reader.on_packet() = [&](auto const &, auto const &payload) { - parse_packet(mdp3::MDP3PacketView{payload}, writer); - return true; - }; - while (reader.read_next()) - ; - return 0; -} - -template transactTime()) = 0> -uint64_t get_transact_time(M &m) { - return m.transactTime(); -} - -template lastUpdateTime()) = 0> -uint64_t get_transact_time(M &m) { - return m.lastUpdateTime(); -} - -struct CSVPrinter { - - std::stringstream stime_buffer; - std::stringstream ttime_buffer; - size_t previous_t_time = 0; - size_t previous_s_time = 0; - mdp3::MDP3PacketView packet; - - CSVPrinter() { - std::cout - << "HumanTransactTime,HumanSendingTime," - "Latency,TransactTime,SendingTime,SeqNum,MsgType,TimeInQueue," - "MatchEventindicator" - << std::endl; - } - - void on_begin_packet(mdp3::MDP3PacketView const &v) { packet = v; } - void on_end_packet() {} - - template void print(M &m) { - stime_buffer.str(""); - stime_buffer.clear(); - mdp3::cme_ts_to_date_str(packet.sending_time(), &stime_buffer); - ttime_buffer.str(""); - ttime_buffer.clear(); - mdp3::cme_ts_to_date_str(get_transact_time(m), &ttime_buffer); - - auto t = get_transact_time(m); - std::cout << ttime_buffer.str() << "," << stime_buffer.str() << "," - << (packet.sending_time() - t) / 1000 << "," << t << "," - << packet.sending_time() << "," << packet.seq_num() << "," - << utils::type_name() << "," - << (t < previous_s_time ? ((previous_s_time - t) / 1000) : 0) - << "," << m.matchEventIndicator().endOfEvent() << std::endl; - previous_s_time = packet.sending_time(); - previous_t_time = t; - } - - void operator()(::mdp3::MDIncrementalRefreshOrderBook43 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshOrderBook47 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshTradeSummary42 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshTradeSummary48 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshVolume37 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshDailyStatistics33 &m) { - print(m); - } - void operator()(::mdp3::MDIncrementalRefreshDailyStatistics49 &m) { - print(m); - } - void operator()(::mdp3::MDIncrementalRefreshLimitsBanding34 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshLimitsBanding50 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshBook46 &m) { print(m); } - void operator()(::mdp3::MDInstrumentDefinitionFuture54 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshSessionStatistics35 &m) { - print(m); - } - void operator()(::mdp3::MDIncrementalRefreshSessionStatistics51 &m) { - print(m); - } - void operator()(::mdp3::MDInstrumentDefinitionFuture27 &m) { print(m); } - void operator()(::mdp3::ChannelReset4 &m) { print(m); } - void operator()(::mdp3::MDIncrementalRefreshBook32 &m) { print(m); } - void operator()(::mdp3::MDInstrumentDefinitionOption41 &m) { print(m); } - void operator()(::mdp3::MDInstrumentDefinitionOption55 &m) { print(m); } - void operator()(::mdp3::MDInstrumentDefinitionSpread29 &m) { print(m); } - void operator()(::mdp3::MDInstrumentDefinitionSpread56 &m) { print(m); } - void operator()(::mdp3::QuoteRequest39 &m) { print(m); } - void operator()(::mdp3::SecurityStatus30 &m) { print(m); } -}; - -int convert_pcap_to_csv_summary(std::vector const &args) { - std::array buffers; - - auto feed_map = mdp3::guess_feed_map(args[1]); - bts_assert(feed_map); - auto reader = PCapReader{args[1]}; - - mdp3::AB_Arbitrageur ab; - CSVPrinter csv_printer; - - reader.on_packet() = [&](auto const &info, auto const &payload) { - if ((info.dst_ip == feed_map.incremental[0].ip && - info.dst_port == feed_map.incremental[0].port)) { - buffers[0].i = mdp3::MDP3Packet{payload}; - } else if ((info.dst_ip == feed_map.incremental[0].ip && - info.dst_port == feed_map.incremental[0].port)) { - buffers[1].i = mdp3::MDP3Packet{payload}; - } else - return true; - auto action = ab(buffers[0].i.view(), buffers[1].i.view()); - if (action.action == mdp3::AB_Arbitrageur::APPLY) - parse_packet(action.packet, csv_printer); - else if (action.action == mdp3::AB_Arbitrageur::RECOVER) { - std::cerr << "Unrecoverable loss detecte at sequence number: " - << ab.expected_next_sn() - 1 << std::endl; - return false; - } - return true; - }; - while (reader.read_next()) - ; - return 0; -} - -void observe_channel(std::string const &file, mdp3::IChannelObserver &obs) { - struct ObsWrapper : mdp3::IChannelObserver { - ObsWrapper(mdp3::IChannelObserver &obs) : real_obs(obs) {} - IChannelObserver &real_obs; - size_t previous_packet = 0; - size_t previous_send_ts = 0; - TimeStamp last_print = Timer::now(); - - void on_recovery_complete( - std::vector const &s) override { - real_obs.on_recovery_complete(s); - } - void on_real_time_event(mdp3::MDP3Event const &ev) override { - if (ms_diff(Timer::now(), last_print) >= 1000) { - last_print = Timer::now(); - std::stringstream str; - mdp3::cme_ts_to_time_str(ev.transact_time.value(), &str); - LOG(Spartan, Info, "Packet time: {} ({} pkt/sec {}x real time)", - str.str(), (ev.first_packet_sn - previous_packet), - (ev.first_packet_send_time.value() - previous_send_ts) / - 1000000000); - previous_packet = ev.first_packet_sn; - previous_send_ts = ev.first_packet_send_time.value(); - } - real_obs.on_real_time_event(ev); - } - void on_real_time_channel_loss() override { - real_obs.on_real_time_channel_loss(); - } - } obs_wrapper(obs); - - struct Ctrl : mdp3::IFeedController { - void start_instrument_feed() override{}; - void stop_instrument_feed() override{}; - void start_snapshot_feed() override{}; - void stop_snapshot_feed() override{}; - void start_incremental_feed() override{}; - void stop_incremental_feed() override{}; - } ctrl; - std::array buffers; - - auto feed_map = mdp3::guess_feed_map(file); - bts_assert(feed_map); - auto reader = PCapReader{file}; - mdp3::ChannelHandler handler(obs_wrapper, ctrl); - - reader.on_packet() = [&](auto const &info, auto const &payload) { - if ((info.dst_ip == feed_map.incremental[0].ip && - info.dst_port == feed_map.incremental[0].port)) { - buffers[0].i.set_bytes(payload); - handler.on_incremental_feed(buffers[0].i.view(), buffers[1].i.view()); - } else if ((info.dst_ip == feed_map.incremental[1].ip && - info.dst_port == feed_map.incremental[1].port)) { - buffers[1].i.set_bytes(payload); - handler.on_incremental_feed(buffers[0].i.view(), buffers[1].i.view()); - } else if ((info.dst_ip == feed_map.instrument.ip && - info.dst_port == feed_map.instrument.port)) { - handler.on_instrument_feed(mdp3::MDP3PacketView{payload}); - } else if ((info.dst_ip == feed_map.snapshot.ip && - info.dst_port == feed_map.snapshot.port)) { - handler.on_snapshot_feed(mdp3::MDP3PacketView{payload}); - } - return true; - }; - while (reader.read_next()) - ; -} - -} // namespace spartan -} // namespace bts diff --git a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.h b/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.h deleted file mode 100644 index ef34cafeb..000000000 --- a/src/server/sparkd/cmds/spartan/analysis/RunAnalysis.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -namespace bts::spartan::mdp3 { -class IChannelObserver; -} -namespace bts::spartan { -int convert_pcap_to_csv_summary(std::vector const &args); -int convert_pcap_to_json(std::vector const &args ); - -void observe_channel(std::string const &, mdp3::IChannelObserver &) ; -} diff --git a/src/server/sparkd/cmds/spartan/docs/recorder.org b/src/server/sparkd/cmds/spartan/docs/recorder.org deleted file mode 100644 index cb53066c2..000000000 --- a/src/server/sparkd/cmds/spartan/docs/recorder.org +++ /dev/null @@ -1,29 +0,0 @@ -* Arbitration -on_msg (Msg* a, Msg *b) { - if (a && a->seq_num == seq_num) - seq_n++; - deliver(*a); - return; - } - if (b && b->seq_num == seq_num) - seq_n++; - deliver(*b); - return; - } - on_loss(seq_num); -} -* On startup -** In recovery -- join instrument feed -- join a, b -- join sambo - -- queued events is not 0 and its an unbroken sequence -- joined the snapshot feed, and it either has a seq n < the the top of the queue (so the snapshot is useless) or we are missing some messages in the snapshot -- we are either joined with the instrument feed but still not gone through a full cycle or we have a full set of securities - - - begin recovery - - b - - - diff --git a/src/server/sparkd/cmds/spartan/instruments/InstrumentStore.h b/src/server/sparkd/cmds/spartan/instruments/InstrumentStore.h deleted file mode 100644 index 164ffe83c..000000000 --- a/src/server/sparkd/cmds/spartan/instruments/InstrumentStore.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -class mdp3::MDInstrumentDefinitionFuture27; -class mdp3::MDInstrumentDefinitionFuture54; -class mdp3::MDInstrumentDefinitionOption41; -class mdp3::MDInstrumentDefinitionOption55; -class mdp3::MDInstrumentDefinitionSpread29; -class mdp3::MDInstrumentDefinitionSpread56; - -namespace bts { -namespace spartan { - -class InstrumentStore { - InstrumentStore(std::string const&base_path); - void store( const mdp3::MDInstrumentDefinitionFuture27&); - void store( const mdp3::MDInstrumentDefinitionFuture54&); - void store( const mdp3::MDInstrumentDefinitionOption41&); - void store( const mdp3::MDInstrumentDefinitionOption55&); - void store( const mdp3::MDInstrumentDefinitionSpread29&); - void store( const mdp3::MDInstrumentDefinitionSpread56&); - -private: - struct PImpl; - std::unique_ptr me; -}; - -}} diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h b/src/server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h index ca136b899..7aa0583f3 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h @@ -1,7 +1,7 @@ #pragma once -#include "mdp3_common.h" #include "InstrumentDefinition.h" +#include "mdp3_common.h" #include "lib/domain_model/Security.pb.h" #include @@ -17,103 +17,103 @@ namespace bts::spartan::mdp3 { // - The instrument's definition // - Price books (implied and customer) // - Resting orders -// - Fills observed so far +// - Fills generated by the last event +// - Order changes generated in the last event +// - The deduced order for the last event // - Market statistics + class InstrumentSnapshot { public: - InstrumentSnapshot(InstrumentDefinition const&); + InstrumentSnapshot(InstrumentDefinition const &); InstrumentSnapshot(InstrumentDefinition &&); ~InstrumentSnapshot(); - // Definition + // Queries ------------------------------------------------------------ + // Security MDP3SecurityID security_id() const; InstrumentDefinition definition() const; - void set_definition(InstrumentDefinition const&); - - // Symbol (via definition) - const char* symbol() const {return definition().symbol();} - - // Last packet that affected this security - size_t last_processed_sn() const ; - void set_last_msg_processed_sn(size_t); - - // Trading status + const char *symbol() const { return definition().symbol(); } ::mdp3::SecurityTradingStatus::Value trading_status() const; - void set_trading_status(::mdp3::SecurityTradingStatus::Value) const; - // Book + // Last packet incorporated in this snapshot + size_t last_processed_sn() const; + + // Books Book const &book(api::Side) const; - void insert_book_level(api::Side, size_t idx,BookLevel const&); - void update_book_level(api::Side, size_t idx,BookLevel const&); - void remove_book_level(api::Side, size_t idx); - - // Implied Book ImpliedBook const &implied_book(api::Side) const; - void insert_implied_book_level(api::Side, size_t idx, BookLevel const&); - void update_implied_book_level(api::Side, size_t idx, BookLevel const&); - void remove_implied_book_level(api::Side, size_t idx); // Orders Orders const &orders() const; + // Last round of order changes OrderChanges const &order_changes() const; - void clear_order_changes() ; - void insert_order(MDP3Order const&); - void update_order(MDP3Order const&); - void remove_order(MDP3OrderKey); - Book build_book_from_orders (api::Side ) const; - void set_books_from_orders() ; - // Deduced order changes, that is the implied order change that + // Deduced order change, that is the order change that // would explain the last event processed in this snapshot as // described by order_changes() and fills() MaybeOrderChange deduced_order_change() const; - - // Reset books in response to a channel reset message - void reset_books(); - - // Fills - Fills const&fills() const; - void add_fill(MDP3Fill const&); - void update_fill(MDP3Fill const&); - void remove_fill(MDP3TradeEntryID, MDP3OrderKey ); - void clear_fills(); - - // Stats + + // Last round of fills + Fills const &fills() const; + + // Stats md::IntPrice high_limit_price() const; - void set_high_limit_price(md::IntPrice); - md::IntPrice low_limit_price() const; - void set_low_limit_price(md::IntPrice); md::IntPrice max_price_variation() const; - void set_max_price_variation(md::IntPrice); - MDP3Quantity cleared_volume() const; - void set_cleared_volume(MDP3Quantity); MDP3Quantity electronic_volume() const; - void set_electronic_volume(MDP3Quantity); + MDP3Quantity cleared_volume() const; md::IntPrice fixing_price() const; - void set_fixing_price(md::IntPrice); MDP3Quantity open_interest() const; - void set_open_interest(MDP3Quantity); md::IntPrice open_price() const; - void set_open_price(md::IntPrice ) ; md::IntPrice high_bid() const; - void set_high_bid(md::IntPrice ) ; md::IntPrice low_offer() const; - void set_low_offer(md::IntPrice ) ; md::IntPrice settlement_price() const; - void set_settlement_price(md::IntPrice ) ; md::IntPrice high_trade_price() const; - void set_high_trade_price(md::IntPrice ) ; md::IntPrice low_trade_price() const; - void set_low_trade_price(md::IntPrice ) ; + + // Mutators ------------------------------------------------------------ + void set_definition(InstrumentDefinition const &); + void set_last_msg_processed_sn(size_t); + void set_trading_status(::mdp3::SecurityTradingStatus::Value) const; + void insert_book_level(api::Side, size_t idx, BookLevel const &); + void update_book_level(api::Side, size_t idx, BookLevel const &); + void remove_book_level(api::Side, size_t idx); + void insert_implied_book_level(api::Side, size_t idx, BookLevel const &); + void update_implied_book_level(api::Side, size_t idx, BookLevel const &); + void remove_implied_book_level(api::Side, size_t idx); + void clear_order_changes(); + void insert_order(MDP3Order const &); + void update_order(MDP3Order const &); + void remove_order(MDP3OrderKey); + Book build_book_from_orders(api::Side) const; + void set_books_from_orders(); + void reset_books(); + void add_fill(MDP3Fill const &); + void update_fill(MDP3Fill const &); + void remove_fill(MDP3TradeEntryID, MDP3OrderKey); + void clear_fills(); + void set_high_limit_price(md::IntPrice); + void set_low_limit_price(md::IntPrice); + void set_max_price_variation(md::IntPrice); + void set_cleared_volume(MDP3Quantity); + void set_electronic_volume(MDP3Quantity); + void set_fixing_price(md::IntPrice); + void set_open_interest(MDP3Quantity); + void set_open_price(md::IntPrice); + void set_high_bid(md::IntPrice); + void set_low_offer(md::IntPrice); + void set_settlement_price(md::IntPrice); + void set_high_trade_price(md::IntPrice); + void set_low_trade_price(md::IntPrice); private: - template void insert(api::Side,std::array &, size_t idx,BookLevel const&); - template void update(api::Side,std::array &, size_t idx, BookLevel const&); - template void remove(api::Side,std::array &, size_t idx); + template + void insert(api::Side, std::array &, size_t idx, BookLevel const &); + template + void update(api::Side, std::array &, size_t idx, BookLevel const &); + template void remove(api::Side, std::array &, size_t idx); struct PImpl; std::unique_ptr me; -}; +}; -std::ostream& operator<<(std::ostream&, InstrumentSnapshot const&); +std::ostream &operator<<(std::ostream &, InstrumentSnapshot const &); } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/sql_tools/md.sql b/src/server/sparkd/cmds/spartan/md/mdp3/sql/md.sql similarity index 55% rename from src/server/sparkd/cmds/spartan/sql_tools/md.sql rename to src/server/sparkd/cmds/spartan/md/mdp3/sql/md.sql index ae517c93c..c555a4537 100644 --- a/src/server/sparkd/cmds/spartan/sql_tools/md.sql +++ b/src/server/sparkd/cmds/spartan/md/mdp3/sql/md.sql @@ -1,62 +1,35 @@ --- drop table msg; --- create table if not exists --- msg ( --- "HumanTransactTime" TEXT, --- "HumanSendingTime" TEXT, --- "Latency" numeric, --- "TransactTime" numeric, --- "SendingTime" numeric, --- "SeqNum" numeric, --- "MsgType" TEXT, --- "TimeInQueue" numeric, --- "MatchEventIndicator" numeric --- ); - --- drop view event_len; --- create view event_len as --- select transacttime, count(*) len from msg group by transacttime; - --- drop view summary_event_len; --- create view summary_event_len as --- select --- count(*) n_events, --- msg_count len --- from --- (select transacttime, count(*) msg_count from msg group by transacttime) t --- group by --- len drop table events; CREATE TABLE events( eid numeric, - "t_time" numeric, - "first_sn" numeric, - "last_sn" numeric, - "first_st" numeric, - "last_st" numeric + t_time numeric, + first_sn numeric, + last_sn numeric, + first_st numeric, + last_st numeric ); drop table event_items; CREATE TABLE event_items( eid numeric, - "t_time" numeric, - "sid" numeric, - "status" TEXT, - "type" TEXT, - "change" TEXT, - "ok" numeric, - "side" TEXT, - "pri" numeric, - "price" numeric, - "qty" numeric, - "tid" numeric, - "agg" TEXT + t_time numeric, + sid numeric, + status TEXT, + type TEXT, + change TEXT, + ok numeric, + side TEXT, + pri numeric, + price numeric, + qty numeric, + tid numeric, + agg TEXT ); drop table securities; CREATE TABLE securities( - "sid" numeric, - "symbol" TEXT, - "group" TEXT, - "asset" TEXT, - "last_t" numeric + sid numeric, + symbol TEXT, + group TEXT, + asset TEXT, + last_t numeric ); .mode csv .import event_items.csv event_items diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp index aabb7e0be..fe82df22c 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp @@ -30,7 +30,6 @@ struct PacketBuffers { }; TEST_CASE("spartan_md", "[spartan_md]") { - //auto file = "/home/ppinto/es_md/es_all.pcap"; auto file = os::sparkd_wd() + "/data_files/small_es.pcap"; auto feed_map = guess_feed_map(file); auto reader = PCapReader{file}; diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp index cd0e14eaa..58bd995ff 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp +++ b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.cpp @@ -22,9 +22,41 @@ #include #include #include +#include namespace bts::spartan::mdp3 { +void cme_ts_to_time_str(uint64_t cme_ts, std::stringstream *out) { + auto one_billion = 1000000000; + time_t unix_ts = cme_ts / one_billion; + auto boost_ts = boost::posix_time::from_time_t(unix_ts); + int hours = boost_ts.time_of_day().hours(); + int minutes = boost_ts.time_of_day().minutes(); + int seconds = boost_ts.time_of_day().seconds(); + *out << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) + << std::setfill('0') << minutes << ":" << std::setw(2) + << std::setfill('0') << seconds << "." << std::setw(9) + << cme_ts - (unix_ts * one_billion); +} + +void cme_ts_to_date_str(uint64_t cme_ts, std::stringstream *out) { + auto one_billion = 1000000000; + time_t unix_ts = cme_ts / one_billion; + auto boost_ts = boost::posix_time::from_time_t(unix_ts); + auto year = boost_ts.date().year(); + auto month = boost_ts.date().month().as_number(); + auto day = boost_ts.date().day().as_number(); + int hours = boost_ts.time_of_day().hours(); + int minutes = boost_ts.time_of_day().minutes(); + int seconds = boost_ts.time_of_day().seconds(); + *out << year << "-" << std::setw(2) << std::setfill('0') << month << "-" + << std::setw(2) << std::setw(2) << std::setfill('0') << day << "." + << std::setw(2) << std::setw(2) << std::setfill('0') << hours << ":" + << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) + << std::setfill('0') << seconds << "." << std::setw(9) + << cme_ts - (unix_ts * one_billion); +} + struct Guesser { FeedMap result; PCapReader::PacketInfo current_packet; @@ -121,7 +153,7 @@ std::ostream &operator<<(std::ostream &o, FeedMap const &fm) { return o; } -bool slim_down_pcap(std::string const &file, std::string const &out_file) { +int compress(std::string const &file, std::string const &out_file) { using namespace bts::spartan; using namespace bts::spartan::mdp3; @@ -141,7 +173,7 @@ bool slim_down_pcap(std::string const &file, std::string const &out_file) { struct Obs : IChannelObserver { bool observed_loss = false; bool recovery_complete = false; - + size_t previous_packet = 0; size_t previous_send_ts = 0; TimeStamp last_print; @@ -156,11 +188,10 @@ bool slim_down_pcap(std::string const &file, std::string const &out_file) { last_print = Timer::now(); std::stringstream str; cme_ts_to_time_str(ev.transact_time.value(), &str); - LOG(Spartan, Info, - "Time: {} -> {} pkt/sec at {}x real time", - str.str(), - (ev.first_packet_sn - previous_packet), - (ev.first_packet_send_time.value() - previous_send_ts) / 1000000000); + LOG(Spartan, Info, "Time: {} -> {} pkt/sec at {}x real time", + str.str(), (ev.first_packet_sn - previous_packet), + (ev.first_packet_send_time.value() - previous_send_ts) / + 1000000000); previous_packet = ev.first_packet_sn; previous_send_ts = ev.first_packet_send_time.value(); } @@ -232,41 +263,262 @@ bool slim_down_pcap(std::string const &file, std::string const &out_file) { while (reader.read_next()) if (obs.observed_loss) { - LOG(Spartan, Error, "Observed loss in {}. Cannot slim it down", file); - return false; + LOG(Spartan, Error, "Observed loss in {}. Cannot compress.", file); + return 1; }; - return true; + return 0; } -void cme_ts_to_time_str(uint64_t cme_ts, std::stringstream *out) { - auto one_billion = 1000000000; - time_t unix_ts = cme_ts / one_billion; - auto boost_ts = boost::posix_time::from_time_t(unix_ts); - int hours = boost_ts.time_of_day().hours(); - int minutes = boost_ts.time_of_day().minutes(); - int seconds = boost_ts.time_of_day().seconds(); - *out << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) - << std::setfill('0') << minutes << ":" << std::setw(2) - << std::setfill('0') << seconds << "." << std::setw(9) - << cme_ts - (unix_ts * one_billion); +struct JSON_Writer { + std::stringstream json_buffer; + nlohmann::json json_obj; + mdp3::MDP3PacketView packet; + + void on_begin_packet(mdp3::MDP3PacketView const &p) { packet = p; } + void on_end_packet() {} + + template void operator()(M const &m) { + json_obj["SeqNum"] = packet.seq_num(); + json_obj["SendTime"] = packet.sending_time(); + json_obj["Size"] = packet.size(); + + json_buffer.str(""); + json_buffer.clear(); + json_buffer << m; + json_obj["Msg"] = nlohmann::json::parse(json_buffer.str()); + std::cout << json_obj.dump(4) << std::endl; + } +}; + +struct PacketBuffers { + mdp3::MDP3Packet i; + mdp3::MDP3Packet n; +}; + +int to_json(std::string const&pcap) { + auto reader = PCapReader{pcap}; + JSON_Writer writer; + reader.on_packet() = [&](auto const &, auto const &payload) { + parse_packet(mdp3::MDP3PacketView{payload}, writer); + return true; + }; + while (reader.read_next()) + ; + return 0; } -void cme_ts_to_date_str(uint64_t cme_ts, std::stringstream *out) { - auto one_billion = 1000000000; - time_t unix_ts = cme_ts / one_billion; - auto boost_ts = boost::posix_time::from_time_t(unix_ts); - auto year = boost_ts.date().year(); - auto month = boost_ts.date().month().as_number(); - auto day = boost_ts.date().day().as_number(); - int hours = boost_ts.time_of_day().hours(); - int minutes = boost_ts.time_of_day().minutes(); - int seconds = boost_ts.time_of_day().seconds(); - *out << year << "-" << std::setw(2) << std::setfill('0') << month << "-" - << std::setw(2) << std::setw(2) << std::setfill('0') << day << "." - << std::setw(2) << std::setw(2) << std::setfill('0') << hours << ":" - << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) - << std::setfill('0') << seconds << "." << std::setw(9) - << cme_ts - (unix_ts * one_billion); +void observe_channel(std::string const &file, mdp3::IChannelObserver &obs) { + struct ObsWrapper : mdp3::IChannelObserver { + ObsWrapper(mdp3::IChannelObserver &obs) : real_obs(obs) {} + IChannelObserver &real_obs; + size_t previous_packet = 0; + size_t previous_send_ts = 0; + TimeStamp last_print = Timer::now(); + + void on_recovery_complete( + std::vector const &s) override { + real_obs.on_recovery_complete(s); + } + void on_real_time_event(mdp3::MDP3Event const &ev) override { + if (ms_diff(Timer::now(), last_print) >= 1000) { + last_print = Timer::now(); + std::stringstream str; + mdp3::cme_ts_to_time_str(ev.transact_time.value(), &str); + LOG(Spartan, Info, "Packet time: {} ({} pkt/sec {}x real time)", + str.str(), (ev.first_packet_sn - previous_packet), + (ev.first_packet_send_time.value() - previous_send_ts) / + 1000000000); + previous_packet = ev.first_packet_sn; + previous_send_ts = ev.first_packet_send_time.value(); + } + real_obs.on_real_time_event(ev); + } + void on_real_time_channel_loss() override { + real_obs.on_real_time_channel_loss(); + } + } obs_wrapper(obs); + + struct Ctrl : mdp3::IFeedController { + void start_instrument_feed() override{}; + void stop_instrument_feed() override{}; + void start_snapshot_feed() override{}; + void stop_snapshot_feed() override{}; + void start_incremental_feed() override{}; + void stop_incremental_feed() override{}; + } ctrl; + std::array buffers; + + auto feed_map = mdp3::guess_feed_map(file); + bts_assert(feed_map); + auto reader = PCapReader{file}; + mdp3::ChannelHandler handler(obs_wrapper, ctrl); + + reader.on_packet() = [&](auto const &info, auto const &payload) { + if ((info.dst_ip == feed_map.incremental[0].ip && + info.dst_port == feed_map.incremental[0].port)) { + buffers[0].i.set_bytes(payload); + handler.on_incremental_feed(buffers[0].i.view(), buffers[1].i.view()); + } else if ((info.dst_ip == feed_map.incremental[1].ip && + info.dst_port == feed_map.incremental[1].port)) { + buffers[1].i.set_bytes(payload); + handler.on_incremental_feed(buffers[0].i.view(), buffers[1].i.view()); + } else if ((info.dst_ip == feed_map.instrument.ip && + info.dst_port == feed_map.instrument.port)) { + handler.on_instrument_feed(mdp3::MDP3PacketView{payload}); + } else if ((info.dst_ip == feed_map.snapshot.ip && + info.dst_port == feed_map.snapshot.port)) { + handler.on_snapshot_feed(mdp3::MDP3PacketView{payload}); + } + return true; + }; + while (reader.read_next()) + ; +} +int to_csv(std::string const &file, std::string const &out_dir) { + using namespace bts::spartan::mdp3; + + struct Obs : IChannelObserver { + + Obs(std::string const &out_dir) + : events(out_dir + "/events.csv"), + event_items(out_dir + "/event_items.csv"), + securities(out_dir + "/securities.csv") { + + events << "eid, t_time,first_sn,last_sn," + "first_st,last_st" + << std::endl; + + event_items << "eid, t_time,sid,status,type," + "change,ok,side," + "pri,price,qty,tid,agg" + << std::endl; + + securities << "sid,symbol,group,asset,last_t" << std::endl; + } + + std::ofstream events; + std::ofstream event_items; + std::ofstream orders; + std::ofstream securities; + size_t event_id = 0; + std::unordered_set known_securities; + + void on_recovery_complete( + std::vector const &secs) override { + for (auto s : secs) { + securities << s->security_id().value() // security id + << "," << s->symbol() << "," // symbol + << s->definition().security_group() << "," // group + << s->definition().asset() << "," // asset + << s->definition().last_update_time() // last update time + << std::endl; + + known_securities.insert(s->security_id()); + + for (auto const &[id, order] : s->orders()) + event_items << 0 << "," // event_id + << 0 << "," // transact time + << s->security_id().value() << "," // security id + << s->trading_status() << "," // trading status + << "order_change," // type + << "init," // change + << id << "," // order key + << api::Side_Name(order.side) << "," // side + << order.priority.value() << "," // priority + << order.price.price() << "," // price + << order.quantity.value() << "," // quantity + << "," // trade_entry_id + << "n/a" // aggressor + << std::endl; + } + } + + void on_real_time_event(MDP3Event const &ev) override { + event_id++; + events << event_id << "," // event id + << ev.transact_time << "," // transact time + << ev.first_packet_sn << "," // first packet_sn + << ev.last_packet_sn << "," // last_packet_sn + << ev.first_packet_send_time << "," // first packet send time + << ev.last_packet_send_time // last packet send time + << std::endl; + + for (auto s : ev.affected_securities) { + + if (known_securities.count(s->security_id()) == 0) { + known_securities.insert(s->security_id()); + securities << s->security_id().value() // security id + << "," << s->symbol() << "," // symbol + << s->definition().security_group() << "," // group + << s->definition().asset() << "," // asset + << s->definition().last_update_time() // last update time + << std::endl; + } + + for (auto const &change : s->order_changes()) + event_items << event_id << "," // event id + << ev.transact_time.value() // transact time + << "," // transact time + << s->security_id().value() << "," // security id + << s->trading_status() << "," // trading status + << "order_change," // type + << change_name(change.change) << "," // change type + << change.order.key.value() << "," // order key + << api::Side_Name(change.order.side) << "," // side + << change.order.priority.value() << "," // priority + << change.order.price.price() << "," // price + << change.order.quantity.value() << "," // quantity + << "," // trade_entry_id + << "n/a" // aggressor + << std::endl; + + for (auto const &f : s->fills()) + event_items << event_id << "," // event id + << ev.transact_time.value() << "," // transact time + << s->security_id().value() << "," // security id + << s->trading_status() << "," // trading status + << "fill," // type + << "," // null + << f.key.value() << "," // order key + << "," // side + << "," // priority + << f.price << "," // price + << f.quantity << "," // quantity + << f.trade_entry_id << "," // trade_entry_id + << aggressor_name(f.aggressor) // aggressor + << std::endl; + + auto deduced_order = s->deduced_order_change(); + if (deduced_order) { + event_items << event_id << "," // event id + << ev.transact_time.value() << "," // transact time + << s->security_id().value() << "," // security id + << s->trading_status() << "," // trading status + << "deduced_order," // type + << change_name(deduced_order->change) << "," + << deduced_order->order.key.value() + << "," // order key + << api::Side_Name(deduced_order->order.side) + << "," // side + << "," // priority + << deduced_order->order.price.price() << "," // price + << deduced_order->order.quantity.value() + << "," // quantity + << "," // trade_entry_id + << "n/a" // aggressor + << std::endl; + } + } + } + + void on_real_time_channel_loss() override { + LOG(Spartan,Error,"Detected loss in feed. Aborting"); + bts_assert(false); + } + } obs(out_dir); + + observe_channel(file, obs); + return 0; } } // namespace bts::spartan::mdp3 diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h index 3888a81ca..5fb24f39c 100644 --- a/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h +++ b/src/server/sparkd/cmds/spartan/md/mdp3/utils/mdp3_utils.h @@ -3,9 +3,14 @@ #include #include #include +#include namespace bts::spartan::mdp3 { +class IChannelObserver; + +// Details the ip/port used for each of the incremental a/b, snapshot +// and instrument feeds in a pcap. struct FeedMap { struct Feed { std::string ip = ""; @@ -16,19 +21,39 @@ struct FeedMap { Feed snapshot; Feed instrument; operator bool() const noexcept { - return - incremental[0].port && - incremental[1].port && - instrument.port && - snapshot.port; + return incremental[0].port && incremental[1].port && instrument.port && + snapshot.port; } }; std::ostream &operator<<(std::ostream &o, FeedMap const &fm); -FeedMap guess_feed_map(std::string const &pcap_path); -bool slim_down_pcap(std::string const&in, std::string const &out); -void cme_ts_to_date_str(uint64_t cme_ts, std::stringstream *out); -void cme_ts_to_time_str(uint64_t cme_ts, std::stringstream *out); +// Examine the passed pcap and determine, if possible, the ip/port +// associated with each of the following feeds: +// - Incremental A +// - Incremental B +// - Snapshot +// - Instrument +FeedMap guess_feed_map(std::string const &pcap) ; +// Examine the passed pcap and throw away redundant packets. Including: +// - Instrument and Snapshoft feed packets after the initial recovery +// - Feed A/Feed B redundant packets +int compress(std::string const&pcap_in, std::string const &pcap_out); + +// Convert the pcap passed to json and output it to standard out (this +// is typically only usefull for debugging) +int to_json(std::string const&pcap); + +// Export the passed pcap to a set of tables in CSV format. The +// following tables are generated: +// - events.csv : one row per event in the pcap +// - event_items.csv : one row per item in an event. Event items +// include: order changes, fills and deduced order +// - securities.csv : one row per security present in the pcap +int to_csv(std::string const &pcap, std::string const &out_dir); + +// Observe the pcap specified, invoking the observer for each event on +// it +void observe_channel(std::string const &pcap, IChannelObserver &obs) ; } // namespace bts::spartan::mdp3 From c43ec4a56d2260cba8eed9916b8b3cec4b87f58e Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Thu, 20 Aug 2020 10:43:58 -0400 Subject: [PATCH 5/5] Added script to easily compress pcaps. --- .../spartan/md/mdp3/scripts/compress_pcap.sh | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100755 src/server/sparkd/cmds/spartan/md/mdp3/scripts/compress_pcap.sh diff --git a/src/server/sparkd/cmds/spartan/md/mdp3/scripts/compress_pcap.sh b/src/server/sparkd/cmds/spartan/md/mdp3/scripts/compress_pcap.sh new file mode 100755 index 000000000..941c995d6 --- /dev/null +++ b/src/server/sparkd/cmds/spartan/md/mdp3/scripts/compress_pcap.sh @@ -0,0 +1,17 @@ +#!/bin/bash +DIR="$(dirname "$(readlink -f "$0")")" +SRC_ROOT=$DIR/../../../../../../../../ +BUILD_ROOT=`readlink -f $SRC_ROOT/build/ninja_release/server` + +IN=$1 +PIPE=$(mktemp -u /tmp/spartan-compress-pipe.XXXXXX.pcap) +mkfifo $PIPE +xz -zc -T0 $PIPE > $IN.xz & (cd $BUILD_ROOT && ./sparkd spartan compress $IN $PIPE) +wait + + + + + + +