refactor: Normalize sec key indexing for new (domain) md sources

This is part of a larger effort to unify the way we index securities in order
to generate unique ids. Older md sources (e.g., MDP3Listener) use
SecurityIDRecorder to generate ids, which uses a different database and
different key-string formatting than the IDGenerator used by the newer md
sources (e.g., GeneralMarketDataListener and various ccapi-based sources).
This commit is contained in:
John Colvin committed 2024-10-14 15:51:44 +00:00
1 parent 98f85b90ee
commit 9d08ddfa53
31 files changed
+401 -186

No files matched your search

@@ -2,6 +2,8 @@
#include "domain/future_security.h"
#include "domain/protobufs/aggressor_side.pb.h"
#include "domain/protobufs/call_put.pb.h"
#include "domain/protobufs/security_type.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/protobufs/venue.h"
#include "domain/security.h"
#include "domain/security_id.h"
@@ -145,13 +147,19 @@ struct PyMarketDataSubscription::PImpl : private py_interop::MdSink {
trade_ptrs_.clear();
}
SecurityID get_sec_id_(const string &venue_name, const string &sec_name) {
SecurityID get_sec_id_(
const string &venue_name,
const string &type_name,
const string &sec_name) {
domain::protobufs::Venue venue;
// Although an overload of 'get_id' accepts a string, we parse `venue_name` to the enum to
// normalize different spellings of the same venue. For example, "deribt", "DERIBIT", and
// "VENUE_deribit" all represent the VENUE_DERIBIT enum (see `venue_parse_smart` for details).
bts_assert(domain::protobufs::venue_parse_smart(venue_name, &venue));
auto sec_id = sec_id_store_->get_id(venue, sec_name, true);
domain::protobufs::SecurityType type;
bts_assert(
domain::protobufs::security_type_parse_smart(type_name, &type));
auto sec_id = sec_id_store_->get_id(venue, type, sec_name, true);
bts_assert_msgf(
sec_id, "Failed to get security id for py_book. venue: {}; name: {}",
venue, sec_name);
@@ -170,7 +178,8 @@ struct PyMarketDataSubscription::PImpl : private py_interop::MdSink {
LOG(md, Error, "Failed to parse venue from '{}'", py_sec.venue());
return std::nullopt;
}
sec_comm.id = get_sec_id_(py_sec.venue(), py_sec.exchange_id());
sec_comm.id =
get_sec_id_(py_sec.venue(), py_sec.type(), py_sec.exchange_id());
sec_comm.exchange_sec_id = py_sec.exchange_id();
sec_comm.currency = py_sec.currency();
sec_comm.asset = py_sec.asset();
@@ -205,7 +214,9 @@ struct PyMarketDataSubscription::PImpl : private py_interop::MdSink {
}
void to_bts_trade_(const PyTrade &source, domain::TradeRecord &dest) {
dest.sec_id = get_sec_id_(source.venue(), source.exchange_security_id());
dest.sec_id = get_sec_id_(
source.venue(), source.security_type(),
source.exchange_security_id());
dest.time_stamp = core::TimeStamp::from_nanos(source.timestamp());
dest.agg_side = source.aggressor_side().starts_with('B') ||
source.aggressor_side().starts_with('b')
@@ -231,8 +242,9 @@ struct PyMarketDataSubscription::PImpl : private py_interop::MdSink {
void to_book_(const PyBook &source, domain::Book &dest) {
to_book_side_(source.bids(), dest.bids());
to_book_side_(source.asks(), dest.asks());
dest.set_security_id(
get_sec_id_(source.venue(), source.exchange_security_id()));
dest.set_security_id(get_sec_id_(
source.venue(), source.security_type(),
source.exchange_security_id()));
}
};
@@ -12,18 +12,19 @@ namespace bts::md::binance {
using bts::domain::SecurityID;
using bts::domain::SecurityMarketDataStatistics;
using std::pair;
using bts::domain::protobufs::SecurityType;
using std::string;
using std::tuple;
using std::vector;
#define VENUE_NAME (Venue_Name(Venue::BINANCE))
struct BinancePriceStatisticsAdaptor::PImpl {
vector<pair<string, SecurityID>> securities;
vector<tuple<SecurityType, string, SecurityID>> securities;
IMarketDataListener *listener;
SecurityID get_sec_id(const string &sec_desc) const {
for (const auto &[desc, id] : securities) {
for (const auto &[type, desc, id] : securities) {
if (desc == sec_desc) {
return id;
}
@@ -36,7 +37,8 @@ struct BinancePriceStatisticsAdaptor::PImpl {
};
BinancePriceStatisticsAdaptor::BinancePriceStatisticsAdaptor(
vector<pair<string, SecurityID>> securities, IMarketDataListener *listener)
vector<tuple<SecurityType, string, SecurityID>> securities,
IMarketDataListener *listener)
: me_(std::make_unique<PImpl>()) {
bts_assert(listener != nullptr);
me_->securities = std::move(securities);
@@ -1,9 +1,11 @@
#pragma once
#include "domain/protobufs/security_type.pb.h"
#include "domain/security_id.h"
#include "sparkd/md/ccapi/ICCApiMessageHandler.h"
#include <string>
#include <tuple>
#include <utility>
#include <vector>
@@ -20,7 +22,10 @@ namespace bts::md::binance {
class BinancePriceStatisticsAdaptor : public ICCApiMessageHandler {
public:
BinancePriceStatisticsAdaptor(
std::vector<std::pair<std::string, domain::SecurityID>> securities,
std::vector<std::tuple<
domain::protobufs::SecurityType,
std::string,
domain::SecurityID>> securities,
IMarketDataListener *listener);
~BinancePriceStatisticsAdaptor();
@@ -49,6 +49,7 @@ using std::vector;
#define _WARN(...) _LOG(Warn, __VA_ARGS__)
#define _ERROR(...) _LOG(Error, __VA_ARGS__)
#define VENUE Venue::VENUE_BINANCE
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE
#define BINANCE_MSG_TYPE_NAME(x) \
@@ -156,7 +157,8 @@ struct BinanceSecurityRequestor::PImpl {
for (auto &sec : added_secs) {
// Since the ids haven't been set yet, we should expect them to be 0
bts_assert(sec.id().value() == 0);
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec.desc())};
SecurityID sec_id{
sec_id_store->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
@@ -38,6 +38,7 @@ using bts::api::md::BinanceMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::domain::protobufs::Venue_Name;
using bts::http::QueryParams;
@@ -50,6 +51,7 @@ using std::unique_ptr;
using std::unordered_map;
using std::vector;
#define VENUE Venue::VENUE_BINANCE
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE
@@ -123,14 +125,15 @@ static CCApiCorrelationID mk_stats_corr_id(const string &desc) {
}
static ccapi::Request mk_stats_req(
const vector<string> &sec_descs, uint32_t batch_id) {
const vector<std::pair<SecurityType, string>> &sec_descs,
uint32_t batch_id) {
const auto corr_id = mk_stats_corr_id(FMT("BATCH_{}", batch_id));
ccapi::Request req{
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, CCAPI_VENUE_NAME};
req.setCorrelationId(corr_id.to_string());
auto quoted_sec_descs =
sec_descs |
ranges::views::transform([](const auto &s) { return "\"" + s + "\""; });
sec_descs | ranges::views::transform(
[](const auto &s) { return "\"" + s.second + "\""; });
const string symbols_query_arg = FMT_JOIN(quoted_sec_descs, ",");
req.appendParam(
{{CCAPI_HTTP_PATH, BINANCE_PRICE_STATS_PATH},
@@ -213,16 +216,18 @@ struct BinanceSubscription::PImpl {
sec_requestor.request();
}
DepthHandler &mk_depth_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
DepthHandler &mk_depth_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
depth_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert(is_new);
return it->second;
}
TickerHandler &mk_ticker_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
TickerHandler &mk_ticker_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
ticker_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -231,24 +236,25 @@ struct BinanceSubscription::PImpl {
}
StatsHandler &mk_stats_handler(
const vector<string> &sec_descs, uint32_t hnd_id) {
vector<pair<string, SecurityID>> sec_desc_id_pairs;
sec_desc_id_pairs.reserve(sec_descs.size());
for (const auto &sec_desc : sec_descs) {
sec_desc_id_pairs.emplace_back(
sec_desc,
SecurityID{sec_id_store->get_or_add(VENUE_NAME, sec_desc)});
const vector<std::pair<SecurityType, string>> &sec_descs,
uint32_t hnd_id) {
vector<std::tuple<SecurityType, string, SecurityID>> sec_desc_id_tuples;
sec_desc_id_tuples.reserve(sec_descs.size());
for (auto [type, name] : sec_descs) {
SecurityID id{sec_id_store->get_or_add(VENUE, type, name)};
sec_desc_id_tuples.emplace_back(type, std::move(name), id);
}
auto [it, is_new] = stats_handlers.try_emplace(
hnd_id,
std::make_unique<StatsHandler>(sec_desc_id_pairs, listener.get()));
std::make_unique<StatsHandler>(sec_desc_id_tuples, listener.get()));
bts_assert_msgf(
is_new, "StatsHandler already created with id '{}'", hnd_id);
return *it->second;
}
void add_stats_handler(
const vector<string> &sec_descs, CCApiSession::BatchRequest &reqs) {
const vector<std::pair<SecurityType, string>> &sec_descs,
CCApiSession::BatchRequest &reqs) {
if (sec_descs.empty()) {
return;
}
@@ -273,14 +279,14 @@ struct BinanceSubscription::PImpl {
CCApiSession::BatchRequest stats_reqs;
const int N_SECS_PER_STATS_REQ = 16;
vector<string> curr_stats_sec_descs;
for (const auto &sec_desc : securities) {
vector<std::pair<SecurityType, string>> curr_stats_sec_descs;
for (const auto &[type, desc] : securities) {
depth_subs.push_back(
{mk_depth_sub(sec_desc, depth_opts), &mk_depth_handler(sec_desc)});
{mk_depth_sub(desc, depth_opts), &mk_depth_handler(type, desc)});
ticker_subs.push_back(
{mk_ticker_sub(sec_desc, ticker_opts),
&mk_ticker_handler(sec_desc)});
curr_stats_sec_descs.push_back(sec_desc);
{mk_ticker_sub(desc, ticker_opts),
&mk_ticker_handler(type, desc)});
curr_stats_sec_descs.push_back(std::make_pair(type, desc));
if (curr_stats_sec_descs.size() == N_SECS_PER_STATS_REQ) {
add_stats_handler(curr_stats_sec_descs, stats_reqs);
curr_stats_sec_descs.clear();
@@ -304,7 +310,7 @@ struct BinanceSubscription::PImpl {
*/
void on_securities(vector<Security> secs) {
// 'sec_descs' is used to make depth subscriptions
vector<string> sec_descs;
vector<pair<SecurityType, string>> sec_descs;
sec_descs.reserve(secs.size());
// 'sec_ptrs' is passed to IMarketDataListeners
vector<const Security *> sec_ptrs;
@@ -317,7 +323,8 @@ struct BinanceSubscription::PImpl {
id, std::make_unique<Security>(std::move(s)));
bts_assert_msgf(
is_new, "Received duplicate Binance security '{}'", desc);
sec_descs.push_back(std::move(desc));
sec_descs.push_back(
std::make_pair(it->second->type(), std::move(desc)));
// add ptr to entry in 'securities' (not the loop var, we moved that)
sec_ptrs.push_back(it->second.get());
}
@@ -12,18 +12,19 @@ namespace bts::md::binance_us {
using bts::domain::SecurityID;
using bts::domain::SecurityMarketDataStatistics;
using std::pair;
using bts::domain::protobufs::SecurityType;
using std::string;
using std::tuple;
using std::vector;
#define VENUE_NAME (Venue_Name(Venue::BINANCE))
struct BinanceUsPriceStatisticsAdaptor::PImpl {
vector<pair<string, SecurityID>> securities;
vector<tuple<SecurityType, string, SecurityID>> securities;
IMarketDataListener *listener;
SecurityID get_sec_id(const string &sec_desc) const {
for (const auto &[desc, id] : securities) {
for (const auto &[type, desc, id] : securities) {
if (desc == sec_desc) {
return id;
}
@@ -36,7 +37,8 @@ struct BinanceUsPriceStatisticsAdaptor::PImpl {
};
BinanceUsPriceStatisticsAdaptor::BinanceUsPriceStatisticsAdaptor(
vector<pair<string, SecurityID>> securities, IMarketDataListener *listener)
vector<tuple<SecurityType, string, SecurityID>> securities,
IMarketDataListener *listener)
: me_(std::make_unique<PImpl>()) {
bts_assert(listener != nullptr);
me_->securities = std::move(securities);
@@ -1,9 +1,11 @@
#pragma once
#include "domain/protobufs/security_type.pb.h"
#include "domain/security_id.h"
#include "sparkd/md/ccapi/ICCApiMessageHandler.h"
#include <string>
#include <tuple>
#include <utility>
#include <vector>
@@ -25,7 +27,10 @@ namespace bts::md::binance_us {
class BinanceUsPriceStatisticsAdaptor : public ICCApiMessageHandler {
public:
BinanceUsPriceStatisticsAdaptor(
std::vector<std::pair<std::string, domain::SecurityID>> securities,
std::vector<std::tuple<
domain::protobufs::SecurityType,
std::string,
domain::SecurityID>> securities,
IMarketDataListener *listener);
~BinanceUsPriceStatisticsAdaptor();
@@ -156,7 +156,8 @@ struct BinanceUsSecurityRequestor::PImpl {
for (auto &sec : added_secs) {
// Since the ids haven't been set yet, we should expect them to be 0
bts_assert(sec.id().value() == 0);
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec.desc())};
SecurityID sec_id{
sec_id_store->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
@@ -40,6 +40,7 @@ using bts::api::md::BinanceUsMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::domain::protobufs::Venue_Name;
using bts::http::QueryParams;
@@ -48,11 +49,13 @@ using bts::persistence::IDGenerator;
using std::pair;
using std::shared_ptr;
using std::string;
using std::tuple;
using std::uint32_t;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
#define VENUE Venue::VENUE_BINANCE_US
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE_US))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE_US
@@ -127,14 +130,14 @@ static CCApiCorrelationID mk_stats_corr_id(const string &desc) {
}
static ccapi::Request mk_stats_req(
const vector<string> &sec_descs, uint32_t batch_id) {
const vector<pair<SecurityType, string>> &sec_descs, uint32_t batch_id) {
const auto corr_id = mk_stats_corr_id(FMT("BATCH_{}", batch_id));
ccapi::Request req{
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, CCAPI_VENUE_NAME};
req.setCorrelationId(corr_id.to_string());
auto quoted_sec_descs =
sec_descs |
ranges::views::transform([](const auto &s) { return "\"" + s + "\""; });
sec_descs | ranges::views::transform(
[](const auto &s) { return "\"" + s.second + "\""; });
const string symbols_query_arg = FMT_JOIN(quoted_sec_descs, ",");
req.appendParam(
{{CCAPI_HTTP_PATH, BINANCE_US_PRICE_STATS_PATH},
@@ -217,16 +220,18 @@ struct BinanceUsSubscription::PImpl {
sec_requestor.request();
}
DepthHandler &mk_depth_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
DepthHandler &mk_depth_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
depth_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert(is_new);
return it->second;
}
TickerHandler &mk_ticker_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
TickerHandler &mk_ticker_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
ticker_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -235,24 +240,25 @@ struct BinanceUsSubscription::PImpl {
}
StatsHandler &mk_stats_handler(
const vector<string> &sec_descs, uint32_t hnd_id) {
vector<pair<string, SecurityID>> sec_desc_id_pairs;
sec_desc_id_pairs.reserve(sec_descs.size());
for (const auto &sec_desc : sec_descs) {
sec_desc_id_pairs.emplace_back(
sec_desc,
SecurityID{sec_id_store->get_or_add(VENUE_NAME, sec_desc)});
const vector<std::pair<SecurityType, string>> &sec_descs,
uint32_t hnd_id) {
vector<tuple<SecurityType, string, SecurityID>> sec_desc_id_tuples;
sec_desc_id_tuples.reserve(sec_descs.size());
for (auto [type, name] : sec_descs) {
SecurityID id{sec_id_store->get_or_add(VENUE, type, name)};
sec_desc_id_tuples.emplace_back(type, std::move(name), id);
}
auto [it, is_new] = stats_handlers.try_emplace(
hnd_id,
std::make_unique<StatsHandler>(sec_desc_id_pairs, listener.get()));
std::make_unique<StatsHandler>(sec_desc_id_tuples, listener.get()));
bts_assert_msgf(
is_new, "StatsHandler already created with id '{}'", hnd_id);
return *it->second;
}
void add_stats_handler(
const vector<string> &sec_descs, CCApiSession::BatchRequest &reqs) {
const vector<pair<SecurityType, string>> &sec_descs,
CCApiSession::BatchRequest &reqs) {
if (sec_descs.empty()) {
return;
}
@@ -277,14 +283,14 @@ struct BinanceUsSubscription::PImpl {
CCApiSession::BatchRequest stats_reqs;
const int N_SECS_PER_STATS_REQ = 16;
vector<string> curr_stats_sec_descs;
for (const auto &sec_desc : securities) {
vector<pair<SecurityType, string>> curr_stats_sec_descs;
for (const auto &[type, name] : securities) {
depth_subs.push_back(
{mk_depth_sub(sec_desc, depth_opts), &mk_depth_handler(sec_desc)});
{mk_depth_sub(name, depth_opts), &mk_depth_handler(type, name)});
ticker_subs.push_back(
{mk_ticker_sub(sec_desc, ticker_opts),
&mk_ticker_handler(sec_desc)});
curr_stats_sec_descs.push_back(sec_desc);
{mk_ticker_sub(name, ticker_opts),
&mk_ticker_handler(type, name)});
curr_stats_sec_descs.push_back(std::make_pair(type, name));
if (curr_stats_sec_descs.size() == N_SECS_PER_STATS_REQ) {
add_stats_handler(curr_stats_sec_descs, stats_reqs);
curr_stats_sec_descs.clear();
@@ -308,7 +314,7 @@ struct BinanceUsSubscription::PImpl {
*/
void on_securities(vector<Security> secs) {
// 'sec_descs' is used to make depth subscriptions
vector<string> sec_descs;
vector<pair<SecurityType, string>> sec_descs;
sec_descs.reserve(secs.size());
// 'sec_ptrs' is passed to IMarketDataListeners
vector<const Security *> sec_ptrs;
@@ -321,7 +327,7 @@ struct BinanceUsSubscription::PImpl {
id, std::make_unique<Security>(std::move(s)));
bts_assert_msgf(
is_new, "Received duplicate Binance US security '{}'", desc);
sec_descs.push_back(std::move(desc));
sec_descs.push_back(std::make_pair(s.type(), std::move(desc)));
// add ptr to entry in 'securities' (not the loop var, we moved that)
sec_ptrs.push_back(it->second.get());
}
@@ -49,6 +49,7 @@ using std::vector;
#define _WARN(...) _LOG(Warn, __VA_ARGS__)
#define _ERROR(...) _LOG(Error, __VA_ARGS__)
#define VENUE Venue::VENUE_BINANCE_USDS_FUTURES
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE_USDS_FUTURES))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES
#define VENUE_PRICE_STATS_PATH BINANCE_USDS_FUTURES_PRICE_STATS_PATH
@@ -158,7 +159,8 @@ struct BinanceUsdsFuturesSecurityRequestor::PImpl {
// the ids, if it does (for whatever reason), better to assert/crash
// than quietly let a potential bug slip through the cracks.
bts_assert(sec.id().value() == 0);
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec.desc())};
SecurityID sec_id{
sec_id_store->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
@@ -1,4 +1,5 @@
#include "BinanceUsdsFuturesSubscription.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/protobufs/venue.pb.h"
#include "domain/security.h"
#include "domain/security_criteria.h"
@@ -34,11 +35,13 @@ using bts::api::md::BinanceUsdsFuturesMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::domain::protobufs::Venue_Name;
using bts::http::QueryParams;
using bts::io::ProtoPrinter;
using bts::persistence::IDGenerator;
using std::pair;
using std::shared_ptr;
using std::string;
using std::uint32_t;
@@ -46,6 +49,7 @@ using std::unique_ptr;
using std::unordered_map;
using std::vector;
#define VENUE Venue::VENUE_BINANCE_USDS_FUTURES
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE_USDS_FUTURES))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES
#define VENUE_PRICE_STATS_PATH BINANCE_USDS_FUTURES_PRICE_STATS_PATH
@@ -197,8 +201,8 @@ struct BinanceUsdsFuturesSubscription::PImpl {
sec_requestor.request();
}
SecurityID get_sec_id(const string &sec_desc) {
return SecurityID{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
SecurityID get_sec_id(SecurityType sec_type, const string &sec_desc) {
return SecurityID{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
}
/**
@@ -216,8 +220,9 @@ struct BinanceUsdsFuturesSubscription::PImpl {
return sec_desc;
}
DepthHandler &add_depth_handler(const string &sec_desc) {
const auto sec_id = get_sec_id(sec_desc);
DepthHandler &add_depth_handler(
SecurityType sec_type, const string &sec_desc) {
const auto sec_id = get_sec_id(sec_type, sec_desc);
auto [it, is_new] =
depth_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -225,8 +230,9 @@ struct BinanceUsdsFuturesSubscription::PImpl {
return it->second;
}
TickerHandler &add_ticker_handler(const string &sec_desc) {
const auto sec_id = get_sec_id(sec_desc);
TickerHandler &add_ticker_handler(
SecurityType sec_type, const string &sec_desc) {
const auto sec_id = get_sec_id(sec_type, sec_desc);
auto [it, is_new] =
ticker_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -234,8 +240,9 @@ struct BinanceUsdsFuturesSubscription::PImpl {
return it->second;
}
StatsHandler &add_stats_handler(const string &sec_desc) {
const auto sec_id = get_sec_id(sec_desc);
StatsHandler &add_stats_handler(
SecurityType sec_type, const string &sec_desc) {
const auto sec_id = get_sec_id(sec_type, sec_desc);
auto [it, is_new] =
stats_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -257,16 +264,16 @@ struct BinanceUsdsFuturesSubscription::PImpl {
CCApiSession::BatchSubscription ticker_subs;
CCApiSession::BatchRequest stats_reqs;
for (const auto &sec_desc : securities) {
const auto sec_desc_for_reqs = get_sec_desc_for_reqs(sec_desc);
for (auto [type, name] : securities) {
const auto sec_desc_for_reqs = get_sec_desc_for_reqs(name);
depth_subs.push_back(
{mk_depth_sub(sec_desc_for_reqs, depth_opts),
&add_depth_handler(sec_desc)});
&add_depth_handler(type, name)});
ticker_subs.push_back(
{mk_ticker_sub(sec_desc_for_reqs, ticker_opts),
&add_ticker_handler(sec_desc)});
&add_ticker_handler(type, name)});
stats_reqs.push_back(
{mk_stats_req(sec_desc), &add_stats_handler(sec_desc)});
{mk_stats_req(name), &add_stats_handler(type, name)});
}
session.subscribe(
@@ -283,7 +290,7 @@ struct BinanceUsdsFuturesSubscription::PImpl {
*/
void on_securities(vector<Security> secs) {
// 'sec_descs' is used to make depth subscriptions
vector<string> sec_descs;
vector<pair<SecurityType, string>> sec_descs;
sec_descs.reserve(secs.size());
// 'sec_ptrs' is passed to IMarketDataListeners
vector<const Security *> sec_ptrs;
@@ -296,7 +303,7 @@ struct BinanceUsdsFuturesSubscription::PImpl {
id, std::make_unique<Security>(std::move(s)));
bts_assert_msgf(
is_new, "Received duplicate Binance USDS Future '{}'", desc);
sec_descs.push_back(std::move(desc));
sec_descs.push_back(std::make_pair(s.type(), std::move(desc)));
// add ptr to entry in 'securities' (not the loop var, we moved that)
sec_ptrs.push_back(it->second.get());
}
@@ -147,7 +147,8 @@ struct CoinbaseSecurityRequestor::PImpl {
for (auto &sec : added_secs) {
// Since the ids haven't been set yet, we should expect them to be 0
bts_assert(sec.id().value() == 0);
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec.desc())};
SecurityID sec_id{
sec_id_store->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
@@ -1,11 +1,11 @@
#include "CoinbaseSubscription.h"
#include "domain/protobufs/venue.pb.h"
#include "domain/security.h"
#include "domain/security_criteria.h"
#include "http/query_params.h"
#include "spark/api/md/CoinbaseMarketDataConfig.pb.h"
#include "spark/io/ProtoPrinter.h"
#include "spark/md/IMarketDataListener.h"
#include "http/query_params.h"
#include "spark/md/common.h"
#include "spark/persistence/IDGenerator.h"
#include "spark/utils/bts_assert.h"
@@ -32,15 +32,19 @@ using bts::api::md::CoinbaseMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::http::QueryParams;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::io::ProtoPrinter;
using bts::persistence::IDGenerator;
using std::map;
using std::pair;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
#define VENUE Venue::VENUE_COINBASE
#define VENUE_NAME (Venue_Name(Venue::VENUE_COINBASE))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_COINBASE
@@ -193,24 +197,28 @@ struct CoinbaseSubscription::PImpl {
sec_requestor.request();
}
StatsHandler &mk_stats_handler(const string &sec_desc) {
auto sec_id = SecurityID{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
StatsHandler &mk_stats_handler(
SecurityType sec_type, const string &sec_desc) {
auto sec_id =
SecurityID{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
stats_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
is_new, "StatsHandler already created with id '{}'", sec_id);
return it->second;
}
DepthHandler &mk_depth_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
DepthHandler &mk_depth_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
depth_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert(is_new);
return it->second;
}
TickerHandler &mk_ticker_handler(const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
TickerHandler &mk_ticker_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
ticker_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -232,14 +240,15 @@ struct CoinbaseSubscription::PImpl {
CCApiSession::BatchRequest stats_reqs;
vector<string> curr_stats_sec_descs;
for (const auto &sec_desc : securities) {
for (const auto &[sec_type, sec_desc] : securities) {
depth_subs.push_back(
{mk_depth_sub(sec_desc, depth_opts), &mk_depth_handler(sec_desc)});
{mk_depth_sub(sec_desc, depth_opts),
&mk_depth_handler(sec_type, sec_desc)});
ticker_subs.push_back(
{mk_ticker_sub(sec_desc, ticker_opts),
&mk_ticker_handler(sec_desc)});
&mk_ticker_handler(sec_type, sec_desc)});
stats_reqs.push_back(
{mk_stats_req(sec_desc), &mk_stats_handler(sec_desc)});
{mk_stats_req(sec_desc), &mk_stats_handler(sec_type, sec_desc)});
}
session.subscribe(
@@ -257,7 +266,7 @@ struct CoinbaseSubscription::PImpl {
void on_securities(std::vector<Security> secs) {
LOG(md, Info, "on sec {}", secs.size());
// 'sec_descs' is used to make depth subscriptions
vector<string> sec_descs;
vector<pair<SecurityType, string>> sec_descs;
sec_descs.reserve(secs.size());
// 'sec_ptrs' is passed to IMarketDataListeners
vector<const Security *> sec_ptrs;
@@ -270,7 +279,7 @@ struct CoinbaseSubscription::PImpl {
id, std::make_unique<Security>(std::move(s)));
bts_assert_msgf(
is_new, "Received duplicate Coinbase security '{}'", desc);
sec_descs.push_back(std::move(desc));
sec_descs.push_back(std::make_pair(s.type(), std::move(desc)));
// add ptr to entry in 'securities' (not the loop var, we moved that)
sec_ptrs.push_back(it->second.get());
}
@@ -2,6 +2,7 @@
#include "databento/datetime.hpp"
#include "databento/timeseries.hpp"
#include "domain/book.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/quantity.h"
#include "domain/security.h"
#include "domain/security_id.h"
@@ -10,7 +11,6 @@
#include "spark/persistence/IDGenerator.h"
#include "spark/utils/TimeStamp.h"
#include "spark/utils/bts_assert.h"
#include "spark/utils/bts_chrono.h"
#include "spark/utils/datetime.h"
#include "system/protobufs/config/system_config.pb.h"
@@ -22,6 +22,10 @@
namespace bts::md::DatabentoHandler {
#define SEC_TYPE(name) bts::domain::protobufs::SECURITY_TYPE_##name
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::system::protobufs::SystemConfig;
@@ -36,6 +40,16 @@ std::string remove_spaces(const std::string_view &str) {
return result;
}
static SecurityType parse_sec_type(std::string_view str) {
if (str.find("OPT") != std::string::npos) {
return SEC_TYPE(OPTION);
}
if (str.find("FUT") != std::string::npos) {
return SEC_TYPE(FUTURE);
}
return SEC_TYPE(UNSPECIFIED);
}
void DatabentoDatahandler::run(
bool use_file,
std::shared_ptr<IMarketDataListener> listener,
@@ -67,12 +81,9 @@ void DatabentoDatahandler::run(
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 = symbol;
@@ -83,35 +94,49 @@ void DatabentoDatahandler::run(
sec.security_common.min_quantity_increment = 0.01;
sec.security_common.currency = {msg.currency.data(), msg.currency.size()};
const std::string_view sec_type = {
msg.security_type.data(), msg.security_type.size()};
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);
if (sec_type.find("OPT") != std::string::npos) {
switch (sec_type) {
case SEC_TYPE(FUTURE):
sec.security.emplace<bts::domain::FutureSecurity>(expiration_time);
break;
case SEC_TYPE(OPTION):
sec.security.emplace<bts::domain::OptionSecurity>(
expiration_time,
bts::domain::Price::from_double(msg.strike_price));
} else if (sec_type.find("FUT") != std::string::npos) {
sec.security.emplace<bts::domain::FutureSecurity>(expiration_time);
} else {
break;
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;
};
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;
// 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;
}
}
sleep_for(sleep_duration);
bts::domain::SecurityID sec_id =
@@ -28,6 +28,7 @@ using bts::domain::Side;
using bts::domain::SpotSecurity;
using bts::domain::SpreadSecurity;
using bts::domain::protobufs::CallPut;
using bts::domain::protobufs::SecurityType;
using bts::persistence::IDGenerator;
using nlohmann::json;
using std::function;
@@ -106,8 +107,8 @@ struct DeribitInstrumentStore::PImpl {
return &it->second;
}
Security *find(const string &name) {
auto id = sec_id_store_->get_id(VENUE, name);
Security *find(SecurityType type, const string &name) {
auto id = sec_id_store_->get_id(VENUE, type, name);
if (!id) {
return nullptr;
}
@@ -147,7 +148,7 @@ struct DeribitInstrumentStore::PImpl {
continue;
}
const SecurityID id{
sec_id_store_->get_or_add(VENUE, di.instrument_name)};
sec_id_store_->get_or_add(VENUE, sec.type(), di.instrument_name)};
sec.security_common.id = id;
auto [it, is_new] = securities_.try_emplace(id, std::move(sec));
if (!is_new) {
@@ -188,8 +189,8 @@ struct DeribitInstrumentStore::PImpl {
// DeribitCombo object, which is required to resolve the leg definitions.
unordered_map<string, Security> unresolved_combos_;
const Security *find_security_(const string &name) {
const auto id = sec_id_store_->get_id(VENUE, name);
const Security *find_security_(SecurityType type, const string &name) {
const auto id = sec_id_store_->get_id(VENUE, type, name);
if (!id) {
return nullptr;
}
@@ -202,7 +203,8 @@ struct DeribitInstrumentStore::PImpl {
bool resolve_combo_(const DeribitCombo &combo, SpreadSecurity &spd) {
for (const auto &leg : combo.legs) {
const auto *leg_sec = find_security_(leg.instrument_name);
const auto *leg_sec =
find_security_(SEC_TYPE(SPREAD), leg.instrument_name);
if (leg_sec == nullptr) {
spd.legs.clear();
return false;
@@ -259,7 +261,8 @@ struct DeribitInstrumentStore::PImpl {
continue;
}
}
SecurityID id{sec_id_store_->get_or_add(VENUE, sec.desc())};
SecurityID id{
sec_id_store_->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = id;
auto [sec_it, is_new] = securities_.try_emplace(id, std::move(sec));
if (!is_new) {
@@ -292,8 +295,8 @@ const Security *DeribitInstrumentStore::find(SecurityID id) const {
return me_->find(id);
}
Security *DeribitInstrumentStore::find(const string &id) {
return me_->find(id);
Security *DeribitInstrumentStore::find(SecurityType type, const string &name) {
return me_->find(type, name);
}
void DeribitInstrumentStore::on_instruments(
@@ -45,11 +45,12 @@ class DeribitInstrumentStore {
const domain::Security *find(domain::SecurityID id) const;
/**
* @brief Finds the security with the specified \p name
* @brief Finds the security with the specified \p name and \p type
* @details No 'const' overload bc the fn that converts name to numeric id
* isn't const
*/
domain::Security *find(const std::string &name);
domain::Security *find(
domain::protobufs::SecurityType type, const std::string &name);
void on_instruments(
const std::vector<DeribitInstrument> &instruments,
@@ -45,6 +45,7 @@ using bts::api::md::DeribitMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::io::ProtoPrinter;
using bts::io::websocket::JsonRpcError;
using bts::io::websocket::JsonRpcId;
@@ -59,6 +60,7 @@ using std::unordered_map;
using std::unordered_set;
using std::vector;
#define VENUE bts::domain::protobufs::VENUE_DERIBIT
#define VENUE_NAME \
(bts::domain::protobufs::Venue_Name(bts::domain::protobufs::VENUE_DERIBIT))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_DERIBIT
@@ -170,8 +172,9 @@ struct DeribitSubscription::PImpl {
subscribe_instrument_state();
}
SecurityData &add_security_data(const string sec_desc) {
const SecurityID sid{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
SecurityData &add_security_data(
SecurityType sec_type, const string &sec_desc) {
const SecurityID sid{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] = security_data_map.try_emplace(
sec_desc, std::make_unique<SecurityData>(sid, listener.get()));
_ASSERT_MSGF(is_new, "add_security_data. Already added '{}'", sec_desc);
@@ -203,27 +206,31 @@ struct DeribitSubscription::PImpl {
void subscribe_md(SecurityNames security_names) {
// Populate list of 'channels', and prepare their corresponding handlers
vector<string> channels;
for (const string &sec : security_names) {
auto &sec_data = add_security_data(sec);
for (auto [type, name] : security_names) {
auto &sec_data = add_security_data(type, name);
// Depth
if (subscribe_depth) {
const auto &ch = channels.emplace_back(
FMT("book.{}.none.{}.100ms", sec, cfg.num_depth_levels()));
FMT("book.{}.none.{}.100ms", name, cfg.num_depth_levels()));
channel_demuxer.add_handler(ch)
.bind<&DeribitDepthAdaptor::on_depths>(sec_data.depth_hnd);
.template bind<&DeribitDepthAdaptor::on_depths>(
sec_data.depth_hnd);
}
// Ticker
if (subscribe_ticker) {
const auto &ch =
channels.emplace_back(FMT("incremental_ticker.{}", sec));
channels.emplace_back(FMT("incremental_ticker.{}", name));
channel_demuxer.add_handler(ch)
.bind<&DeribitTickerAdaptor::on_tickers>(sec_data.ticker_hnd);
.template bind<&DeribitTickerAdaptor::on_tickers>(
sec_data.ticker_hnd);
}
// Trades
if (subscribe_trades) {
const auto &ch = channels.emplace_back(FMT("trades.{}.100ms", sec));
const auto &ch =
channels.emplace_back(FMT("trades.{}.100ms", name));
channel_demuxer.add_handler(ch)
.bind<&DeribitTradeAdaptor::on_trades>(sec_data.trade_hnd);
.template bind<&DeribitTradeAdaptor::on_trades>(
sec_data.trade_hnd);
}
}
// If 'channels' is empty, it's a no-op
@@ -257,7 +264,9 @@ struct DeribitSubscription::PImpl {
bts_assert(!CONTAINS_KEY(security_data_map, sec->desc()));
}
listener->on_securities(secs);
auto sec_names = TRANSFORM(secs, [](const auto *s) { return s->desc(); });
auto sec_names = TRANSFORM(secs, [](const auto *s) {
return std::make_pair(s->type(), s->desc());
});
batch_subscribe_md(sec_names);
}
@@ -35,6 +35,7 @@ using std::string;
using std::unordered_set;
using std::vector;
#define VENUE Venue::VENUE_FTX
#define VENUE_NAME (Venue_Name(Venue::VENUE_FTX))
#define SEC_TYPE(x) bts::domain::protobufs::SECURITY_TYPE_##x
@@ -172,7 +173,8 @@ struct FTXSecurityRequestor::PImpl {
for (auto &sec : added_secs) {
// Since the ids haven't been set yet, we should expect them to be 0
bts_assert(sec.id().value() == 0);
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec.desc())};
SecurityID sec_id{
sec_id_store->get_or_add(VENUE, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
@@ -1,4 +1,5 @@
#include "FTXSubscription.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/protobufs/venue.pb.h"
#include "domain/security.h"
#include "domain/security_criteria.h"
@@ -32,16 +33,19 @@ using bts::api::md::FTXMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::Venue;
using bts::domain::protobufs::Venue_Name;
using bts::io::ProtoPrinter;
using bts::persistence::IDGenerator;
using std::pair;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
#define VENUE Venue::VENUE_FTX
#define VENUE_NAME (Venue_Name(Venue::VENUE_FTX))
#define FTX_MSG_TYPE_NAME(x) \
@@ -135,16 +139,18 @@ struct FTXSubscription::PImpl {
sec_requestor.request();
}
DepthHandler &create_depth_handler(string sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
DepthHandler &create_depth_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
depth_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert(is_new);
return it->second;
}
TickerHandler &create_ticker_handler(string sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
TickerHandler &create_ticker_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
ticker_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -152,8 +158,9 @@ struct FTXSubscription::PImpl {
return it->second;
}
StatsHandler &create_stats_handler(string sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
StatsHandler &create_stats_handler(
SecurityType sec_type, const string &sec_desc) {
SecurityID sec_id{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] =
stats_handlers.try_emplace(sec_desc, sec_id, listener.get());
bts_assert_msgf(
@@ -176,15 +183,16 @@ struct FTXSubscription::PImpl {
CCApiSession::BatchSubscription ticker_subs;
CCApiSession::BatchRequest stats_reqs;
for (const auto &sec_desc : securities) {
for (const auto &[sec_type, sec_desc] : securities) {
depth_subs.push_back(
{create_depth_sub(sec_desc, depth_opts),
&create_depth_handler(sec_desc)});
&create_depth_handler(sec_type, sec_desc)});
ticker_subs.push_back(
{create_ticker_sub(sec_desc, ticker_opts),
&create_ticker_handler(sec_desc)});
&create_ticker_handler(sec_type, sec_desc)});
stats_reqs.push_back(
{create_stats_req(sec_desc), &create_stats_handler(sec_desc)});
{create_stats_req(sec_desc),
&create_stats_handler(sec_type, sec_desc)});
}
session.subscribe(
@@ -201,7 +209,7 @@ struct FTXSubscription::PImpl {
*/
void on_securities(vector<domain::Security> secs) {
// 'sec_descs' is used to make depth subscriptions
vector<string> sec_descs;
vector<pair<SecurityType, string>> sec_descs;
sec_descs.reserve(secs.size());
// 'sec_ptrs' is passed to IMarketDataListeners
vector<const domain::Security *> sec_ptrs;
@@ -213,7 +221,7 @@ struct FTXSubscription::PImpl {
auto [it, is_new] = securities.try_emplace(
id, std::make_unique<domain::Security>(std::move(s)));
bts_assert_msgf(is_new, "Received duplicate FTX security '{}'", desc);
sec_descs.push_back(std::move(desc));
sec_descs.push_back(std::make_pair(s.type(), std::move(desc)));
// add ptr to entry in 'securities' (not the loop var, we moved that)
sec_ptrs.push_back(it->second.get());
}
@@ -1,5 +1,6 @@
#include "OkxInstrumentStore.h"
#include "domain/protobufs/security_type.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/security.h"
#include "spark/persistence/IDGenerator.h"
#include "spark/utils/bts_fatal.h"
@@ -21,6 +22,7 @@ using bts::domain::Security;
using bts::domain::SecurityID;
using bts::domain::SpotSecurity;
using bts::domain::protobufs::CallPut;
using bts::domain::protobufs::SecurityType;
using bts::persistence::IDGenerator;
using nlohmann::json;
using std::function;
@@ -94,8 +96,8 @@ struct OkxInstrumentStore::PImpl {
return &it->second;
}
Security *find(const string &name) {
auto id = sec_id_store_->get_id(VENUE, name);
Security *find(SecurityType type, const string &name) {
auto id = sec_id_store_->get_id(VENUE, type, name);
if (!id) {
return nullptr;
}
@@ -124,7 +126,7 @@ struct OkxInstrumentStore::PImpl {
if (!filter_(sec)) {
continue;
}
SecurityID id{sec_id_store_->get_or_add(VENUE, oi.instId)};
SecurityID id{sec_id_store_->get_or_add(VENUE, sec.type(), oi.instId)};
sec.security_common.id = id;
auto [it, is_new] = securities_.try_emplace(id, std::move(sec));
if (!is_new) {
@@ -152,7 +154,9 @@ const Security *OkxInstrumentStore::find(SecurityID id) const {
return me_->find(id);
}
Security *OkxInstrumentStore::find(const string &id) { return me_->find(id); }
Security *OkxInstrumentStore::find(SecurityType type, const string &name) {
return me_->find(type, name);
}
void OkxInstrumentStore::on_instruments(
const vector<OkxInstrument> &instruments,
@@ -50,7 +50,8 @@ class OkxInstrumentStore {
* @details No 'const' overload bc the fn that converts name to numeric id
* isn't const
*/
domain::Security *find(const std::string &name);
domain::Security *find(
domain::protobufs::SecurityType type, const std::string &name);
void on_instruments(
const std::vector<OkxInstrument> &instruments,
@@ -42,6 +42,7 @@ using bts::api::md::OkxMarketDataConfig;
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::domain::protobufs::SecurityType;
using bts::io::ProtoPrinter;
using bts::persistence::IDGenerator;
using std::optional;
@@ -61,6 +62,7 @@ using std::vector;
#define _WARN(...) _LOG(Warn, __VA_ARGS__)
#define _ERROR(...) _LOG(Error, __VA_ARGS__)
#define VENUE bts::domain::protobufs::VENUE_OKX
#define VENUE_NAME \
(bts::domain::protobufs::Venue_Name(bts::domain::protobufs::VENUE_OKX))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_OKX
@@ -171,8 +173,9 @@ struct OkxSubscription::PImpl {
[this](const auto &secs) { on_securities(secs); });
}
SecurityData &add_security_data(const string sec_desc) {
const SecurityID sid{sec_id_store->get_or_add(VENUE_NAME, sec_desc)};
SecurityData &add_security_data(
SecurityType sec_type, const string &sec_desc) {
const SecurityID sid{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
auto [it, is_new] = security_data_map.try_emplace(
sec_desc, std::make_unique<SecurityData>(sid, listener.get()));
_ASSERT_MSGF(is_new, "add_security_data. Already added '{}'", sec_desc);
@@ -189,13 +192,13 @@ struct OkxSubscription::PImpl {
void subscribe_md(SecurityNames security_names) {
// Populate list of 'channels', and prepare their corresponding handlers
vector<OkxChannel> channels;
for (const string &sec : security_names) {
auto &sec_data = add_security_data(sec);
for (const auto &[type, name] : security_names) {
auto &sec_data = add_security_data(type, name);
// Depth
if (subscribe_depth) {
auto &ch = channels.emplace_back();
ch.channel = "books5";
ch.instId = sec;
ch.instId = name;
channel_demuxer.add_handler(ch).bind<&OkxDepthAdaptor::on_depths>(
sec_data.depth_hnd);
}
@@ -203,7 +206,7 @@ struct OkxSubscription::PImpl {
if (subscribe_ticker) {
auto &ch = channels.emplace_back();
ch.channel = "tickers";
ch.instId = sec;
ch.instId = name;
channel_demuxer.add_handler(ch).bind<&OkxTickerAdaptor::on_tickers>(
sec_data.ticker_hnd);
}
@@ -211,7 +214,7 @@ struct OkxSubscription::PImpl {
if (subscribe_trades) {
auto &ch = channels.emplace_back();
ch.channel = "trades";
ch.instId = sec;
ch.instId = name;
channel_demuxer.add_handler(ch).bind<&OkxTradeAdaptor::on_trades>(
sec_data.trade_hnd);
}
@@ -247,7 +250,9 @@ struct OkxSubscription::PImpl {
bts_assert(!CONTAINS_KEY(security_data_map, sec->desc()));
}
listener->on_securities(secs);
auto sec_names = TRANSFORM(secs, [](const auto *s) { return s->desc(); });
auto sec_names = TRANSFORM(secs, [](const auto *s) {
return std::make_pair(s->type(), s->desc());
});
batch_subscribe_md(sec_names);
}
};
@@ -61,7 +61,9 @@ using namespace bts::orderman;
namespace bts::md {
#define SEC_TYPE(x) bts::domain::protobufs::SECURITY_TYPE_##x
#define TRADING_STATUS(x) bts::domain::protobufs::TRADINGSTATUS_##x
#define VENUE bts::domain::protobufs::VENUE_DERIBIT
using bts::domain::protobufs::TradingStatus;
@@ -1150,16 +1152,32 @@ DescSearchResult EmMDListener::_find_em_sec(
}
}
static domain::protobufs::SecurityType convert_sec_type(
emumba::market_data::security_type emumba_sec_type) {
switch (emumba_sec_type) {
case emumba::market_data::security_type::index:
return SEC_TYPE(SPOT);
case emumba::market_data::security_type::future:
return SEC_TYPE(FUTURE);
case emumba::market_data::security_type::spread:
return SEC_TYPE(SPREAD);
case emumba::market_data::security_type::option:
return SEC_TYPE(OPTION);
default:
bts_assert_msg(false, "Unknown sec type");
return SEC_TYPE(UNSPECIFIED);
}
}
security_key EmMDListener::_add_sec_entry(
const emumba::market_data::security &sec) {
const std::string &desc = extract_security_desc(sec);
// id_gen either adds a key and returns a new id, or finds one and returns
// the previously added id
bts_assert(me->sec_emdesc_map.find(desc) == me->sec_emdesc_map.end());
auto new_key_opt = me->id_gen.get_id("exchange_key", desc, true);
bts_assert(new_key_opt.has_value());
const security_key new_key = static_cast<security_key>(
me->id_gen.get_or_add(VENUE, convert_sec_type(sec.sec_type()), desc));
// TODO (64 -> 32 conversion)
security_key new_key = new_key_opt.value();
me->sec_emdesc_map.insert({desc, {new_key, sec}});
bts_assert(me->sec_btsid_map.find(new_key) == me->sec_btsid_map.end());
me->sec_btsid_map.insert({new_key, desc});
@@ -1,5 +1,6 @@
#include "TaifexDataHandler.h"
#include "domain/price.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/security.h"
#include "domain/security_id.h"
#include "spark/config/config.h"
@@ -1139,6 +1140,20 @@ struct I083Data {
}
};
static domain::protobufs::SecurityType convert_sec_type(
I010Data::ProductInfo::ProductType type) {
switch (type) {
case I010Data::ProductInfo::ProductType::FUTURES:
return domain::protobufs::SECURITY_TYPE_FUTURE;
case I010Data::ProductInfo::ProductType::OPTIONS:
return domain::protobufs::SECURITY_TYPE_OPTION;
default:
bts_assert_msg(
false, "Unsupported ProductType (expected FUTURES or OPTIONS)");
return domain::protobufs::SECURITY_TYPE_UNSPECIFIED;
}
}
bool readBinaryFile(
const std::string &file_name,
std::shared_ptr<bts::md::IMarketDataListener> listener,
@@ -1205,8 +1220,10 @@ bool readBinaryFile(
const auto id = remove_spaces(i010_message.prod_id);
const auto symbol = id.substr(0, 2);
const auto sec_type =
convert_sec_type(i010_message.parsedProductInfo.productType);
bts::domain::SecurityID sec_id{
sec_id_store->get_or_add(Venue::VENUE_TAIFEX, id)};
sec_id_store->get_or_add(Venue::VENUE_TAIFEX, sec_type, id)};
security_details->add_i010_mapping(
id, sec_id, i010_message.decimal_locator);
// std::ostringstream oss;
+16
View File
@@ -20,6 +20,14 @@ class PyBook {
const std::string &venue() const;
void set_venue(std::string value);
/**
* @brief Gets the security type
*
* @return const std::string& The security type
*/
const std::string &security_type() const;
void set_security_type(std::string value);
/**
* @brief Gets the exchange security id. This is typically the security's name
* (e.g., "BTS-PERPETUAL", or "ESH5").
@@ -57,6 +65,7 @@ class PyBook {
private:
std::string venue_;
std::string security_type_;
std::string exchange_security_id_;
PyBookSide bids_;
PyBookSide asks_;
@@ -69,6 +78,13 @@ class PyBook {
inline const std::string &PyBook::venue() const { return venue_; }
inline void PyBook::set_venue(std::string value) { venue_ = std::move(value); }
inline const std::string &PyBook::security_type() const {
return security_type_;
}
inline void PyBook::set_security_type(std::string value) {
security_type_ = std::move(value);
}
inline const std::string &PyBook::exchange_security_id() const {
return exchange_security_id_;
}
@@ -64,6 +64,7 @@ PYBIND11_MODULE(python_md_module, m) {
.PROP(PySecurity, id)
.PROP(PySecurity, exchange_id)
.PROP(PySecurity, venue)
.def("type", &PySecurity::type)
.PROP(PySecurity, name)
.PROP(PySecurity, currency)
.PROP(PySecurity, group)
@@ -93,6 +94,7 @@ PYBIND11_MODULE(python_md_module, m) {
py::class_<bts::md::py_interop::PyBook>(m, "PyBook")
.def(py::init<>())
.PROP(PyBook, venue)
.PROP(PyBook, security_type)
.PROP(PyBook, exchange_security_id)
.EXPLICIT_DEF(PyBook, bids, BookSideGetter)
.DEF(PyBook, set_bids)
@@ -110,6 +112,7 @@ PYBIND11_MODULE(python_md_module, m) {
py::class_<PyTrade>(m, "PyTrade")
.def(py::init<>())
.PROP(PyTrade, venue)
.PROP(PyTrade, security_type)
.PROP(PyTrade, exchange_security_id)
.PROP(PyTrade, price)
.PROP(PyTrade, quantity)
@@ -143,4 +146,5 @@ PYBIND11_MODULE(python_md_module, m) {
#undef PROP
#undef DEF
#undef EXPLICIT_DEF
#undef _STR
+19
View File
@@ -22,6 +22,8 @@ class PySecurity {
const std::string &venue() const;
void set_venue(std::string value);
const std::string &type() const;
const std::string &currency() const;
void set_currency(std::string value);
@@ -78,6 +80,23 @@ inline void PySecurity::set_venue(std::string value) {
venue_ = std::move(value);
}
inline const std::string &PySecurity::type() const {
if (is_spot()) {
static std::string SPOT = "SPOT";
return SPOT;
}
if (is_future()) {
static std::string FUTURE = "FUTURE";
return FUTURE;
}
if (is_option()) {
static std::string OPTION = "OPTION";
return OPTION;
}
static std::string UNDEFINED = "UNDEFINED";
return UNDEFINED;
}
inline const std::string &PySecurity::currency() const { return currency_; }
inline void PySecurity::set_currency(std::string value) {
currency_ = std::move(value);
+11
View File
@@ -12,6 +12,9 @@ class PyTrade {
const std::string &venue() const;
void set_venue(std::string value);
const std::string &security_type() const;
void set_security_type(std::string value);
const std::string &exchange_security_id() const;
void set_exchange_security_id(std::string value);
@@ -37,6 +40,7 @@ class PyTrade {
private:
std::string venue_;
std::string security_type_;
std::string exchange_security_id_;
double price_;
double quantity_;
@@ -51,6 +55,13 @@ class PyTrade {
inline const std::string &PyTrade::venue() const { return venue_; }
inline void PyTrade::set_venue(std::string value) { venue_ = std::move(value); }
inline const std::string &PyTrade::security_type() const {
return security_type_;
}
inline void PyTrade::set_security_type(std::string value) {
security_type_ = std::move(value);
}
inline const std::string &PyTrade::exchange_security_id() const {
return exchange_security_id_;
}
@@ -19,14 +19,13 @@
#include "domain/trade_record.h"
#include "spark/domain/DomainSecurityUtils.h"
#include "spark/domain_model/Security.pb.h"
#include "spark/md/GeneralSecurityIndex.h"
#include "spark/md/IntPrice.h"
#include "spark/md/MDProducer.h"
#include "spark/md/MDProducerHandle.h"
#include "spark/md/PriceSize.h"
#include "spark/md/SecurityIDRecorder.h"
#include "spark/md/SecurityIndex.h"
#include "spark/md/shm/fixed_security.h"
#include "spark/md/protos/co2.pb.h"
#include "spark/md/shm/fixed_security.h"
#include "spark/md/shm/hot_depth_entry.h"
#include "spark/orderman/actors/SODPosition.h"
#include "spark/orderman/gateways/sim/SimExecutionGateway.h"
@@ -73,11 +72,12 @@ struct CCSecSearchResult {
};
struct GeneralMarketDataListener::PImpl {
const domain::protobufs::Venue venue;
// if this is set to true, then the security key passed on in the
// on_securities function is used. If this is not set to true, then a new key
// is generated
const bool use_given_sec_key = false;
const std::string cc_name_prefix = "cc_security";
const bool use_given_sec_key = false;
size_t n_bk_updates = 0;
bts::persistence::IDGenerator *id_gen;
std::shared_ptr<GeneralSecurityIndex> index;
@@ -93,11 +93,12 @@ struct GeneralMarketDataListener::PImpl {
MDArray bids = {};
MDArray asks = {};
explicit PImpl(
domain::protobufs::Venue venue,
std::shared_ptr<GeneralSecurityIndex> index,
std::shared_ptr<MDProducer> md_producer,
std::shared_ptr<bts::orderman::SimExecutionGateway> sim_ex_gwy,
persistence::IDGenerator *sec_id_store)
: id_gen(sec_id_store), index(std::move(index)),
: venue(venue), id_gen(sec_id_store), index(std::move(index)),
md_producer(std::move(md_producer)),
sim_ex_gwy(std::move(sim_ex_gwy)) {
if (this->sim_ex_gwy != nullptr) {
@@ -155,6 +156,7 @@ GeneralMarketDataListener::GeneralMarketDataListener(
api::Venue venue,
persistence::IDGenerator *sec_id_store)
: me(std::make_unique<PImpl>(
domain::DomainSecurityUtils::convert(venue),
index,
md_producer,
bts::orderman::SimExecutionGatewayFactory::get()->get_getayeway(
@@ -172,7 +174,7 @@ void GeneralMarketDataListener::on_securities(
LOG(md, Info, "GeneralMarketDataListener::on_securities n_secs: {}",
complete_security_list.size());
for (auto s_ptr : complete_security_list) {
domain::Security sec = *s_ptr;
const domain::Security &sec = *s_ptr;
const auto &s_comm = sec.security_common;
CCSecSearchResult search_result = _find_sec(sec, true);
LOG(md, Info,
@@ -304,11 +306,7 @@ CCSecSearchResult GeneralMarketDataListener::_find_sec(
if (add_if_absent) {
uint64_t bts_id = cc_id.value();
if (!me->use_given_sec_key) {
auto logical_key = get_logical_key(sec);
auto new_key_opt =
me->id_gen->get_id(me->cc_name_prefix, logical_key, true);
bts_assert(new_key_opt.has_value());
bts_id = new_key_opt.value();
bts_id = me->id_gen->get_or_add(me->venue, sec.type(), sec.desc());
}
me->cc_sec_id_map.insert({cc_id, {bts_id}});
LOG(md, Info,
@@ -451,9 +449,7 @@ uint64_t GeneralMarketDataListener::_generate_security_key(
auto logical_key = get_logical_key(sec);
// if (me->use_given_sec_key)
// return sec.security_common.id.value();
auto rv = me->id_gen->get_id(me->cc_name_prefix, logical_key, true);
bts_assert(rv.has_value());
return rv.value();
return me->id_gen->get_or_add(me->venue, sec.type(), sec.desc());
}
void GeneralMarketDataListener::_possibly_match_with_sim_orders(
@@ -1,5 +1,10 @@
#include "IDGenerator.h"
#include "domain/protobufs/security_type.pb.h"
#include "spark/md/GeneralSecurityIndex.h"
#include "spark/md/SecurityIDRecorder.h"
#include "spark/md/shm/fixed_security.h"
#include "spark/persistence/SqliteStore.h"
#include "spark/spark_data_directory.h"
#include "spark/utils/bts_assert.h"
#include "system/logging/logging.h"
@@ -10,6 +15,8 @@
namespace bts::persistence {
using bts::domain::protobufs::SecurityType;
using bts::domain::protobufs::SecurityType_Name;
using bts::domain::protobufs::Venue;
using bts::domain::protobufs::Venue_Name;
using std::string;
@@ -53,8 +60,14 @@ uint64_t get_next_id(
}
std::optional<uint64_t> IDGenerator::get_id(
const Venue &venue, const string &name, bool add_if_new) {
return get_id(Venue_Name(venue), name, add_if_new);
const Venue &venue,
SecurityType type,
const string &name,
bool add_if_new) {
std::string ns = fmt::format(
"{}.{}", Venue_Name(venue).substr(6),
SecurityType_Name(type).substr(12));
return get_id(ns, name, add_if_new);
}
std::optional<uint64_t> IDGenerator::get_id(
@@ -81,10 +94,6 @@ std::optional<uint64_t> IDGenerator::get_id(
}
}
std::uint64_t IDGenerator::get_or_add(const Venue &venue, const string &name) {
return get_or_add(Venue_Name(venue), name);
}
std::uint64_t IDGenerator::get_or_add(
const std::string &ns, const std::string &key) {
auto id = get_id(ns, key, true);
@@ -1,5 +1,6 @@
#pragma once
#include "domain/protobufs/security_type.pb.h"
#include "domain/protobufs/venue.pb.h"
#include <OnixS/CME/MDH/Integral.h>
@@ -22,6 +23,7 @@ class IDGenerator {
std::optional<uint64_t> get_id(
const domain::protobufs::Venue &venue,
domain::protobufs::SecurityType type,
const std::string &name,
bool add_if_new = false);
@@ -29,9 +31,9 @@ class IDGenerator {
const std::string &ns, const std::string &key, bool add_if_new);
std::uint64_t get_or_add(
const domain::protobufs::Venue &venue, const std::string &name);
std::uint64_t get_or_add(const std::string &ns, const std::string &key);
const domain::protobufs::Venue &venue,
domain::protobufs::SecurityType type,
const std::string &name);
private:
static std::shared_ptr<IDGenerator> instance_ptr_;
@@ -39,6 +41,10 @@ class IDGenerator {
struct PImpl;
std::unique_ptr<PImpl> me;
// These methods are private to force callers to use the [public] overloads with venue, type and
// name params, to ensure consistent formatting.
std::uint64_t get_or_add(const std::string &ns, const std::string &key);
};
} // namespace bts::persistence