Files
spark/src/app_sparkd/sparkd/md/ftx/FTXSecurityRequestor.cpp
T
John Colvin bef84d6dc3 build: Install boost via vcpkg on linux, update ccapi
Old ccapi wasn't compatible with new boost
2026-03-20 17:02:44 +00:00

278 lines
9.7 KiB
C++

#include "FTXSecurityRequestor.h"
#include "spark/api/domain/SecurityType.pb.h"
#include "spark/api/domain/Venue.pb.h"
#include "spark/collections/Contains.h"
#include "spark/collections/Remove.h"
#include "spark/domain/Security.h"
#include "spark/domain/SecurityCriteria.h"
#include "spark/logging/logging.h"
#include "spark/persistence/IDGenerator.h"
#include "sparkd/md/ccapi/CCApiCorrelationID.h"
#include "sparkd/md/ccapi/CCApiMessageHandler.h"
#include "sparkd/md/ccapi/CCApiSession.h"
#include "sparkd/md/ccapi/ICCApiMessageHandler.h"
#include "sparkd/md/ftx/FTXFuture.h"
#include "sparkd/md/ftx/FTXMarket.h"
#include "sparkd/md/ftx/FTXMessageType.h"
#include <algorithm>
#include <ccapi_cpp/bts_session_options.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 <string>
#include <unordered_set>
namespace bts::md::ftx {
using api::domain::SecurityType;
using api::domain::Venue;
using api::domain::Venue_Name;
using bts::domain::Security;
using bts::domain::SecurityID;
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::api::domain::SECURITY_TYPE_##x
#define FTX_MSG_TYPE_NAME(x) \
std::string { FTXMessageType{x}.name() }
static ccapi::Request markets_req() {
auto secs_corr_id = CCApiCorrelationID::from_parts(
VENUE_NAME, FTX_MSG_TYPE_NAME(FTXMessageType::SECURITIES));
ccapi::Request secs_req{
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, "ftx"};
secs_req.appendParam(
{{CCAPI_HTTP_PROTOCOL, "https"},
{CCAPI_HTTP_HOST, "ftx.com"},
{CCAPI_HTTP_PORT, "443"},
{CCAPI_HTTP_PATH, "/api/markets"},
{CCAPI_HTTP_METHOD, "GET"}});
secs_req.setCorrelationId(secs_corr_id.to_string());
return secs_req;
}
static ccapi::Request futures_req() {
auto futs_corr_id = CCApiCorrelationID::from_parts(
VENUE_NAME, FTX_MSG_TYPE_NAME(FTXMessageType::FUTURES));
ccapi::Request futs_req{
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, "ftx"};
futs_req.appendParam(
{{CCAPI_HTTP_PROTOCOL, "https"},
{CCAPI_HTTP_HOST, "ftx.com"},
{CCAPI_HTTP_PORT, "443"},
{CCAPI_HTTP_PATH, "/api/futures"},
{CCAPI_HTTP_METHOD, "GET"}});
futs_req.setCorrelationId(futs_corr_id.to_string());
return futs_req;
}
static vector<string> get_sec_descs(const vector<Security> &sec_ptrs) {
vector<string> descs{sec_ptrs.size()};
std::transform(
sec_ptrs.begin(), sec_ptrs.end(), descs.begin(),
[](const auto &s) { return s.desc(); });
return descs;
}
static void validate_response(const ccapi::Event &event, bool is_expected) {
bts_assert_msgf(
event.getType() == ccapi::Event::Type::RESPONSE,
"Received event w/ unexpected type:\n{}", event.toPrettyString());
bts_assert_msgf(
is_expected, "Received unexpected response from FTX:\n{}",
event.toPrettyString());
}
struct FTXSecurityRequestor::PImpl {
// General Notes:
// FTX securities must be obtained from 2 different urls:
// 1) https://ftx.com/api/markets
// 2) https://ftx.com/api/futures
// Although all securities are listed in the response from (1), not all
// information is provided for futures (notably, the expiration date is
// missing!). This missing information is obtained from (2). Therefore,
// futures are published when (2) is received, while all other securities
// are published when (1) is received.
domain::SecurityCriteria criteria;
unordered_set<string> securities;
persistence::IDGenerator *sec_id_store;
// True when a 'markets' request is in flight
bool mkts_req_pending = false;
// True when a 'futures' request is in flight
bool futs_req_pending = false;
// True when someone called FTXSecurityRequestor::request while another
// request was already in flight. In this case, the 'external_req_pending'
// flag is used to signal that another request should be sent immediately
// after the current one finishes.
bool external_req_pending = false;
// These proxy handlers don't actually process new securities. Member methods
// in this class process the securities; we simply bind them to proxy handler
// callbacks. This is easier than defining separate ICCApiMessageHandler
// impls for 'markets', and 'futures', esp since they would need access to
// state contained in this class.
CCApiMessageHandler futs_handler_proxy;
CCApiMessageHandler mkts_handler_proxy;
Callback callback;
// The session automatically starts/stops in its ctr/dtr
CCApiSession session;
explicit PImpl(
ccapi::EventDispatcher *dispatcher,
domain::SecurityCriteria criteria,
persistence::IDGenerator *sec_id_store)
: criteria(std::move(criteria)), sec_id_store(sec_id_store),
session(
dispatcher, ccapi::SessionConfigs{}, {}, {ccapi::BtsVenues::FTX}) {
mkts_handler_proxy.callback().bind<&PImpl::on_markets>(*this);
futs_handler_proxy.callback().bind<&PImpl::on_futures>(*this);
}
bool is_busy() const { return mkts_req_pending || futs_req_pending; }
void request() {
external_req_pending = false;
mkts_req_pending = true;
futs_req_pending = true;
session.request(markets_req(), &mkts_handler_proxy);
session.request(futures_req(), &futs_handler_proxy);
}
/**
* @brief Parses securities from a ccapi::Message
*
* @details Only new securities that satisfy the 'SecurityCriteria' are added
* to \p added_secs
*
* @tparam TParser
* @param msg The ccapi::Message to parse
* @param types The types of securities to parse
* @param parser Ther parser to use
*/
template <class T>
void parse_secs(
const ccapi::Message &msg,
const vector<SecurityType> &types,
vector<Security> &added_secs) {
T::parse(msg, added_secs);
// Exclude secs that don't satisfy the SecurityCriteria
auto is_sec_excluded = [this, &types](const Security &sec) {
return !CONTAINS(types, sec.type()) ||
!criteria.includes_or_undefined(sec) ||
securities.count(sec.desc()) > 0;
};
REMOVE_IF(added_secs, is_sec_excluded);
// Assign security ids
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, sec.type(), sec.desc())};
sec.security_common.id = sec_id;
}
}
/**
* @brief Parses securities from ccapi messages, updates the securities set,
* and subscribes depth for newly arrived securities
*
* @details Securities that don't pass the criteria filter are ignored
*
* @tparam TParser The type of parser
* @param msgs Vector of ccapi messages containing securities
* @param types The types of securities to update (types must be explicitly
* specified to be included)
*/
template <class T>
void update_securities(
const vector<const ccapi::Message *> &msgs,
const vector<SecurityType> &types) {
vector<Security> added_secs;
for (const auto *msg : msgs) {
bts_assert_msgf(
msg->getType() == ccapi::Message::Type::GENERIC_PUBLIC_REQUEST,
"Received msg w/ unexpected type:\n{}", msg->toPrettyString());
parse_secs<T>(*msg, types, added_secs);
}
auto added_sec_descs = get_sec_descs(added_secs);
LOG(md, Info, "Received FTX securities:\n{}",
fmt::to_string(fmt::join(added_sec_descs, "\n")));
callback(added_secs);
}
/**
* Handles 'markets' update from CCApiSession
*/
bool on_markets(
const ccapi::Event &event,
ccapi::Session * /*session*/,
const vector<const ccapi::Message *> &msgs,
const CCApiCorrelationID & /*corr_id*/) {
validate_response(event, mkts_req_pending);
LOG(md, Diag, "Received FTX markets:\n{}", event.toPrettyString());
update_securities<FTXMarket>(msgs, {SEC_TYPE(SPOT)});
mkts_req_pending = false;
if (external_req_pending && !is_busy()) {
request();
}
return true;
}
/**
* Handles 'futures' update from CCApiSession
*/
bool on_futures(
const ccapi::Event &event,
ccapi::Session * /*session*/,
const vector<const ccapi::Message *> &msgs,
const CCApiCorrelationID & /*corr_id*/) {
validate_response(event, futs_req_pending);
LOG(md, Diag, "Received FTX futures:\n{}", event.toPrettyString());
update_securities<FTXFuture>(msgs, {SEC_TYPE(FUTURE)});
futs_req_pending = false;
if (external_req_pending && !is_busy()) {
request();
}
return true;
}
};
FTXSecurityRequestor::FTXSecurityRequestor(
ccapi::EventDispatcher *dispatcher,
domain::SecurityCriteria criteria,
persistence::IDGenerator *sec_id_store)
: me_(std::make_unique<PImpl>(
dispatcher, std::move(criteria), sec_id_store)) {}
FTXSecurityRequestor::FTXSecurityRequestor(FTXSecurityRequestor &&) noexcept =
default;
FTXSecurityRequestor &FTXSecurityRequestor::operator=(
FTXSecurityRequestor &&) noexcept = default;
FTXSecurityRequestor::~FTXSecurityRequestor() = default;
void FTXSecurityRequestor::request() {
if (is_busy()) {
me_->external_req_pending = true;
return;
}
me_->request();
}
bool FTXSecurityRequestor::is_busy() const { return me_->is_busy(); }
FTXSecurityRequestor::Callback &FTXSecurityRequestor::callback() {
return me_->callback;
}
} // namespace bts::md::ftx