From fd015577b218a23b48b71bee3909c990735ee4f7 Mon Sep 17 00:00:00 2001 From: Mohammad Arham Date: Wed, 26 Feb 2025 02:49:41 +0000 Subject: [PATCH] MD working on my laptop --- .../api/md/DatabentoMarketDataConfig.proto | 1 + src/lib/logging/Sink.cpp | 3 +- src/lib/persistence/IDGenerator.cpp | 2 +- .../md/databento/DatabentoDataHandler.cpp | 472 ++++++++++++------ 4 files changed, 335 insertions(+), 143 deletions(-) diff --git a/src/lib/api/md/DatabentoMarketDataConfig.proto b/src/lib/api/md/DatabentoMarketDataConfig.proto index 685589930..6f13b3ce4 100644 --- a/src/lib/api/md/DatabentoMarketDataConfig.proto +++ b/src/lib/api/md/DatabentoMarketDataConfig.proto @@ -15,4 +15,5 @@ message DatabentoMarketDataConfig { string dataset = 70; uint32 filter_securities_upto_n_months= 80; bool load_reference_data = 90; + uint32 debug_sec = 100; } diff --git a/src/lib/logging/Sink.cpp b/src/lib/logging/Sink.cpp index d37e7821d..ee56efb04 100644 --- a/src/lib/logging/Sink.cpp +++ b/src/lib/logging/Sink.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -94,7 +95,7 @@ std::ifstream::pos_type filesize(std::string const &filename) { Sink file_sink(LoggingConfig const &cfg) { static std::ofstream stream; static uint64_t bytes_written = 0; - const auto max_sz = 120 * 1024 * 1024; + const uintmax_t max_sz = 1024 * 1024 * 1024 ; auto f = formatter(cfg); auto path = log_path(); diff --git a/src/lib/persistence/IDGenerator.cpp b/src/lib/persistence/IDGenerator.cpp index 7cf38724e..86e0848ce 100644 --- a/src/lib/persistence/IDGenerator.cpp +++ b/src/lib/persistence/IDGenerator.cpp @@ -73,7 +73,7 @@ std::optional IDGenerator::get_id( return std::optional(rowid); } else { if (add_if_new) { - auto all = me->kv_store->retrieve_all(); + // auto all = me->kv_store->retrieve_all(); auto new_id = me->kv_store->insert(ns, key, ""); LOG(Gen, Diag, "IDGenerator::get_id ns: {} key: id: {}", ns, key, new_id); diff --git a/src/server/sparkd/md/databento/DatabentoDataHandler.cpp b/src/server/sparkd/md/databento/DatabentoDataHandler.cpp index d18d59b73..5a16d6226 100644 --- a/src/server/sparkd/md/databento/DatabentoDataHandler.cpp +++ b/src/server/sparkd/md/databento/DatabentoDataHandler.cpp @@ -1,5 +1,6 @@ #include "DatabentoDataHandler.h" #include "databento/datetime.hpp" +#include "databento/dbn_encoder.hpp" #include "databento/enums.hpp" #include "databento/exceptions.hpp" #include "databento/live_blocking.hpp" @@ -7,6 +8,7 @@ #include "databento/record.hpp" #include "databento/timeseries.hpp" #include "lib/api/domain/Venue.pb.h" +#include "lib/api/md/MarketDataConfig.pb.h" #include "lib/config/config.h" #include "lib/config/protos/system_config.pb.h" #include "lib/core/TimeStamp.h" @@ -22,14 +24,21 @@ #include "lib/utils/TimeStamp.h" #include "lib/utils/bts_assert.h" #include "lib/utils/bts_chrono.h" +#include "lib/utils/datetime.h" #include "lib/utils/helper_macros.h" +#include #include #include +#include #include #include #include #include +#include #include +#include +#include +#include #include namespace bts::md::DatabentoHandler { @@ -61,7 +70,87 @@ static SecurityType parse_sec_type(std::string_view str) { } return SEC_TYPE(UNSPECIFIED); } +void update_file( + const std::string &key, + const std::string &dataset, + const std::vector &parent_symbols, + const uint time_to_run, + std::string file_path) { + auto client = + databento::LiveBuilder{} + .SetKey(key) + .SetDataset(dataset) + .SetUpgradePolicy(databento::VersionUpgradePolicy::UpgradeToV2) + .BuildBlocking(); + + client.Subscribe( + parent_symbols, databento::Schema::Definition, databento::SType::Parent, + databento::UnixNanos{}); + // We start streaming + databento::Metadata metadata = client.Start(); + { + // We open a file for writing and encode the metadata + databento::OutFileStream out_file{file_path}; + databento::DbnEncoder encoder{metadata, &out_file}; + // Wait for at least one record and 5 seconds before closing the connection + const std::chrono::seconds timeout{time_to_run}; + const auto start = std::chrono::steady_clock::now(); + while (auto *record = client.NextRecord(timeout)) { + encoder.EncodeRecord(*record); + if (std::chrono::steady_clock::now() - start >= timeout) { + break; + } + } + } + return; +} +void log_time_statistics( + const std::vector>> + &all_times) { + std::unordered_map> subpart_times; + + // Collect all timing values per subpart + for (const auto &entry : all_times) { + for (const auto &[time, label] : entry) { + subpart_times[label].push_back(time); + } + } + + // Function to compute statistics + auto compute_statistics = [](std::vector &values) + -> std::tuple { + if (values.empty()) + return std::make_tuple(0.0, 0.0, 0, 0, 0, 0, 0); + + std::sort(values.begin(), values.end()); + + double sum = std::accumulate(values.begin(), values.end(), 0.0); + double avg = sum / values.size(); + + double sq_sum = + std::inner_product(values.begin(), values.end(), values.begin(), 0.0); + double stddev = std::sqrt(sq_sum / values.size() - avg * avg); + + auto percentile = [&](double p) -> uint64_t { + size_t idx = static_cast(p * (values.size() - 1)); + return values[idx]; + }; + + return std::make_tuple( + avg, stddev, percentile(0.00), percentile(0.25), percentile(0.50), + percentile(0.75), percentile(1.00)); + }; + + // Compute and log statistics + for (auto &[label, times] : subpart_times) { + auto [avg, stddev, p0, p25, p50, p75, p100] = compute_statistics(times); + LOG(md, Sys, + "Subpart: {}, Avg: {:.2f} ns, Std: {:.2f} ns, P0: {} ns, P25: {} ns, " + "P50: {} ns, P75: {} ns, P100: {} ns", + label, avg, stddev, p0, p25, p50, p75, p100); + } +} void DatabentoDatahandler::run( bool use_file, std::shared_ptr listener, @@ -74,59 +163,71 @@ void DatabentoDatahandler::run( const uint filter_securities_upto_n_months, const bool load_reference_data, const std::chrono::duration sleep_duration) { - + uint DEBUG_SEC_ID = 0; + if (venue == api::domain::VENUE_CBOE) + DEBUG_SEC_ID = config::get() + .cboe() + .at(0) + .databento_settings() + .debug_sec(); auto sleep_duration_updated = sleep_duration; - + std::vector>> all_times; + std::unordered_map sec_id_map; if (!use_file) { sleep_duration_updated = std::chrono::duration< long double>::zero(); // Set to zero for live data } - auto process_security = [&](const databento::Record &record) { - const auto &msg = record.Get(); - std::string id = remove_spaces(msg.RawSymbol()); - std::string symbol; - + auto sec_filter = [&](const core::TimeStamp expiration_time, + const std::string &symbol, + const api::domain::Venue &venue, uint strike) { + uint months = filter_securities_upto_n_months; switch (venue) { case api::domain::Venue::VENUE_CBOE: { - symbol = remove_spaces( - std::string(msg.underlying.data(), msg.underlying.size())); + if (strike < 3800 || strike > 8000) { + return false; + } + if (symbol == "SPX") + months = 6; + else if (symbol == "SPXW") + months = 1; break; } case api::domain::Venue::VENUE_GLBX: - if (id.length() > 5) - return databento::KeepGoing::Continue; - symbol = id.substr(0, 2); - // sec.security_common.cpp = msg.unit_of_measure_qty; - - break; + return true; default: bts_assert_msg(false, "Exchange not supported on databento"); - return databento::KeepGoing::Stop; + } + + auto duration = months * 32 * 24 * 60 * 60; + return expiration_time.seconds() < + bts::core::TimeStamp::now().seconds() + duration; + }; + auto process_security = [&](const databento::Record &record) -> bool { + const auto &msg = record.Get(); + const auto exp_nanos = msg.expiration; + std::string exp_string = databento::ToIso8601(exp_nanos); + const auto expiration_time = + bts::core::TimeStamp::from_iso_string(exp_string); + if (!sec_filter( + expiration_time, msg.Underlying(), venue, + msg.strike_price / 1000000000)) { + return false; } bts::domain::Security sec; sec.security_common = domain::SecurityCommon(); sec.security_common.venue = venue; sec.security_common.exchange_sec_id = msg.hd.instrument_id; sec.security_common.desc = msg.RawSymbol(); - sec.security_common.symbol = msg.Asset(); + sec.security_common.symbol = msg.Underlying(); sec.security_common.asset = msg.Asset(); sec.security_common.group = msg.Group(); sec.security_common.min_price_increment = 0.01; sec.security_common.min_quantity = 0.01; sec.security_common.min_quantity_increment = 0.01; sec.security_common.currency = {msg.currency.data(), msg.currency.size()}; - // sec.security_common.cpp = msg.hd. const SecurityType sec_type = parse_sec_type({msg.security_type.data(), msg.security_type.size()}); - const auto exp_nanos = msg.expiration; - std::string exp_string = databento::ToIso8601(exp_nanos); - const auto expiration_time = - bts::core::TimeStamp::from_iso_string(exp_string); - auto duration = filter_securities_upto_n_months*30*24*60*60; - if( expiration_time.seconds() >= bts::core::TimeStamp::now().seconds() + duration){ - return databento::KeepGoing::Continue; - } switch (sec_type) { case SEC_TYPE(FUTURE): @@ -134,11 +235,10 @@ void DatabentoDatahandler::run( break; case SEC_TYPE(OPTION): { auto call_put = CallPut::PUT; - if (msg.instrument_class == 'C') { + if (msg.instrument_class == 'C') call_put = CallPut::CALL; - } else { + else bts_assert(msg.instrument_class == 'P'); - } sec.security.emplace( expiration_time, bts::domain::Price(msg.strike_price, -9), call_put); @@ -147,36 +247,62 @@ void DatabentoDatahandler::run( default: bts_assert_msg( false, "Only futures and options supported on databento"); - return databento::KeepGoing::Stop; } - *sec.security_common.id = sec_id_store->get_or_add( venue, sec_type, std::to_string(msg.hd.instrument_id)); listener->on_securities({&sec}); - return databento::KeepGoing::Continue; + sec_id_map.insert({msg.hd.instrument_id, sec.security_common.id}); + return true; + }; + auto debug_log = [&](const databento::Mbp1Msg &msg) { + if (DEBUG_SEC_ID != msg.hd.instrument_id) + return; + const double denom = 1000000000; + // auto delta = std::to_string(std::chrono::duration(msg.ts_in_delta).count()); + auto seq_num = msg.sequence; + auto ap = msg.levels[0].ask_px / denom; + auto bp = msg.levels[0].bid_px / denom; + auto as = msg.levels[0].ask_sz; + auto bs = msg.levels[0].bid_sz; + LOG(md, Sys, "ID: {}, seq_num: {}, B_P: {}, B_S: {}, A_P: {}, A_S: {}", + msg.hd.instrument_id, seq_num, bp, bs, ap, as); }; auto process_bbo = [&](const databento::Record &record) { const auto &msg = record.Get(); + debug_log(msg); + + // std::vector>& times = all_times.emplace_back(); + // times.reserve(8); + // return databento::KeepGoing::Continue; //only added so the same functions work with the threaded builder, not really need in the blocking version // The security type to is needed to get the id. Since the sec type isn't known, // check for an id using both types (OPTION and FUTURE). This is safe to do since // options and futures never have common names (instrument ids). - const auto name = std::to_string(msg.hd.instrument_id); - auto sec_id_opt = - sec_id_store->get_id(venue, SEC_TYPE(OPTION), name, false); - if (!sec_id_opt.has_value()) { - sec_id_opt = - sec_id_store->get_id(venue, SEC_TYPE(FUTURE), name, false); - if (!sec_id_opt.has_value()) { - return databento::KeepGoing::Continue; - } - } + // auto current = bts::datetime::unix_nano_now(); + // auto prev = current; + // times.push_back({current-prev,"Start Process bbo"}); + + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"MISC to check log time"}); + if (!sec_id_map.contains(msg.hd.instrument_id)) + return databento::KeepGoing::Continue; + bts::domain::SecurityID sec_id = sec_id_map.at(msg.hd.instrument_id); + + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"Sec_ID done"}); + + // sleep_for(sleep_duration_updated); + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"Sleep done"}); - sleep_for(sleep_duration_updated); - bts::domain::SecurityID sec_id = - bts::domain::SecurityID(sec_id_opt.value()); domain::Book book; book.set_security_id(sec_id); + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"Empty Book Made"}); auto &bids = book.bids(); auto &asks = book.asks(); @@ -186,130 +312,194 @@ void DatabentoDatahandler::run( asks.begin()->price = bts::domain::Price(msg.levels[0].ask_px, -9); asks.begin()->total_quantity = bts::domain::Quantity(msg.levels[0].ask_sz); + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"Complete book done"}); auto recv_time = bts::core::TimeStamp::from_iso_string( databento::ToIso8601(msg.ts_recv)); + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"Time converted"}); + listener->on_book( book, utils::TimeStamp{datetime::ptime_to_timestamp(recv_time.to_ptime())}); - return databento::KeepGoing::Continue; + // prev = current; + // current = bts::datetime::unix_nano_now(); + // times.push_back({current-prev,"On book done"}); + + return databento::KeepGoing:: + Continue; //only added so the same functions work with the threaded builder, not really need in the blocking version }; + auto process_trades = [&](const databento::Record &record) { const auto &msg = record.Get(); // The security type to is needed to get the id. Since the sec type isn't known, // check for an id using both types (OPTION and FUTURE). This is safe to do since // options and futures never have common names (instrument ids). - const auto name = std::to_string(msg.hd.instrument_id); - auto sec_id_opt = - sec_id_store->get_id(venue, SEC_TYPE(OPTION), name, false); - if (!sec_id_opt.has_value()) { - sec_id_opt = - sec_id_store->get_id(venue, SEC_TYPE(FUTURE), name, false); - if (!sec_id_opt.has_value()) { - return databento::KeepGoing::Continue; - } - } + if (!sec_id_map.contains(msg.hd.instrument_id)) + return databento::KeepGoing::Continue; + bts::domain::SecurityID sec_id = sec_id_map.at(msg.hd.instrument_id); - sleep_for(sleep_duration_updated); - bts::domain::SecurityID sec_id = - bts::domain::SecurityID(sec_id_opt.value()); + // sleep_for(sleep_duration_updated); domain::TradeRecord trade; trade.trade_price = bts::domain::Price(msg.price, -9); trade.trade_quantity = bts::domain::Quantity(msg.size); - trade.sec_id = sec_id; - switch(msg.side){ - case databento::Side::Ask: - trade.agg_side = domain::AggressorSide::Sell; - break; - case databento::Side::Bid: - trade.agg_side = domain::AggressorSide::Buy; - break; - case databento::Side::None: - trade.agg_side = domain::AggressorSide::None; - break; + trade.sec_id = sec_id; + switch (msg.side) { + case databento::Side::Ask: + trade.agg_side = domain::AggressorSide::Sell; + break; + case databento::Side::Bid: + trade.agg_side = domain::AggressorSide::Buy; + break; + case databento::Side::None: + trade.agg_side = domain::AggressorSide::None; + break; } trade.time_stamp = bts::core::TimeStamp::from_iso_string( databento::ToIso8601(msg.ts_recv)); std::vector trade_ptrs; trade_ptrs.push_back(&trade); listener->on_trades(trade_ptrs); - - return databento::KeepGoing::Continue; + + return databento::KeepGoing:: + Continue; //only added so the same functions work with the threaded builder, not really need in the blocking version }; if (use_file) { auto client = databento::HistoricalBuilder{}.SetKey(key).Build(); databento::DbnFileStore dbn_file_store(securities_path); - dbn_file_store.Replay(process_security); + // dbn_file_store.Replay(process_security); // fix this databento::DbnFileStore dbn_file_store2(books_path); dbn_file_store2.Replay(process_bbo); - }else { - bts_assert(dataset!=""); - // auto client = databento::LiveBuilder{} - // .SetKey(key) - // .SetDataset(dataset) - // .BuildThreaded(); - auto client = databento::LiveBlocking{ - databento::ILogReceiver::Default(), - key, - dataset, - true, - databento::VersionUpgradePolicy::UpgradeToV2, - {} - }; - //hardcoding for now will update later - std::vector symbols; - switch (venue) { - case api::domain::VENUE_CBOE: symbols= {"SPX.OPT","SPXW.OPT"}; break; - case api::domain::VENUE_GLBX: symbols= {"ES.FUT"}; break; - default:bts_assert_msg(false, "ONLY GLBX AND CBOE SUPPORTED FOR NOW"); - } - if(load_reference_data) - client.Subscribe(symbols, databento::Schema::Definition, databento::SType::Parent,databento::UnixNanos{}); - else client.Subscribe(symbols, databento::Schema::Definition, databento::SType::Parent); - client.Subscribe(symbols, databento::Schema::Mbp1, databento::SType::Parent); - client.Subscribe(symbols, databento::Schema::Trades, databento::SType::Parent); - client.Start(); - while (true) { - try { - auto* record = client.NextRecord(std::chrono::seconds{500}); - if (record == nullptr) { - LOG(md, Error, "Timed out waiting for data"); - break; - } - if (record->Holds()) { - process_bbo(*record); - } - if (record->Holds()) { - process_security(*record); - } - if (record->Holds()) { - process_trades(*record); - } - } catch (const databento::TcpError& error) { - std::string err = error.what(); - LOG(md, Error, "Caught TCP error: {} \nAttempting reconnect\n",err); - client.Reconnect(); - } catch(const databento::DbnResponseError& err){ - std::string msg = err.Message(); - std::string what = err.what(); - LOG(md, Error, "Caught DbnResponseError what: {} ,msg:{} \nShutting down\n",msg, what); - client.Stop(); - // bts_assert(false); - } - catch(const databento::Exception& excp){ - std::string err = excp.Message(); - std::string err2 = excp.what(); - LOG(md, Error, "Caught unknown dadtabento::exception what: {}, msg: {} \nShutting down\n",err, err2); - client.Stop(); - // bts_assert(false); - }catch (const std::exception& exc) { - std::string err = exc.what(); - LOG(md, Error, "Caught unknown exception: {} \nShutting down\n",err); - client.Stop(); - // bts_assert(false); - } - - } + } else { + bts_assert(dataset != ""); + + //hardcoding for now will update later + std::vector symbols; + switch (venue) { + case api::domain::VENUE_CBOE: + symbols = {"SPX.OPT", "SPXW.OPT"}; + break; + case api::domain::VENUE_GLBX: + symbols = {"ES.FUT"}; + break; + default: + bts_assert_msg(false, "ONLY GLBX AND CBOE SUPPORTED FOR NOW"); + } + //ocassionaly run security writer to update security dbn + if (!boost::filesystem::exists(securities_path) || load_reference_data) { + update_file(key, dataset, symbols, 15 * 60, securities_path); + } + + //regular flow + //read from security dbn, filter contracts that we need and subscribe to those in batches of two thousand + LOG(md, Info, "starting loading symbols"); + databento::DbnFileStore store{securities_path}; + std::vector> all_sec; + + all_sec.emplace_back(); + all_sec.back().reserve(2000); + size_t total_count = 0; + + while (auto *record = store.NextRecord()) { + if (auto *def = record->GetIf()) { + std::string s = def->RawSymbol(); + if (process_security(*record)) { + ++total_count; + // Check if the last vector is full + if (all_sec.back().size() == 2000) { + all_sec.emplace_back(); + all_sec.back().reserve(2000); + LOG(md, Info, "{} symbols added", total_count); + } + all_sec.back().push_back(std::move(s)); // Move to avoid copying + } + } + } + // std::ostringstream output; + + // for (const auto& sec_group : all_sec) { + // for (size_t i = 0; i < sec_group.size(); ++i) { + // if (i > 0) output << ", "; + // output << sec_group[i]; + // } + // output << '\n'; // Newline after each group + // } + + // // Store the final output in a stringls + + // std::string final_output = output.str(); + // size_t size = all_sec.size(); + LOG(md, Info, "total {} secs loaded", total_count); + + bool first = true; + auto client = databento::LiveBlocking{ + databento::ILogReceiver::Default(), key, dataset, true, + databento::VersionUpgradePolicy::UpgradeToV2, {}}; + for (std::vector vec : all_sec) { + client.Subscribe( + vec, databento::Schema::Mbp1, databento::SType::RawSymbol); + client.Subscribe( + vec, databento::Schema::Trades, databento::SType::RawSymbol); + } + + client.Start(); + while (true) { + try { + auto *record = client.NextRecord(std::chrono::seconds{500}); + if (first) { + LOG(md, Info, "first record"); + first = false; + } + if (record == nullptr) { + LOG(md, Error, "Timed out waiting for data"); + break; + } + if (record->Holds()) { + process_bbo(*record); + } + if (all_times.size() == 1001) { + log_time_statistics(all_times); + client.Stop(); + } + // if (record->Holds()) { + // process_security(*record); + // } + if (record->Holds()) { + process_trades(*record); + } + } catch (const databento::TcpError &error) { + std::string err = error.what(); + LOG(md, Error, "Caught TCP error: {} \nAttempting reconnect\n", + err); + client.Reconnect(); + } catch (const databento::DbnResponseError &err) { + std::string msg = err.Message(); + std::string what = err.what(); + LOG(md, Error, + "Caught DbnResponseError what: {} ,msg:{} \nShutting down\n", + msg, what); + client.Stop(); + // bts_assert(false); + } catch (const databento::Exception &excp) { + std::string err = excp.Message(); + std::string err2 = excp.what(); + LOG(md, Error, + "Caught unknown dadtabento::exception what: {}, msg: {} " + "\nShutting down\n", + err, err2); + client.Stop(); + // bts_assert(false); + } catch (const std::exception &exc) { + std::string err = exc.what(); + LOG(md, Error, "Caught unknown exception: {} \nShutting down\n", + err); + client.Stop(); + // bts_assert(false); + } + } } }