Files
spark/src/app_sparkd/sparkd/md/deribit/DeribitSecurityRequestor.cpp
T
John Colvin 304c6fd4d1 refactor: Move domain types into new lib_domain
Also rename files in snake_case (standard naming convention for protos)
https://protobuf.dev/programming-guides/style/
2024-10-17 05:33:11 +00:00

449 lines
16 KiB
C++

/**
* @file
*
* General Notes:
* Deribit's websocket api implements Json-RPC 2.0. If you aren't familiar
* with this standard, follow the 'jsonrpc' link below to read the spec
* (it's pleasantly brief).
* @a https://www.jsonrpc.org/specification
*
* Request types:
* * get_instruments
* params: currency, instrument kind
* REST example: @a https://www.deribit.com/api/v2/public/get_instruments?currency=USDC
* @a https://docs.deribit.com/?#public-get_instruments
*
* * get_instrument
* params: name
* REST example: @a https://www.deribit.com/api/v2/public/get_instrument?instrument_name=BTC-PERPETUAL
* @a https://docs.deribit.com/?#public-get_instrument
*
* * get_currencies - gets list of currencies
* params: none
* @a https://docs.deribit.com/?#public-get_currencies
*
* * get_combos - gets a list of combos
* params: currency
* @a https://docs.deribit.com/?#public-get_combos
*
* * get_combo_details - gets a single combo
* params: name
* @a https://docs.deribit.com/?#public-get_combo_details
*
* Note that the 'get_instruments' request requires a currency param.
* Currencies may or may not be provided in DeribitMarketDataConfig.
* If omitted, we request them from the exchange, and then subscribe
* to instruments for each one.
*
* Although combos (spreads) are included in the 'get_instruments'
* response, their leg definitions are not. We obtain these via
* 'get_combos' and 'get_combo_details' requests. Then we join the response
* data by combo id to resolve the combos into proper spread Securities in
* our sys.
*
* Warning: If we subscribe to too many currency/instrument-kind pairs at
* once, we may exceed Deribit's request/subscription limits. If this
* happens, try specifying currencies in config. If it still happens, we'll
* need to revisit this issue, perhaps impl a request throttle.
*
* On late securities:
* When an instrument is added/removed, we receive a notification with the
* instrument's name (string id). Then we request its metadata through a
* 'get_instrument' request. If that instrument is a combo (spread), we
* send another request, 'get_combo_details', to get its legs. Once we have
* the legs, we can resolve the combo into a proper domain::Security and
* pass it to the callback.
*/
#include "DeribitSecurityRequestor.h"
#include "domain/protobufs/security_type.pb.h"
#include "domain/protobufs/venue.pb.h"
#include "domain/security.h"
#include "domain/security_criteria.h"
#include "spark/io/websocket/JsonRpcError.h"
#include "spark/io/websocket/JsonRpcHandler.h"
#include "spark/io/websocket/JsonRpcRequest.h"
#include "spark/logging/logging.h"
#include "sparkd/md/ccapi/CCApiCorrelationID.h"
#include "sparkd/md/ccapi/CCApiJsonRpcRequest.h"
#include "sparkd/md/ccapi/CCApiJsonRpcRouter.h"
#include "sparkd/md/ccapi/CCApiReader.h"
#include "sparkd/md/ccapi/CCApiSession.h"
#include "sparkd/md/deribit/DeribitCombo.h"
#include "sparkd/md/deribit/DeribitCurrency.h"
#include "sparkd/md/deribit/DeribitInstrument.h"
#include "sparkd/md/deribit/DeribitInstrumentKind.h"
#include "sparkd/md/deribit/DeribitInstrumentRequest.h"
#include "sparkd/md/deribit/DeribitInstrumentStore.h"
#include "sparkd/md/deribit/DeribitMessageType.h"
#include <algorithm>
#include <ccapi_cpp/ccapi_macro.h>
#include <ccapi_cpp/ccapi_message.h>
#include <ccapi_cpp/ccapi_session.h>
#include <nlohmann/json.hpp>
#include <string>
#include <unordered_set>
namespace bts::md::deribit {
#define _LOG(level, ...) \
LOG(md, level, "DeribitSecurityRequestor::" __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__)
using bts::domain::Security;
using bts::domain::SecurityCriteria;
using bts::domain::SecurityID;
using bts::io::websocket::JsonRpcError;
using bts::io::websocket::JsonRpcId;
using bts::io::websocket::JsonRpcRequest;
using nlohmann::json;
using std::string;
using std::unordered_set;
using std::vector;
#define VENUE bts::domain::protobufs::VENUE_DERIBIT
#define VENUE_NAME (bts::domain::protobufs::Venue_Name(VENUE))
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_DERIBIT
#define DERIBIT_MSG_TYPE_NAME(x) \
std::string { DeribitMessageType{DeribitMessageType::x}.name() }
#define SEC_TYPE(x) bts::domain::protobufs::SECURITY_TYPE_##x
#define CORR_ID(msg_type, ...) \
CCApiCorrelationID::from_parts( \
VENUE_NAME, DeribitMessageType::msg_type, __VA_ARGS__)
/**
* @brief Creates a 'get_combos' rpc-request object
*/
static CCApiJsonRpcRequest currencies_req() {
return {
{DERIBIT_CURRENCIES_METHOD, json::object(), JsonRpcId::create()},
CCAPI_VENUE_NAME,
CORR_ID(CURRENCIES, "ALL")};
}
/**
* @brief Creates a 'get_instrument' rpc-request object
*
* @param name The name of the instrument to get
*/
static CCApiJsonRpcRequest instrument_req(const string &name) {
return {
{DERIBIT_INSTRUMENT_METHOD,
{{"instrument_name", name}},
JsonRpcId::create()},
CCAPI_VENUE_NAME,
CORR_ID(INSTRUMENT, name)};
}
/**
* @brief Creates a 'get_instruments' rpc-request object
*
* @param currency The currency of the instruments to get
* @param kind The kind of instruments to get
*/
static CCApiJsonRpcRequest instruments_req(
const string &currency, DeribitInstrumentKind kind) {
json params{{"currency", currency}};
if (kind != DeribitInstrumentKind::NONE) {
params["kind"] = kind;
}
return {
{DERIBIT_INSTRUMENTS_METHOD, params, JsonRpcId::create()},
CCAPI_VENUE_NAME,
CORR_ID(INSTRUMENTS, currency, kind)};
}
/**
* @brief Creates a 'get_combos' rpc-request object
*
* @param currency The currency of the combos to get
*/
static CCApiJsonRpcRequest combos_req(const string &currency) {
return {
{DERIBIT_COMBOS_METHOD, {{"currency", currency}}, JsonRpcId::create()},
CCAPI_VENUE_NAME,
CORR_ID(COMBOS, currency)};
}
/**
* @brief Creates a 'get_combo_details' rpc-request object
*
* @param name The name of the combo whose details to get
*/
static CCApiJsonRpcRequest combo_details_req(const string &name) {
return {
{DERIBIT_COMBO_DETAILS_METHOD,
{{"combo_id", name}},
JsonRpcId::create()},
CCAPI_VENUE_NAME,
CORR_ID(COMBO_DETAILS, name)};
}
struct DeribitSecurityRequestor::PImpl {
explicit PImpl(
CCApiSession *const session,
SecurityCriteria criteria,
DeribitInstrumentStore *instrument_store,
vector<string> default_currencies)
: session_(session), criteria_(std::move(criteria)),
default_currencies_(std::move(default_currencies)),
request_currencies_(
default_currencies_.empty() &&
std::any_of(
criteria_.clauses.begin(),
criteria_.clauses.end(),
[](const auto &c) { return c.currencies.empty(); })),
instrument_store_(instrument_store) {
rpc_.error_handler<JsonRpcError>().bind<&PImpl::on_rpc_error_>(*this);
}
Callback &callback() { return callback_; }
void request_all_instruments() {
if (!request_currencies_) {
_INFO("request_all_instruments");
const auto req = DeribitInstrumentRequest::from_criteria(
criteria_, default_currencies_);
request_instruments(req);
return;
}
// Get the list of currencies, then request instruments for each one.
_INFO("request_all_instruments. Requesting currencies");
const auto curr_req = currencies_req();
rpc_.response_handler<vector<DeribitCurrency>>(curr_req.id())
.bind<&PImpl::request_currency_instruments_>(*this);
session_->subscribe(
curr_req.ccapi_sub(), &rpc_,
{ccapi::Message::Type::GENERIC_PUBLIC_SUBSCRIPTION});
}
void request_instruments(const DeribitInstrumentRequest &req) {
_INFO("request_instruments. Req\n:{}", req);
const auto ccapi_sub = prepare_request_(req);
if (ccapi_sub.empty()) {
_ERROR("request_instruments. Unable to submit request: "
"DeribitInstrumentRequest object is empty. Make sure "
"currencies are specified DeribitMarketDataConfig");
return;
}
session_->subscribe(
ccapi_sub, {ccapi::Message::Type::GENERIC_PUBLIC_SUBSCRIPTION});
}
private:
CCApiSession *const session_;
// 'criteria' and 'excluded_securities' collectively form the security
// filter predicate. Securities are forwarded to the callback if and only if
// they are included by 'criteria', and absent from 'excluded_securities'.
const SecurityCriteria criteria_;
const unordered_set<string> excluded_securities_;
const unordered_set<string> securities_;
const vector<string> default_currencies_;
const bool request_currencies_;
DeribitInstrumentStore *instrument_store_;
Callback callback_;
CCApiJsonRpcRouter rpc_;
void request_currency_instruments_(vector<DeribitCurrency> currencies) {
_INFO(
"request_currency_instruments. currencies: {}",
FMT_JOIN_FN(
currencies, ", ", [](const auto &c) { return c.currency; }));
DeribitInstrumentRequest req;
for (const auto &c : currencies) {
req.add_currency(c.currency);
}
request_instruments(req);
}
/**
* @brief Sets up handlers for an instrument request
* @return The ccapi Subscription for the request
*/
ccapi::Subscription prepare_instrument_req_(const std::string &name) {
const auto req = instrument_req(name);
rpc_.response_handler<vector<DeribitInstrument>>(req.id())
.bind<&PImpl::on_instrument_>(*this);
return req.ccapi_sub();
}
/**
* @brief Sets up handlers for an instruments request
* @return The ccapi Subscription for the request
*/
ccapi::Subscription prepare_instruments_req_(
const std::string &currency, DeribitInstrumentKind kind) {
const auto req = instruments_req(currency, kind);
rpc_.response_handler<vector<DeribitInstrument>>(req.id())
.bind<&PImpl::on_instruments_>(*this);
return req.ccapi_sub();
}
/**
* @brief Sets up handlers for a combos request
* @return The ccapi Subscription for the request
*/
ccapi::Subscription prepare_combos_req_(const std::string &currency) {
const auto req = combos_req(currency);
rpc_.response_handler<vector<DeribitCombo>>(req.id())
.bind<&PImpl::on_combos_>(*this);
return req.ccapi_sub();
}
/**
* @brief Sets up handlers for a 'get_combo_details' request
* @param name The name of the combo whose details to get
* @return The ccapi Subscription for the request
*/
ccapi::Subscription prepare_combo_details_req_(const std::string &name) {
const auto req = combo_details_req(name);
rpc_.response_handler<vector<DeribitCombo>>(req.id())
.bind<&PImpl::on_combos_>(*this);
return req.ccapi_sub();
}
/**
* @brief Sets up handlers for an instruments request
* @return The ccapi BatchSubscription for the request
*/
CCApiSession::BatchSubscription prepare_request_(
const DeribitInstrumentRequest &req) {
CCApiSession::BatchSubscription subs;
for (const auto &[currency, req] : req.currency_reqs()) {
bool include_combos = false;
for (const auto kind : req.kinds) {
if (kind.is_combo()) {
include_combos = true;
}
subs.push_back({prepare_instruments_req_(currency, kind), &rpc_});
}
if (include_combos) {
subs.push_back({prepare_combos_req_(currency), &rpc_});
}
}
for (const auto &name : req.name_reqs()) {
subs.push_back({prepare_instrument_req_(name), &rpc_});
}
return subs;
}
/**
* @brief Handles a 'get_instrument' response from Deribit
* @details Adds the instrument to the store, and fires the callback with
* the resultant new securities, which may include newly resolved spreads,
* in addition to the security in the event payload.
* @a https://docs.deribit.com/?#public-get_instrument
*/
void on_instrument_(vector<DeribitInstrument> instruments) {
_INFO(
"on_instrument. Received {} DeribitInstruments", instruments.size());
if (instruments.empty()) {
return;
}
bts_assert(instruments.size() == 1);
// Pass the instrument to the store
vector<const Security *> new_secs;
vector<const DeribitInstrument *> unresolved_combos;
instrument_store_->on_instruments(
instruments, new_secs, &unresolved_combos);
_INFO(
"on_instrument. Generated {} Securities, {} unresolved DeribitCombos",
new_secs.size(), unresolved_combos.size());
// Fire callback with new_secs
if (!new_secs.empty()) {
callback_(new_secs);
}
bts_assert(unresolved_combos.size() <= instruments.size());
if (!unresolved_combos.empty()) {
CCApiSession::BatchSubscription combo_details_subs;
for (const auto *di : unresolved_combos) {
const auto id = JsonRpcId::create();
const auto sub = prepare_combo_details_req_(di->instrument_name);
combo_details_subs.push_back({sub, &rpc_});
}
_INFO(
"on_instrument. Requesting combo details for '{}'",
unresolved_combos.at(0)->instrument_name);
session_->subscribe(combo_details_subs);
}
}
/**
* @brief Handles a 'get_instruments' response from Deribit
* @details Adds the instruments to the store, and fires the callback with
* the resultant new securities, which may include newly resolved spreads,
* in addition to the securities in the event payload.
* @a https://docs.deribit.com/?#public-get_instruments
*/
void on_instruments_(vector<DeribitInstrument> instruments) {
_INFO(
"on_instruments. Received {} DeribitInstruments.",
instruments.size());
// Pass the instruments to the store
vector<const Security *> new_secs;
instrument_store_->on_instruments(instruments, new_secs, nullptr);
_INFO("on_instruments. Generated {} Securities", new_secs.size());
// Fire callback with new secs
if (!new_secs.empty()) {
callback_(new_secs);
}
}
/**
* @brief Handles a 'get_combos' or 'get_combo_details' responses from
* Deribit (via CCApi).
* @details The only diff between the two responses is that 'get_combos'
* contains a list of DeribitCombos, while 'get_combo_details' contains a
* single DeribitCombo object.
*/
void on_combos_(vector<DeribitCombo> combos) {
_INFO("on_combos. Received {} DeribitCombos", combos.size());
// Pass the combos to the store
vector<const Security *> new_secs;
instrument_store_->on_combos(combos, new_secs);
_INFO("on_combos. Generated {} Securities", new_secs.size());
// Fire callback with new secs
if (!new_secs.empty()) {
callback_(new_secs);
}
}
void on_rpc_error_(JsonRpcError err) {
_ERROR("on_rpc_error. Error: {}", err);
}
};
DeribitSecurityRequestor::DeribitSecurityRequestor(
CCApiSession *const session,
SecurityCriteria criteria,
DeribitInstrumentStore *const instrument_store,
vector<string> default_currencies)
: me_(std::make_unique<PImpl>(
session, std::move(criteria), instrument_store, default_currencies)) {
}
DeribitSecurityRequestor::DeribitSecurityRequestor(
DeribitSecurityRequestor &&) noexcept = default;
DeribitSecurityRequestor &DeribitSecurityRequestor::operator=(
DeribitSecurityRequestor &&) noexcept = default;
DeribitSecurityRequestor::~DeribitSecurityRequestor() = default;
void DeribitSecurityRequestor::request(const DeribitInstrumentRequest &req) {
me_->request_instruments(req);
}
void DeribitSecurityRequestor::request_all() { me_->request_all_instruments(); }
DeribitSecurityRequestor::Callback &DeribitSecurityRequestor::callback() {
return me_->callback();
}
} // namespace bts::md::deribit