Files
spark/src/server/sparkd/md/databento/DatabentoDataHandler.cpp
T

220 lines
8.2 KiB
C++

#include "DatabentoDataHandler.h"
#include "databento/datetime.hpp"
#include "databento/enums.hpp"
#include "databento/live_blocking.hpp"
#include "databento/log.hpp"
#include "databento/timeseries.hpp"
#include "lib/api/domain/Venue.pb.h"
#include "lib/config/config.h"
#include "lib/config/protos/system_config.pb.h"
#include "lib/domain/Book.h"
#include "lib/domain/Quantity.h"
#include "lib/domain/Security.h"
#include "lib/domain/SecurityID.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/logging/logging.h"
#include "lib/utils/TimeStamp.h"
#include "lib/utils/bts_assert.h"
#include "lib/utils/bts_chrono.h"
#include "lib/utils/helper_macros.h"
#include <cassert>
#include <chrono>
#include <databento/constants.hpp>
#include <databento/historical.hpp>
#include <databento/live.hpp>
#include <optional>
#include <string>
namespace bts::md::DatabentoHandler {
std::string remove_spaces(const std::string_view& str) {
std::string result;
result.reserve(str.size()); // Reserve space for better performance
for (char c : str) {
if (!isspace(c)) {
result += c;
}
}
return result;
}
void DatabentoDatahandler::run(
bool use_file,
std::shared_ptr<IMarketDataListener> listener,
std::shared_ptr<persistence::IDGenerator> sec_id_store,
bts::api::domain::Venue venue,
const std::string &securities_path,
const std::string &books_path,
const std::string &key,
const std::string &dataset,
const std::chrono::duration<long double> sleep_duration) {
auto sleep_duration_updated = sleep_duration;
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<databento::InstrumentDefMsg>();
std::string id = remove_spaces(msg.RawSymbol());
std::string symbol;
switch (venue) {
case api::domain::Venue::VENUE_CBOE:{
symbol = remove_spaces(std::string(msg.underlying.data(),msg.underlying.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);
// if(expiration_time.seconds() < expiration_time.now().seconds() || expiration_time.seconds() > expiration_time.now().seconds() + 8*30*24*60){
// return databento::KeepGoing::Continue;
// }
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;
default:
bts_assert_msg(false, "Exchange not supported on databento");
return databento::KeepGoing::Stop;
}
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
venue, std::to_string(msg.hd.instrument_id))};
bts::domain::Security sec;
sec.security_common = domain::SecurityCommon();
sec.security_common.venue = venue;
sec.security_common.id = sec_id;
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.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 std::string_view 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);
if (sec_type.find("OPT") != std::string::npos) {
auto call_put = api::domain::CallPut::PUT;
if(msg.instrument_class == 'C' ){
call_put=api::domain::CallPut::CALL;
}
else{
bts_assert(msg.instrument_class == 'P');
}
sec.security.emplace<bts::domain::OptionSecurity>(
expiration_time, bts::domain::Price(msg.strike_price, -9),call_put);
} else if (sec_type.find("FUT") != std::string::npos) {
sec.security.emplace<bts::domain::FutureSecurity>(expiration_time);
} else {
bts_assert_msg(false, "Only futures and options supported on databento");
return databento::KeepGoing::Stop;
}
listener->on_securities({&sec});
return databento::KeepGoing::Continue;
};
auto process_bbo = [&](const databento::Record &record) {
const auto &msg = record.Get<databento::Mbp1Msg>();
auto sec_id_opt = sec_id_store->get_id(
venue, std::to_string(msg.hd.instrument_id), false);
if (!sec_id_opt.has_value())
return databento::KeepGoing::Continue;
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);
auto &bids = book.bids();
auto &asks = book.asks();
bids.begin()->price = bts::domain::Price(msg.levels[0].bid_px, -9);
bids.begin()->total_quantity =
bts::domain::Quantity(msg.levels[0].bid_sz);
asks.begin()->price = bts::domain::Price(msg.levels[0].ask_px, -9);
asks.begin()->total_quantity =
bts::domain::Quantity(msg.levels[0].ask_sz);
auto recv_time = bts::core::TimeStamp::from_iso_string(
databento::ToIso8601(msg.ts_recv));
listener->on_book(
book,
utils::TimeStamp{datetime::ptime_to_timestamp(recv_time.to_ptime())});
return databento::KeepGoing::Continue;
};
if (use_file) {
auto client = databento::HistoricalBuilder{}
.SetKey(key)
.Build();
databento::DbnFileStore dbn_file_store(securities_path);
dbn_file_store.Replay(process_security);
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::Upgrade,
{}
};
//hardcoding for now will update later
switch (venue) {
case api::domain::VENUE_CBOE:
client.Subscribe({"SPX.OPT","SPXW.OPT"}, databento::Schema::Definition, databento::SType::Parent);
client.Subscribe({"SPX.OPT","SPXW.OPT"}, databento::Schema::Mbp1, databento::SType::Parent);
break;
case api::domain::VENUE_GLBX:
client.Subscribe({"ES.FUT"}, databento::Schema::Definition, databento::SType::Parent);
client.Subscribe({"ES.FUT"}, databento::Schema::Mbp1, databento::SType::Parent);
break;
default:
bts_assert_msg(false, "ONLY GLBX AND CBOE SUPPORTED FOR NOW");
}
client.Start();
while (true) {
try {
auto* record = client.NextRecord(std::chrono::seconds{5});
if (record == nullptr) {
LOG(md, Error, "Timed out waiting for data");
break;
}
if (auto* bbo = record->GetIf<databento::Mbp1Msg>()) {
process_bbo(*record);
}
if (auto* def = record->GetIf<databento::InstrumentDefMsg>()) {
process_security(*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 std::exception& exc) {
std::string err = exc.what();
LOG(md, Error, "Caught unknown exception: {} \nShutting down\n",err);
client.Stop();
}
}
}
}
} // namespace bts::md::DatabentoHandler