Also moved a few logging deps from lib_spark -> system: * bts_chrono.h * bts_no_copy.h * defer.h * dispatcher.h/cpp * file_utils.h/cpp * type_name.h
316 lines
11 KiB
C++
316 lines
11 KiB
C++
#include "DeribitSubscription.h"
|
|
#include "domain/protobufs/venue.pb.h"
|
|
#include "domain/security.h"
|
|
#include "domain/security_criteria.h"
|
|
#include "logging/logging.h"
|
|
#include "spark/api/md/DeribitMarketDataConfig.pb.h"
|
|
#include "spark/domain_model/Security.pb.h"
|
|
#include "spark/io/ProtoPrinter.h"
|
|
#include "spark/io/websocket/JsonRpcError.h"
|
|
#include "spark/io/websocket/JsonRpcRequest.h"
|
|
#include "spark/md/IMarketDataListener.h"
|
|
#include "spark/persistence/IDGenerator.h"
|
|
#include "sparkd/md/ccapi/CCApiCorrelationID.h"
|
|
#include "sparkd/md/ccapi/CCApiSession.h"
|
|
#include "sparkd/md/deribit/DeribitChannelDemuxer.h"
|
|
#include "sparkd/md/deribit/DeribitDepthAdaptor.h"
|
|
#include "sparkd/md/deribit/DeribitInstrumentRequest.h"
|
|
#include "sparkd/md/deribit/DeribitInstrumentState.h"
|
|
#include "sparkd/md/deribit/DeribitInstrumentStore.h"
|
|
#include "sparkd/md/deribit/DeribitMessageType.h"
|
|
#include "sparkd/md/deribit/DeribitSecurityRequestor.h"
|
|
#include "sparkd/md/deribit/DeribitTickerAdaptor.h"
|
|
#include "sparkd/md/deribit/DeribitTradeAdaptor.h"
|
|
#include "system/FMT.h"
|
|
#include "system/collections/chunk.h"
|
|
#include "system/collections/contains.h"
|
|
#include "system/collections/remove.h"
|
|
#include "system/collections/transform.h"
|
|
#include "system/time_stamp.h"
|
|
|
|
#include <ccapi_cpp/ccapi_event_dispatcher.h>
|
|
#include <ccapi_cpp/ccapi_macro.h>
|
|
#include <ccapi_cpp/ccapi_message.h>
|
|
#include <ccapi_cpp/ccapi_request.h>
|
|
#include <ccapi_cpp/ccapi_session.h>
|
|
#include <ccapi_cpp/ccapi_subscription.h>
|
|
#include <functional>
|
|
#include <string>
|
|
#include <unordered_map>
|
|
#include <unordered_set>
|
|
|
|
namespace bts::md::deribit {
|
|
|
|
using bts::api::md::DeribitMarketDataConfig;
|
|
using bts::domain::Security;
|
|
using bts::domain::SecurityCriteria;
|
|
using bts::domain::SecurityID;
|
|
using bts::io::ProtoPrinter;
|
|
using bts::io::websocket::JsonRpcError;
|
|
using bts::io::websocket::JsonRpcId;
|
|
using bts::io::websocket::JsonRpcRequest;
|
|
using bts::persistence::IDGenerator;
|
|
using nlohmann::json;
|
|
using std::shared_ptr;
|
|
using std::string;
|
|
using std::uint32_t;
|
|
using std::unique_ptr;
|
|
using std::unordered_map;
|
|
using std::unordered_set;
|
|
using std::vector;
|
|
|
|
#define VENUE_NAME \
|
|
(bts::domain::protobufs::Venue_Name(bts::domain::protobufs::VENUE_DERIBIT))
|
|
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_DERIBIT
|
|
#define SEC_TYPE(t) bts::domain::protobufs::SECURITY_TYPE_##t
|
|
|
|
#define _ASSERT_MSGF(condition, ...) \
|
|
bts_assert_msgf(condition, "DeribitSubscription::" __VA_ARGS__)
|
|
#define _LOG(level, ...) LOG(md, level, "DeribitSubscription::" __VA_ARGS__)
|
|
#define _DIAG(...) _LOG(Diag, __VA_ARGS__)
|
|
#define _INFO(...) _LOG(Info, __VA_ARGS__)
|
|
#define _WARN(...) _LOG(Warn, __VA_ARGS__)
|
|
#define _ERROR(...) _LOG(Error, __VA_ARGS__)
|
|
|
|
/**
|
|
* @brief Applies overrides from our config to a ccapi::SessionConfigs object
|
|
* that is otherwise populated with defaults
|
|
*/
|
|
static ccapi::SessionConfigs mk_session_cfg(
|
|
const DeribitMarketDataConfig &cfg) {
|
|
ccapi::SessionConfigs rv;
|
|
if (!cfg.url_rest_base().empty()) {
|
|
rv.urlRestBase[CCAPI_VENUE_NAME] = cfg.url_rest_base();
|
|
}
|
|
if (!cfg.url_ws_base().empty()) {
|
|
rv.urlWebsocketBase[CCAPI_VENUE_NAME] = cfg.url_ws_base();
|
|
}
|
|
return rv;
|
|
}
|
|
|
|
/**
|
|
* @brief Creates a Subscription for the specified \p channels
|
|
*/
|
|
template <class Channels = vector<string>>
|
|
static ccapi::Subscription mk_deribit_sub(Channels channels, size_t sub_id) {
|
|
const JsonRpcRequest req{
|
|
"public/subscribe",
|
|
{{"channels", vector<string>{channels.begin(), channels.end()}}},
|
|
JsonRpcId::create()};
|
|
return {
|
|
CCAPI_VENUE_NAME, "", CCAPI_GENERIC_PUBLIC_SUBSCRIPTION, req.to_string(),
|
|
FMT("{}.SUBSCRIPTION_{}", VENUE_NAME, sub_id)};
|
|
}
|
|
|
|
struct SecurityData {
|
|
DeribitDepthAdaptor depth_hnd;
|
|
DeribitTradeAdaptor trade_hnd;
|
|
DeribitTickerAdaptor ticker_hnd;
|
|
DeribitInstrumentStateType state;
|
|
const Security *security = nullptr;
|
|
|
|
SecurityData(
|
|
SecurityID id,
|
|
IMarketDataListener *listener,
|
|
DeribitInstrumentStateType state = DeribitInstrumentStateType::NONE)
|
|
: depth_hnd(id, listener), trade_hnd(id, listener),
|
|
ticker_hnd(id, listener), state(state) {}
|
|
};
|
|
|
|
struct DeribitSubscription::PImpl {
|
|
const DeribitMarketDataConfig cfg;
|
|
const SecurityCriteria criteria;
|
|
unordered_set<string> excluded_secs;
|
|
unordered_map<SecurityID, unique_ptr<Security>> securities;
|
|
IDGenerator *sec_id_store;
|
|
DeribitInstrumentStore instrument_store;
|
|
DeribitSecurityRequestor sec_requestor;
|
|
// Keyed by security name
|
|
unordered_map<string, unique_ptr<SecurityData>> security_data_map;
|
|
unordered_map<string, DeribitInstrumentStateType> dirty_instruments;
|
|
const bool subscribe_depth = true;
|
|
const bool subscribe_ticker = true;
|
|
const bool subscribe_trades = true;
|
|
size_t sub_id_counter = 0;
|
|
CCApiSession session;
|
|
shared_ptr<IMarketDataListener> listener;
|
|
DeribitChannelDemuxer channel_demuxer;
|
|
|
|
explicit PImpl(
|
|
ccapi::EventDispatcher *dispatcher,
|
|
DeribitMarketDataConfig cfg,
|
|
IDGenerator *sec_id_store)
|
|
: cfg(std::move(cfg)),
|
|
criteria(SecurityCriteria::from_proto(this->cfg.security_criteria())),
|
|
excluded_secs(
|
|
this->cfg.excluded_securities().begin(),
|
|
this->cfg.excluded_securities().end()),
|
|
sec_id_store(sec_id_store),
|
|
instrument_store(
|
|
sec_id_store,
|
|
[&](const Security &s) {
|
|
return this->criteria.includes_or_undefined(s) &&
|
|
!CONTAINS(excluded_secs, s.desc());
|
|
}),
|
|
sec_requestor(
|
|
&session,
|
|
criteria,
|
|
&instrument_store,
|
|
{this->cfg.currencies().begin(), this->cfg.currencies().end()}),
|
|
session(dispatcher, mk_session_cfg(this->cfg), {}) {
|
|
// DON'T reference the ctr arg 'cfg' (it has been moved to 'this->cfg')
|
|
_INFO("ctr. config:\n{}", ProtoPrinter::to_string(this->cfg));
|
|
sec_requestor.callback().bind<&PImpl::on_securities>(*this);
|
|
}
|
|
|
|
void start(std::shared_ptr<IMarketDataListener> listener) {
|
|
bts_assert(listener != nullptr);
|
|
this->listener = std::move(listener);
|
|
sec_requestor.request_all();
|
|
subscribe_instrument_state();
|
|
}
|
|
|
|
SecurityData &add_security_data(const string sec_desc) {
|
|
const SecurityID sid{sec_id_store->get_or_add(VENUE_NAME, 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);
|
|
_INFO("add_security_data. sec: '{}'", sec_desc);
|
|
return *it->second;
|
|
}
|
|
|
|
/**
|
|
* @brief Subscribes to instrument state updates. This is how we detect when
|
|
* instruments are added/removed.
|
|
* @details At Deribit new exps/strikes are added daily.
|
|
*/
|
|
void subscribe_instrument_state() {
|
|
static const string channel = "instrument.state.any.any";
|
|
channel_demuxer.add_handler(channel).bind<&PImpl::on_instrument_state>(
|
|
*this);
|
|
const auto sub = mk_deribit_sub({channel}, ++sub_id_counter);
|
|
session.subscribe(
|
|
sub, &channel_demuxer,
|
|
{ccapi::Message::Type::GENERIC_PUBLIC_SUBSCRIPTION});
|
|
}
|
|
|
|
/**
|
|
* @brief Subscribes to depth, ticker, and trades for a list of securities
|
|
* @param security_names The securities for which to subscribe md (elements
|
|
* should be strings, not actual domain::Security objects)
|
|
*/
|
|
template <class SecurityNames>
|
|
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);
|
|
// Depth
|
|
if (subscribe_depth) {
|
|
const auto &ch = channels.emplace_back(
|
|
FMT("book.{}.none.{}.100ms", sec, cfg.num_depth_levels()));
|
|
channel_demuxer.add_handler(ch)
|
|
.bind<&DeribitDepthAdaptor::on_depths>(sec_data.depth_hnd);
|
|
}
|
|
// Ticker
|
|
if (subscribe_ticker) {
|
|
const auto &ch =
|
|
channels.emplace_back(FMT("incremental_ticker.{}", sec));
|
|
channel_demuxer.add_handler(ch)
|
|
.bind<&DeribitTickerAdaptor::on_tickers>(sec_data.ticker_hnd);
|
|
}
|
|
// Trades
|
|
if (subscribe_trades) {
|
|
const auto &ch = channels.emplace_back(FMT("trades.{}.100ms", sec));
|
|
channel_demuxer.add_handler(ch)
|
|
.bind<&DeribitTradeAdaptor::on_trades>(sec_data.trade_hnd);
|
|
}
|
|
}
|
|
// If 'channels' is empty, it's a no-op
|
|
if (channels.empty()) {
|
|
return;
|
|
}
|
|
const auto sub = mk_deribit_sub(channels, ++sub_id_counter);
|
|
// Send the subscription to Deribit
|
|
session.subscribe(
|
|
sub, &channel_demuxer,
|
|
{ccapi::Message::Type::GENERIC_PUBLIC_SUBSCRIPTION});
|
|
}
|
|
|
|
template <class SecurityNames, int BatchSize = 32>
|
|
void batch_subscribe_md(SecurityNames security_names) {
|
|
auto batches = CHUNK(security_names, BatchSize);
|
|
for (auto batch : batches) {
|
|
subscribe_md(batch);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief Updates the securities map and subscribes market data for newly
|
|
* arrived securities
|
|
*/
|
|
void on_securities(vector<const Security *> secs) {
|
|
_INFO("on_securities. Received {} securities", secs.size());
|
|
// Assert no duplicates
|
|
for (const auto *sec : secs) {
|
|
bts_assert(sec != nullptr);
|
|
bts_assert(!CONTAINS_KEY(security_data_map, sec->desc()));
|
|
}
|
|
listener->on_securities(secs);
|
|
auto sec_names = TRANSFORM(secs, [](const auto *s) { return s->desc(); });
|
|
batch_subscribe_md(sec_names);
|
|
}
|
|
|
|
void on_instrument_state(const vector<json> &instrument_states) {
|
|
_INFO("on_instrument_state. Received {} jsons", instrument_states.size());
|
|
DeribitInstrumentRequest req;
|
|
for (const auto &j : instrument_states) {
|
|
DeribitInstrumentState istate;
|
|
j.get_to(istate);
|
|
_INFO("on_instrument_state. {}", istate);
|
|
if (CONTAINS_KEY(security_data_map, istate.instrument_name)) {
|
|
continue;
|
|
}
|
|
if (!criteria.includes(istate.instrument_name).value_or(true)) {
|
|
_INFO(
|
|
"on_instrument_state. SecurityCriteria excluded instrument "
|
|
"'{}' (will not request further metadata)",
|
|
istate.instrument_name);
|
|
continue;
|
|
}
|
|
switch (istate.state.value) {
|
|
case DeribitInstrumentStateType::CREATED:
|
|
case DeribitInstrumentStateType::STARTED:
|
|
req.add_name(istate.instrument_name);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
if (req.empty()) {
|
|
return;
|
|
}
|
|
_INFO("on_instrument_state. Requesting late instruments:\n{}", req);
|
|
sec_requestor.request(req);
|
|
}
|
|
};
|
|
|
|
DeribitSubscription::DeribitSubscription(
|
|
ccapi::EventDispatcher *dispatcher,
|
|
DeribitMarketDataConfig cfg,
|
|
IDGenerator *sec_id_store)
|
|
: me_(std::make_unique<PImpl>(dispatcher, std::move(cfg), sec_id_store)) {}
|
|
|
|
DeribitSubscription::DeribitSubscription(DeribitSubscription &&) noexcept =
|
|
default;
|
|
DeribitSubscription &DeribitSubscription::operator=(
|
|
DeribitSubscription &&) noexcept = default;
|
|
|
|
DeribitSubscription::~DeribitSubscription() = default;
|
|
|
|
void DeribitSubscription::start(shared_ptr<IMarketDataListener> listener) {
|
|
me_->start(std::move(listener));
|
|
}
|
|
|
|
} // namespace bts::md::deribit
|