feat: Add Binance Coin Futures market data
This commit is contained in:
1 parent
03e19afe1d
commit
c00e4fcb6b
31 files changed
+1629
No files matched your search
@@ -92,6 +92,11 @@ else()
|
||||
add_compile_definitions(BINANCE_USDS_FUTURES_INSTRUMENTS_PATH="/dapi/v1/exchangeInfo")
|
||||
add_compile_definitions(BINANCE_USDS_FUTURES_PRICE_STATS_PATH="/dapi/v1/ticker/24hr")
|
||||
|
||||
# ** Binance Coin Futures **
|
||||
add_compile_definitions(CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE="https://dapi.binance.com")
|
||||
add_compile_definitions(BINANCE_COIN_FUTURES_INSTRUMENTS_PATH="/dapi/v1/exchangeInfo")
|
||||
add_compile_definitions(BINANCE_COIN_FUTURES_PRICE_STATS_PATH="/dapi/v1/ticker/24hr")
|
||||
|
||||
# ** Deribit **
|
||||
add_compile_definitions(DERIBIT_INSTRUMENT_PATH="/api/v2/public/get_instrument")
|
||||
add_compile_definitions(DERIBIT_INSTRUMENTS_PATH="/api/v2/public/get_instruments")
|
||||
|
||||
@@ -105,6 +105,7 @@ namespace bts.api {
|
||||
Security.ExchangeDataOneofCase.Deribit => security.Deribit.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.Ftx => security.Ftx.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.Binance => security.Binance.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.BinanceCoinFutures => security.BinanceCoinFutures.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.BinanceUs => security.BinanceUs.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.BinanceUsdsFutures => security.BinanceUsdsFutures.SecurityDesc,
|
||||
Security.ExchangeDataOneofCase.Coinbase => security.Coinbase.SecurityDesc,
|
||||
@@ -151,6 +152,7 @@ namespace bts.api {
|
||||
domain.Venue.Deribit => Venue.Deribit,
|
||||
domain.Venue.Ftx => Venue.Ftx,
|
||||
domain.Venue.Binance => Venue.Binance,
|
||||
domain.Venue.BinanceCoinFutures => Venue.BinanceCoinFutures,
|
||||
domain.Venue.BinanceUs => Venue.BinanceUs,
|
||||
domain.Venue.BinanceUsdsFutures => Venue.BinanceUsdsFutures,
|
||||
domain.Venue.Glbx => Venue.Glbx,
|
||||
@@ -171,6 +173,7 @@ namespace bts.api {
|
||||
Venue.Deribit => domain.Venue.Deribit,
|
||||
Venue.Ftx => domain.Venue.Ftx,
|
||||
Venue.Binance => domain.Venue.Binance,
|
||||
Venue.BinanceCoinFutures => domain.Venue.BinanceCoinFutures,
|
||||
Venue.BinanceUs => domain.Venue.BinanceUs,
|
||||
Venue.BinanceUsdsFutures => domain.Venue.BinanceUsdsFutures,
|
||||
Venue.Coinbase => domain.Venue.Coinbase,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
syntax = "proto3";
|
||||
|
||||
import "lib/api/domain/SecurityCriteria.proto";
|
||||
import "lib/api/core/RegexFormatting.proto";
|
||||
|
||||
package bts.api.md;
|
||||
|
||||
option csharp_namespace = "bts.api.md";
|
||||
option cc_enable_arenas = true;
|
||||
|
||||
message BinanceCoinFuturesMarketDataConfig {
|
||||
uint32 num_depth_levels = 1;
|
||||
uint32 depth_throttle_ms = 2;
|
||||
bts.api.domain.SecurityCriteria security_criteria = 3;
|
||||
// Market data isn't subscribed for securities listed here (even if they are
|
||||
// included by 'security_criteria'). There are some securities that don't
|
||||
// fit into our system just yet, such as 'BTCBIDR', which trades in prices
|
||||
// larger than our cpp 'domain::Price' class supports.
|
||||
repeated string excluded_securities = 4;
|
||||
|
||||
// The list of instruments at Binance is obtained via an 'exchangeInfo' http
|
||||
// rest request. In the corresponding response, each instrument has a 'pair'
|
||||
// field, which is analgous to a security desc in our system (a unique
|
||||
// human-readable string representation of the security). For some
|
||||
// instruments, the string representation used in the market depth request is
|
||||
// slightly different.
|
||||
//
|
||||
// 'depth_symbol_mappings' is a list of regex find/replace patterns to
|
||||
// apply (to the 'pair' field) when subscribing to depth.
|
||||
repeated bts.api.core.RegexFormatting security_desc_formattings = 5;
|
||||
|
||||
string url_rest_base = 6;
|
||||
string url_ws_base = 7;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ syntax = "proto3";
|
||||
|
||||
import "lib/api/md/FTXMarketDataConfig.proto";
|
||||
import "lib/api/md/BinanceMarketDataConfig.proto";
|
||||
import "lib/api/md/BinanceCoinFuturesMarketDataConfig.proto";
|
||||
import "lib/api/md/BinanceUsMarketDataConfig.proto";
|
||||
import "lib/api/md/CoinbaseMarketDataConfig.proto";
|
||||
import "lib/api/md/BinanceUsdsFuturesMarketDataConfig.proto";
|
||||
@@ -21,6 +22,7 @@ package bts.api.md;
|
||||
message MarketDataConfig {
|
||||
repeated FTXMarketDataConfig ftx = 1;
|
||||
repeated BinanceMarketDataConfig binance = 2;
|
||||
repeated BinanceCoinFuturesMarketDataConfig binance_coin_futures = 11;
|
||||
repeated BinanceUsdsFuturesMarketDataConfig binance_usds_futures = 3;
|
||||
repeated BinanceUsMarketDataConfig binance_us = 4;
|
||||
repeated DeribitMarketDataConfig deribit = 5;
|
||||
|
||||
@@ -66,6 +66,7 @@ bool AdminServiceUtils::has_exchange(
|
||||
case api::Venue::VENUE_DERIBIT: // TODO
|
||||
case api::Venue::VENUE_FTX:
|
||||
case api::Venue::VENUE_BINANCE:
|
||||
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::Venue::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
|
||||
@@ -185,6 +186,7 @@ AdminServiceUtils::resolve_connection(
|
||||
case api::Venue::VENUE_FTX:
|
||||
case api::Venue::VENUE_OKX:
|
||||
case api::Venue::VENUE_BINANCE:
|
||||
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::Venue::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::Venue::VENUE_TAIFEX:
|
||||
@@ -454,6 +456,7 @@ std::string AdminServiceUtils::find_account_exchange_account(
|
||||
case api::Venue::VENUE_DERIBIT: // TODO
|
||||
case api::Venue::VENUE_FTX: // TODO
|
||||
case api::Venue::VENUE_BINANCE: // TODO
|
||||
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::Venue::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
|
||||
@@ -751,6 +754,7 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record(
|
||||
}
|
||||
case api::VENUE_FTX: // TODO
|
||||
case api::VENUE_BINANCE: // TODO
|
||||
case api::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::VENUE_BINANCE_USDS_FUTURES:
|
||||
@@ -1145,6 +1149,7 @@ std::string AdminServiceUtils::find_user_exchange_id(
|
||||
case api::Venue::VENUE_DERIBIT: // TODO
|
||||
case api::Venue::VENUE_FTX: // TODO
|
||||
case api::Venue::VENUE_BINANCE: // TODO
|
||||
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::Venue::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
|
||||
@@ -1180,6 +1185,7 @@ std::string AdminServiceUtils::find_user_company_id(
|
||||
case api::Venue::VENUE_DERIBIT:
|
||||
case api::Venue::VENUE_FTX: // TODO
|
||||
case api::Venue::VENUE_BINANCE: // TODO
|
||||
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
case api::Venue::VENUE_BINANCE_US:
|
||||
case api::Venue::VENUE_COINBASE:
|
||||
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
|
||||
|
||||
@@ -19,6 +19,11 @@ SymbolLists {
|
||||
symbol: "BTC"
|
||||
symbol: "ETH"
|
||||
}
|
||||
list {
|
||||
key: "BINANCE_COIN_FUTURES"
|
||||
symbol: "BTC"
|
||||
symbol: "ETH"
|
||||
}
|
||||
list {
|
||||
key: "TAIFEX"
|
||||
symbol: "QFFH"
|
||||
@@ -140,6 +145,11 @@ Symbols {
|
||||
spot: @SymbolLists.list[BINANCE].symbol
|
||||
spread: @SymbolLists.list[BINANCE].symbol
|
||||
}
|
||||
venues {
|
||||
name: "VENUE_BINANCE_COIN_FUTURES"
|
||||
future: @SymbolLists.list[BINANCE_COIN_FUTURES].symbol
|
||||
spread: @SymbolLists.list[BINANCE_COIN_FUTURES].symbol
|
||||
}
|
||||
venues {
|
||||
name: "VENUE_BINANCE_US"
|
||||
spot: @SymbolLists.list[BINANCE_US].symbol
|
||||
|
||||
@@ -13,6 +13,19 @@ MarketDataConfig {
|
||||
}
|
||||
}
|
||||
|
||||
binance_coin_futures {
|
||||
num_depth_levels: 5
|
||||
url_rest_base: "https://testnet.binancefuture.com"
|
||||
url_ws_base: "wss://dstream.binance.com"
|
||||
security_criteria {
|
||||
clauses {
|
||||
security_types: SECURITY_TYPE_FUTURE
|
||||
symbols: "BTC"
|
||||
symbols: "ETH"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
binance_us {
|
||||
num_depth_levels: 5
|
||||
url_rest_base: "https://api.binance.us"
|
||||
|
||||
@@ -13,6 +13,19 @@ MarketDataConfig {
|
||||
}
|
||||
}
|
||||
|
||||
binance_coin_futures {
|
||||
num_depth_levels: 5
|
||||
url_rest_base: "https://dapi.binance.com"
|
||||
url_ws_base: "wss://dstream.binance.com"
|
||||
security_criteria {
|
||||
clauses {
|
||||
security_types: SECURITY_TYPE_FUTURE
|
||||
symbols: "BTC"
|
||||
symbols: "ETH"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
binance_usds_futures {
|
||||
num_depth_levels: 5
|
||||
url_rest_base: "https://dapi.binance.com"
|
||||
|
||||
@@ -33,6 +33,8 @@ api::domain::Venue DomainSecurityUtils::convert(bts::api::Venue venue) {
|
||||
return DOMAIN_VENUE(SIM);
|
||||
case bts::api::Venue::VENUE_BINANCE:
|
||||
return DOMAIN_VENUE(BINANCE);
|
||||
case bts::api::Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
return DOMAIN_VENUE(BINANCE_COIN_FUTURES);
|
||||
case bts::api::Venue::VENUE_BINANCE_US:
|
||||
return DOMAIN_VENUE(BINANCE_US);
|
||||
case bts::api::VENUE_BINANCE_USDS_FUTURES:
|
||||
@@ -65,6 +67,8 @@ bts::api::Venue DomainSecurityUtils::convert(api::domain::Venue venue) {
|
||||
return api::Venue::VENUE_FTX;
|
||||
case DOMAIN_VENUE(BINANCE):
|
||||
return api::Venue::VENUE_BINANCE;
|
||||
case DOMAIN_VENUE(BINANCE_COIN_FUTURES):
|
||||
return api::Venue::VENUE_BINANCE_COIN_FUTURES;
|
||||
case DOMAIN_VENUE(BINANCE_US):
|
||||
return api::Venue::VENUE_BINANCE_US;
|
||||
case DOMAIN_VENUE(BINANCE_USDS_FUTURES):
|
||||
@@ -189,6 +193,9 @@ bool DomainSecurityUtils::get_security_desc(
|
||||
case bts::api::Security::ExchangeDataCase::kBinance:
|
||||
desc = security.binance().security_desc();
|
||||
break;
|
||||
case bts::api::Security::ExchangeDataCase::kBinanceCoinFutures:
|
||||
desc = security.binance_coin_futures().security_desc();
|
||||
break;
|
||||
case bts::api::Security::ExchangeDataCase::kBinanceUs:
|
||||
desc = security.binance_us().security_desc();
|
||||
break;
|
||||
|
||||
@@ -15,6 +15,7 @@ enum Venue {
|
||||
VENUE_DERIBIT = 400;
|
||||
VENUE_FTX = 410;
|
||||
VENUE_BINANCE = 420;
|
||||
VENUE_BINANCE_COIN_FUTURES = 425;
|
||||
VENUE_BINANCE_USDS_FUTURES = 430;
|
||||
VENUE_BINANCE_US = 440;
|
||||
VENUE_COINBASE = 450;
|
||||
@@ -106,6 +107,11 @@ message BinanceExchangeData {
|
||||
string security_desc = 2;
|
||||
}
|
||||
|
||||
message BinanceCoinFuturesExchangeData {
|
||||
int64 exchange_id = 1;
|
||||
string security_desc = 2;
|
||||
}
|
||||
|
||||
message BinanceUsdsFuturesExchangeData {
|
||||
int64 exchange_id = 1;
|
||||
string security_desc = 2;
|
||||
@@ -228,6 +234,7 @@ message Security {
|
||||
DeribitExchangeData deribit = 240;
|
||||
FTXExchangeData ftx = 250;
|
||||
BinanceExchangeData binance = 260;
|
||||
BinanceCoinFuturesExchangeData binance_coin_futures = 265;
|
||||
BinanceUsdsFuturesExchangeData binance_usds_futures = 270;
|
||||
BinanceUsExchangeData binance_us = 280;
|
||||
CoinbaseExchangeData coinbase = 290;
|
||||
|
||||
@@ -129,6 +129,11 @@ void convert_security(const FixedSecurity &source, Security *presult) {
|
||||
dest.mutable_binance()->set_security_desc(source.security_desc());
|
||||
dest.mutable_binance()->set_exchange_id(source.numeric_id);
|
||||
break;
|
||||
case Venue::VENUE_BINANCE_COIN_FUTURES:
|
||||
dest.mutable_binance_coin_futures()->set_security_desc(
|
||||
source.security_desc());
|
||||
dest.mutable_binance_coin_futures()->set_exchange_id(source.numeric_id);
|
||||
break;
|
||||
case Venue::VENUE_BINANCE_US:
|
||||
dest.mutable_binance_us()->set_security_desc(source.security_desc());
|
||||
dest.mutable_binance_us()->set_exchange_id(source.numeric_id);
|
||||
@@ -248,6 +253,8 @@ uint64_t exchange_id(const Security &security) {
|
||||
return security.ftx().exchange_id();
|
||||
case Security::ExchangeDataCase::kBinance:
|
||||
return security.binance().exchange_id();
|
||||
case Security::ExchangeDataCase::kBinanceCoinFutures:
|
||||
return security.binance_coin_futures().exchange_id();
|
||||
case Security::ExchangeDataCase::kBinanceUs:
|
||||
return security.binance_us().exchange_id();
|
||||
case Security::ExchangeDataCase::kCoinbase:
|
||||
@@ -324,6 +331,10 @@ void convert_security(
|
||||
dest.numeric_id = src.binance().exchange_id();
|
||||
dest.security_desc(src.binance().security_desc());
|
||||
break;
|
||||
case Security::ExchangeDataCase::kBinanceCoinFutures:
|
||||
dest.numeric_id = src.binance_coin_futures().exchange_id();
|
||||
dest.security_desc(src.binance_coin_futures().security_desc());
|
||||
break;
|
||||
case Security::ExchangeDataCase::kBinanceUs:
|
||||
dest.numeric_id = src.binance_us().exchange_id();
|
||||
dest.security_desc(src.binance_us().security_desc());
|
||||
|
||||
@@ -179,6 +179,9 @@ struct MDConsumerGroup {
|
||||
case api::VENUE_BINANCE:
|
||||
this->mic = "BINANCE";
|
||||
break;
|
||||
case api::VENUE_BINANCE_COIN_FUTURES:
|
||||
this->mic = "BINANCE_COIN_FUTURES";
|
||||
break;
|
||||
case api::VENUE_BINANCE_US:
|
||||
this->mic = "BINANCE_US";
|
||||
break;
|
||||
|
||||
@@ -16,6 +16,7 @@ EnumOptionNames<api::Venue> VenueOption::names() {
|
||||
NAME_PAIR(api::VENUE_DERIBIT),
|
||||
NAME_PAIR(api::VENUE_FTX),
|
||||
NAME_PAIR(api::VENUE_BINANCE),
|
||||
NAME_PAIR(api::VENUE_BINANCE_COIN_FUTURES),
|
||||
NAME_PAIR(api::VENUE_BINANCE_US),
|
||||
NAME_PAIR(api::VENUE_COINBASE),
|
||||
NAME_PAIR(api::VENUE_BINANCE_USDS_FUTURES),
|
||||
@@ -41,6 +42,8 @@ std::string VenueOption::name(api::Venue venue) {
|
||||
return "ftx";
|
||||
case api::VENUE_BINANCE:
|
||||
return "binance";
|
||||
case api::VENUE_BINANCE_COIN_FUTURES:
|
||||
return "binance_coin_futures";
|
||||
case api::VENUE_BINANCE_US:
|
||||
return "binance_us";
|
||||
case api::VENUE_COINBASE:
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
#include "server/sparkd/md/MarketDataRegistrationFactory.h"
|
||||
#include "server/sparkd/md/MarketDataSubscription.h"
|
||||
#include "server/sparkd/md/binance/BinanceSubscription.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_subscription.h"
|
||||
#include "server/sparkd/md/binance_us/BinanceUsSubscription.h"
|
||||
#include "server/sparkd/md/binance_usds_futures/BinanceUsdsFuturesSubscription.h"
|
||||
#include "server/sparkd/md/cboe/CboeMarketDataHandler.h"
|
||||
@@ -189,6 +190,17 @@ MarketDataRegistration MarketDataGateway::_start_cc(
|
||||
p->listener.get()});
|
||||
}
|
||||
|
||||
// Binance Coin Futures
|
||||
for (const auto &binance_cfs : cfg.binance_coin_futures()) {
|
||||
auto p =
|
||||
me_->venue_listeners.emplace_back(std::make_shared<VenueListenerData>(
|
||||
bts::api::VENUE_BINANCE_COIN_FUTURES));
|
||||
listener_data.subscription.add(
|
||||
binance_coin_futures::BinanceCoinFuturesSubscription{
|
||||
&me_->dispatcher, binance_cfs, me_->sec_id_store.get(),
|
||||
p->listener.get()});
|
||||
}
|
||||
|
||||
// Binance US
|
||||
for (const auto &binance_us : cfg.binance_us()) {
|
||||
auto p = me_->venue_listeners.emplace_back(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "MarketDataSubscription.h"
|
||||
#include "server/sparkd/md/binance/BinanceSubscription.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_subscription.h"
|
||||
#include "server/sparkd/md/binance_us/BinanceUsSubscription.h"
|
||||
#include "server/sparkd/md/binance_usds_futures/BinanceUsdsFuturesSubscription.h"
|
||||
#include "server/sparkd/md/coinbase/CoinbaseSubscription.h"
|
||||
@@ -16,6 +17,8 @@ using std::vector;
|
||||
struct MarketDataSubscription::PImpl {
|
||||
vector<ftx::FTXSubscription> ftx_subs;
|
||||
vector<binance::BinanceSubscription> binance_subs;
|
||||
vector<binance_coin_futures::BinanceCoinFuturesSubscription>
|
||||
binance_coin_futures_subs;
|
||||
vector<binance_us::BinanceUsSubscription> binance_us_subs;
|
||||
vector<coinbase::CoinbaseSubscription> coinbase_subs;
|
||||
vector<binance_usds_futures::BinanceUsdsFuturesSubscription>
|
||||
@@ -34,6 +37,11 @@ void MarketDataSubscription::add(binance::BinanceSubscription sub) {
|
||||
me_->binance_subs.push_back(std::move(sub));
|
||||
}
|
||||
|
||||
void MarketDataSubscription::add(
|
||||
binance_coin_futures::BinanceCoinFuturesSubscription sub) {
|
||||
me_->binance_coin_futures_subs.push_back(std::move(sub));
|
||||
}
|
||||
|
||||
void MarketDataSubscription::add(binance_us::BinanceUsSubscription sub) {
|
||||
me_->binance_us_subs.push_back(std::move(sub));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ namespace bts::md::binance {
|
||||
class BinanceSubscription;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
class BinanceCoinFuturesSubscription;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_us {
|
||||
class BinanceUsSubscription;
|
||||
}
|
||||
@@ -44,6 +48,7 @@ class MarketDataSubscription {
|
||||
~MarketDataSubscription();
|
||||
|
||||
void add(binance::BinanceSubscription);
|
||||
void add(binance_coin_futures::BinanceCoinFuturesSubscription);
|
||||
void add(binance_us::BinanceUsSubscription);
|
||||
void add(coinbase::CoinbaseSubscription);
|
||||
void add(binance_usds_futures::BinanceUsdsFuturesSubscription);
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
#include "binance_coin_future.h"
|
||||
#include "lib/domain/Price.h"
|
||||
#include "lib/domain/Quantity.h"
|
||||
#include "lib/domain/Security.h"
|
||||
#include "lib/io/JsonDumper.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
#include <ccapi_cpp/ccapi_message.h>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using bts::api::domain::SecurityType;
|
||||
using bts::domain::FutureSecurity;
|
||||
using bts::domain::Price;
|
||||
using bts::domain::Quantity;
|
||||
using bts::domain::Security;
|
||||
using bts::io::JsonDumper;
|
||||
using bts::io::JsonReader;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#define SEC_TYPE(x) bts::api::domain::SECURITY_TYPE_##x
|
||||
#define VENUE api::domain::Venue::VENUE_BINANCE_COIN_FUTURES;
|
||||
|
||||
static string deduce_sym_from_name(const string &name) {
|
||||
const std::regex word_regex("(\\w+)");
|
||||
const auto words_begin =
|
||||
std::sregex_iterator(name.begin(), name.end(), word_regex);
|
||||
const auto words_end = std::sregex_iterator();
|
||||
if (words_begin != words_end) {
|
||||
return words_begin->str();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
static std::string deduce_sym(const BinanceCoinFuture &bfut) {
|
||||
if (!bfut.base_asset.empty()) {
|
||||
return bfut.base_asset;
|
||||
}
|
||||
if (!bfut.pair.empty()) {
|
||||
return bfut.pair;
|
||||
}
|
||||
return deduce_sym_from_name(bfut.symbol);
|
||||
}
|
||||
|
||||
void BinanceCoinFuture::parse(
|
||||
const ccapi::Message &msg, vector<Security> &securities) {
|
||||
const auto &sec_elements = msg.getElementList();
|
||||
for (const auto &sec_el : sec_elements) {
|
||||
const auto &sec_props = sec_el.getNameValueMap();
|
||||
auto it = sec_props.find(CCAPI_HTTP_BODY);
|
||||
if (it == sec_props.end()) {
|
||||
continue;
|
||||
}
|
||||
const auto &body = it->second;
|
||||
const auto js = nlohmann::json::parse(body);
|
||||
JsonReader jr{&js};
|
||||
vector<BinanceCoinFuture> binance_futs;
|
||||
if (!jr.read("symbols", binance_futs)) {
|
||||
const auto js_str = js.dump(2);
|
||||
LOG(md, Error,
|
||||
"Invalid json. Expected field 'symbols' to contain list of future "
|
||||
"secs:\n{}",
|
||||
js_str);
|
||||
continue;
|
||||
}
|
||||
for (const auto &bf : binance_futs) {
|
||||
auto &sec = securities.emplace_back();
|
||||
auto &scomm = sec.security_common;
|
||||
scomm.venue = VENUE;
|
||||
|
||||
scomm.exchange_sec_id = bf.symbol;
|
||||
scomm.desc = bf.symbol;
|
||||
scomm.symbol = deduce_sym(bf);
|
||||
scomm.asset = scomm.symbol;
|
||||
scomm.group = scomm.symbol;
|
||||
scomm.currency = bf.quote_asset.name();
|
||||
|
||||
scomm.min_price = Price::from_double(bf.filter_tuple.price.min_price);
|
||||
scomm.max_price = Price::from_double(bf.filter_tuple.price.max_price);
|
||||
scomm.min_price_increment = bf.filter_tuple.price.tick_size;
|
||||
|
||||
scomm.min_quantity = bf.filter_tuple.lot_size.min_qty;
|
||||
scomm.max_quantity = bf.filter_tuple.lot_size.max_qty;
|
||||
scomm.min_quantity_increment = bf.filter_tuple.lot_size.step_size;
|
||||
|
||||
auto &fut = sec.security.emplace<FutureSecurity>();
|
||||
fut.expiration = bf.delivery_date;
|
||||
LOG(md, Diag,
|
||||
"Converted BinanceCoinFuture:\n{}\nto domain::Security:\n{}",
|
||||
JsonDumper::dump(bf), JsonDumper::dump(sec));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void from_json(const nlohmann::json &j, BinanceCoinFuture &sec) {
|
||||
JsonReader jr{&j};
|
||||
bool success =
|
||||
jr.read("symbol", sec.symbol) && jr.read("pair", sec.pair) &&
|
||||
jr.read("contractType", sec.contract_type) &&
|
||||
jr.read_epoch_millis("deliveryDate", sec.delivery_date) &&
|
||||
jr.read_epoch_millis("onboardDate", sec.onboard_date) &&
|
||||
jr.read("contractStatus", sec.contract_status) &&
|
||||
jr.read("contractSize", sec.contract_size) &&
|
||||
jr.read("marginAsset", sec.margin_asset) &&
|
||||
jr.read("maintMarginPercent", sec.maint_margin_percent) &&
|
||||
jr.read("requiredMarginPercent", sec.required_margin_percent) &&
|
||||
jr.read("baseAsset", sec.base_asset) &&
|
||||
jr.read("quoteAsset", sec.quote_asset) &&
|
||||
jr.read("pricePrecision", sec.price_precision) &&
|
||||
jr.read("quantityPrecision", sec.quantity_precision) &&
|
||||
jr.read("baseAssetPrecision", sec.base_asset_precision) &&
|
||||
jr.read("quotePrecision", sec.quote_precision) &&
|
||||
jr.read("equalQtyPrecision", sec.equal_qty_precision) &&
|
||||
jr.read("maxMoveOrderLimit", sec.max_move_order_limit) &&
|
||||
jr.read("triggerProtect", sec.trigger_protect) &&
|
||||
jr.read("underlyingType", sec.underlying_type) &&
|
||||
jr.read("underlyingSubType", sec.underlying_sub_type) &&
|
||||
jr.read("filters", sec.filter_tuple);
|
||||
if (!success) {
|
||||
const string j_str = j.dump(2);
|
||||
LOG(md, Error, "Failed to parse json to BinanceCoinFuture:\n{}", j_str);
|
||||
}
|
||||
}
|
||||
|
||||
void to_json(nlohmann::json &j, const BinanceCoinFuture &sec) {
|
||||
j = nlohmann::json{
|
||||
{"symbol", sec.symbol},
|
||||
{"pair", sec.pair},
|
||||
{"contractType", sec.contract_type},
|
||||
{"deliveryDate", sec.delivery_date.to_iso_string()},
|
||||
{"onboardDate", sec.onboard_date.to_iso_string()},
|
||||
{"contractStatus", sec.contract_status},
|
||||
{"contractSize", sec.contract_size},
|
||||
{"marginAsset", sec.margin_asset},
|
||||
{"maintMarginPercent", sec.maint_margin_percent},
|
||||
{"requiredMarginPercent", sec.required_margin_percent},
|
||||
{"baseAsset", sec.base_asset},
|
||||
{"quoteAsset", sec.quote_asset},
|
||||
{"pricePrecision", sec.price_precision},
|
||||
{"quantityPrecision", sec.quantity_precision},
|
||||
{"baseAssetPrecision", sec.base_asset_precision},
|
||||
{"quotePrecision", sec.quote_precision},
|
||||
{"equalQtyPrecision", sec.equal_qty_precision},
|
||||
{"maxMoveOrderLimit", sec.max_move_order_limit},
|
||||
{"triggerProtect", sec.trigger_protect},
|
||||
{"underlyingType", sec.underlying_type},
|
||||
{"underlyingSubType", sec.underlying_sub_type},
|
||||
{"filterTuple", sec.filter_tuple}};
|
||||
}
|
||||
|
||||
std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuture &spot) noexcept {
|
||||
out << spot.symbol;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/md/binance/BinanceInstrumentStatus.h"
|
||||
#include "server/sparkd/md/binance/BinanceQuoteAsset.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_contract_type.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_filter_tuple.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts::domain {
|
||||
class Security;
|
||||
}
|
||||
|
||||
namespace ccapi {
|
||||
class Message;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Represents a Future security at Binance Coin Futures
|
||||
*/
|
||||
class BinanceCoinFuture {
|
||||
public:
|
||||
std::string symbol;
|
||||
std::string pair;
|
||||
BinanceCoinFuturesContractType contract_type;
|
||||
core::TimeStamp delivery_date;
|
||||
core::TimeStamp onboard_date;
|
||||
binance::BinanceInstrumentStatus contract_status;
|
||||
double contract_size;
|
||||
std::string margin_asset;
|
||||
double maint_margin_percent;
|
||||
double required_margin_percent;
|
||||
std::string base_asset;
|
||||
binance::BinanceQuoteAsset quote_asset;
|
||||
std::uint32_t price_precision;
|
||||
std::uint32_t quantity_precision;
|
||||
std::uint32_t base_asset_precision;
|
||||
std::uint32_t quote_precision;
|
||||
std::uint32_t equal_qty_precision;
|
||||
std::uint32_t max_move_order_limit;
|
||||
double trigger_protect;
|
||||
std::string underlying_type;
|
||||
std::vector<std::string> underlying_sub_type;
|
||||
BinanceCoinFuturesFilterTuple filter_tuple;
|
||||
|
||||
static void parse(
|
||||
const ccapi::Message &msg, std::vector<domain::Security> &securities);
|
||||
};
|
||||
|
||||
void from_json(const nlohmann::json &j, BinanceCoinFuture &fut);
|
||||
|
||||
void to_json(nlohmann::json &j, const BinanceCoinFuture &fut);
|
||||
|
||||
std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuture &fut) noexcept;
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/core/EnumMacros.h"
|
||||
#include "lib/core/FMT_IMPL.h"
|
||||
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
// clang-format off
|
||||
#define FOR_ALL_VALUES(per_value) \
|
||||
per_value(BinanceCoinFuturesContractType, NONE) \
|
||||
per_value(BinanceCoinFuturesContractType, PERPETUAL) \
|
||||
per_value(BinanceCoinFuturesContractType, CURRENT_QUARTER) \
|
||||
per_value(BinanceCoinFuturesContractType, NEXT_QUARTER)
|
||||
// clang-format on
|
||||
|
||||
/**
|
||||
* @brief Represents contract types at Binance Coin Futures
|
||||
*/
|
||||
ENUM_CLASS_DEF(BinanceCoinFuturesContractType, FOR_ALL_VALUES)
|
||||
|
||||
#undef FOR_ALL_VALUES
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
|
||||
FMT_IMPL(
|
||||
bts::md::binance_coin_futures::BinanceCoinFuturesContractType,
|
||||
t,
|
||||
"{}",
|
||||
t.name());
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/io/JsonDumper.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
#include "server/sparkd/md/binance/BinanceFilterType.h"
|
||||
#include "server/sparkd/md/binance/BinanceLotSizeFilter.h"
|
||||
#include "server/sparkd/md/binance/BinanceMarketLotSizeFilter.h"
|
||||
#include "server/sparkd/md/binance/BinancePriceFilter.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_max_num_orders_filter.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_percent_price_filter.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using namespace bts::md::binance;
|
||||
|
||||
class BinanceCoinFuturesFilterTuple {
|
||||
public:
|
||||
BinanceLotSizeFilter lot_size;
|
||||
BinanceMarketLotSizeFilter market_lot_size;
|
||||
BinanceCoinFuturesMaxNumOrdersFilter max_num_orders;
|
||||
BinanceCoinFuturesPercentPriceFilter percent_price;
|
||||
BinancePriceFilter price;
|
||||
};
|
||||
|
||||
void from_json(const nlohmann::json &j, BinanceCoinFuturesFilterTuple &f);
|
||||
void to_json(nlohmann::json &j, const BinanceCoinFuturesFilterTuple &f);
|
||||
|
||||
std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesFilterTuple &f) noexcept;
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
inline void from_json(
|
||||
const nlohmann::json &j, BinanceCoinFuturesFilterTuple &f) {
|
||||
for (const auto &el : j) {
|
||||
io::JsonReader jr{&el};
|
||||
BinanceFilterType filter_type;
|
||||
if (!jr.read("filterType", filter_type)) {
|
||||
continue;
|
||||
}
|
||||
switch (filter_type.value) {
|
||||
case BinanceFilterType::LOT_SIZE:
|
||||
jr.read(f.lot_size);
|
||||
break;
|
||||
case BinanceFilterType::MARKET_LOT_SIZE:
|
||||
jr.read(f.market_lot_size);
|
||||
break;
|
||||
case BinanceFilterType::MAX_NUM_ORDERS:
|
||||
jr.read(f.max_num_orders);
|
||||
break;
|
||||
case BinanceFilterType::PERCENT_PRICE:
|
||||
jr.read(f.percent_price);
|
||||
break;
|
||||
case BinanceFilterType::PRICE_FILTER:
|
||||
jr.read(f.price);
|
||||
break;
|
||||
case BinanceFilterType::NONE:
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void to_json(nlohmann::json &j, const BinanceCoinFuturesFilterTuple &f) {
|
||||
j = nlohmann::json{
|
||||
{"lotSize", f.lot_size},
|
||||
{"marketLotSize", f.market_lot_size},
|
||||
{"maxNumOrders", f.max_num_orders},
|
||||
{"percentPrice", f.percent_price},
|
||||
{"price", f.price}};
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesFilterTuple &f) noexcept {
|
||||
out << io::JsonDumper::dump(f);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/io/JsonDumper.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
#include "server/sparkd/md/binance/BinanceFilterType.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Represents a Max Num Orders Filter at Binance Coin Futures
|
||||
*
|
||||
*/
|
||||
class BinanceCoinFuturesMaxNumOrdersFilter {
|
||||
public:
|
||||
binance::BinanceFilterType filter_type;
|
||||
double limit;
|
||||
};
|
||||
|
||||
void from_json(
|
||||
const nlohmann::json &j, BinanceCoinFuturesMaxNumOrdersFilter &f);
|
||||
|
||||
std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesMaxNumOrdersFilter &f) noexcept;
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
inline void from_json(
|
||||
const nlohmann::json &j, BinanceCoinFuturesMaxNumOrdersFilter &f) {
|
||||
io::JsonReader jr{&j};
|
||||
bool success =
|
||||
jr.read("filterType", f.filter_type) && jr.read("limit", f.limit);
|
||||
if (!success) {
|
||||
const auto j_str = j.dump(2);
|
||||
LOG(md, Error,
|
||||
"Failed to parse json to BinanceCoinFuturesMaxNumOrdersFilter:\n{}",
|
||||
j_str);
|
||||
}
|
||||
}
|
||||
|
||||
inline void to_json(
|
||||
nlohmann::json &j, const BinanceCoinFuturesMaxNumOrdersFilter &f) {
|
||||
j = nlohmann::json{{"filterType", f.filter_type}, {"limit", f.limit}};
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesMaxNumOrdersFilter &f) noexcept {
|
||||
out << io::JsonDumper::dump(f, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/core/EnumMacros.h"
|
||||
#include "lib/core/FMT_IMPL.h"
|
||||
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
// clang-format off
|
||||
#define FOR_ALL_VALUES(per_value) \
|
||||
per_value(BinanceCoinFuturesMessageType, NONE) \
|
||||
per_value(BinanceCoinFuturesMessageType, EXCHANGE_INFO) \
|
||||
per_value(BinanceCoinFuturesMessageType, DEPTH) \
|
||||
per_value(BinanceCoinFuturesMessageType, MINI_TICKER) \
|
||||
per_value(BinanceCoinFuturesMessageType, TICKER) \
|
||||
per_value(BinanceCoinFuturesMessageType, STATISTICS)
|
||||
// clang-format on
|
||||
|
||||
/**
|
||||
* @brief Represents the different types of messages received from Binance Coin
|
||||
* Futures
|
||||
*
|
||||
* @details Each enum value is associated with a particular type of request (or
|
||||
* subscription) that is sent to the exchange, and a particular handler type
|
||||
* designed to adapt the messages for an IMarketDataListener.
|
||||
* Note: Some message types are native to the exchange, while others are CCApi
|
||||
* constructs.
|
||||
*/
|
||||
ENUM_CLASS_DEF(BinanceCoinFuturesMessageType, FOR_ALL_VALUES)
|
||||
|
||||
#undef FOR_ALL_VALUES
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
|
||||
FMT_IMPL(
|
||||
bts::md::binance_coin_futures::BinanceCoinFuturesMessageType,
|
||||
t,
|
||||
"{}",
|
||||
t.name());
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/io/JsonDumper.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
#include "server/sparkd/md/binance/BinanceFilterType.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Represents a Percent Price Filter at Binance Coin Futures
|
||||
*
|
||||
* @details This filter defines valid range for a price based on the mark
|
||||
* price.
|
||||
*
|
||||
* @a https://developers.binance.com/docs/derivatives/coin-margined-futures/common-definition#percent_price
|
||||
*/
|
||||
class BinanceCoinFuturesPercentPriceFilter {
|
||||
public:
|
||||
binance::BinanceFilterType filter_type;
|
||||
double multiplier_up;
|
||||
double multiplier_down;
|
||||
std::uint32_t multiplier_decimal;
|
||||
};
|
||||
|
||||
void from_json(
|
||||
const nlohmann::json &j, BinanceCoinFuturesPercentPriceFilter &f);
|
||||
|
||||
void to_json(nlohmann::json &j, const BinanceCoinFuturesPercentPriceFilter &f);
|
||||
|
||||
std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesPercentPriceFilter &f) noexcept;
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
inline void from_json(
|
||||
const nlohmann::json &j, BinanceCoinFuturesPercentPriceFilter &f) {
|
||||
io::JsonReader jr{&j};
|
||||
bool success = jr.read("filterType", f.filter_type) &&
|
||||
jr.read("multiplierUp", f.multiplier_up) &&
|
||||
jr.read("multiplierDown", f.multiplier_down) &&
|
||||
jr.read("multiplierDecimal", f.multiplier_decimal);
|
||||
if (!success) {
|
||||
const auto j_str = j.dump(2);
|
||||
LOG(md, Error,
|
||||
"Failed to parse json to BinanceCoinFuturesPercentPriceFilter:\n{}",
|
||||
j_str);
|
||||
}
|
||||
}
|
||||
|
||||
inline void to_json(
|
||||
nlohmann::json &j, const BinanceCoinFuturesPercentPriceFilter &f) {
|
||||
j = nlohmann::json{
|
||||
{"filterType", f.filter_type},
|
||||
{"multiplierUp", f.multiplier_up},
|
||||
{"multiplierDown", f.multiplier_down},
|
||||
{"multiplierDecimal", f.multiplier_decimal}};
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(
|
||||
std::ostream &out, const BinanceCoinFuturesPercentPriceFilter &f) noexcept {
|
||||
out << io::JsonDumper::dump(f, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "binance_coin_futures_price_statistics.h"
|
||||
#include "lib/domain/Price.h"
|
||||
#include "lib/domain/Quantity.h"
|
||||
#include "lib/domain/SecurityMarketDataStatistics.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiReader.h"
|
||||
|
||||
#include <ccapi_cpp/ccapi_macro.h>
|
||||
#include <ccapi_cpp/ccapi_message.h>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using bts::domain::Price;
|
||||
using bts::domain::Quantity;
|
||||
using bts::domain::SecurityMarketDataStatistics;
|
||||
using bts::io::JsonReader;
|
||||
using std::map;
|
||||
using std::pair;
|
||||
using std::size_t;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
static bool parse(
|
||||
const map<string, string> &name_values,
|
||||
vector<BinanceCoinFuturesPriceStatistics> &result) {
|
||||
CCApiReader ccapi_reader{&name_values};
|
||||
nlohmann::json js;
|
||||
if (!ccapi_reader.read(CCAPI_HTTP_BODY, js)) {
|
||||
return false;
|
||||
}
|
||||
JsonReader jr{&js};
|
||||
if (!jr.read(result)) {
|
||||
LOG(md, Error,
|
||||
"Failed to read BinanceCoinFuturePriceStatistics json:\n{}", js);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
pair<size_t, size_t> BinanceCoinFuturesPriceStatistics::parse(
|
||||
const ccapi::Message &msg,
|
||||
vector<BinanceCoinFuturesPriceStatistics> &result) {
|
||||
size_t n_hits = 0;
|
||||
size_t n_misses = 0;
|
||||
for (const auto &sec_el : msg.getElementList()) {
|
||||
const auto &hp_props = sec_el.getNameValueMap();
|
||||
auto it = hp_props.find(CCAPI_HTTP_BODY);
|
||||
if (it == hp_props.end()) {
|
||||
continue;
|
||||
}
|
||||
(binance_coin_futures::parse(hp_props, result) ? n_hits : n_misses)++;
|
||||
}
|
||||
return {n_hits, n_misses};
|
||||
}
|
||||
|
||||
void BinanceCoinFuturesPriceStatistics::to_security_statistics(
|
||||
SecurityMarketDataStatistics &result) const {
|
||||
result.open = Price::from_double(openPrice);
|
||||
// TODO: get appropriate settle price (it isn't in this data, though there
|
||||
// is a 'close time', which implies there is a 'close price' to go with it)
|
||||
// result.settle = Price::from_double(last_price);
|
||||
result.settle = Price::nan();
|
||||
result.high = Price::from_double(highPrice);
|
||||
result.low = Price::from_double(lowPrice);
|
||||
result.volume.value() = static_cast<Quantity::Value>(volume);
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/io/JsonMacros.h"
|
||||
#include "lib/io/JsonReader.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ccapi {
|
||||
class Message;
|
||||
}
|
||||
|
||||
namespace bts::domain {
|
||||
class SecurityMarketDataStatistics;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Represents a Binance Coin Futures '24hr Ticker Price Change
|
||||
* Statistics' update
|
||||
*
|
||||
* @a https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/24hr-Ticker-Price-Change-Statistics
|
||||
*/
|
||||
class BinanceCoinFuturesPriceStatistics {
|
||||
public:
|
||||
std::string symbol;
|
||||
std::string pair;
|
||||
double priceChange;
|
||||
double priceChangePercent;
|
||||
double weightedAvgPrice;
|
||||
double lastPrice;
|
||||
double lastQty;
|
||||
double openPrice;
|
||||
double highPrice;
|
||||
double lowPrice;
|
||||
double volume;
|
||||
double baseVolume;
|
||||
// epoch millis
|
||||
std::int64_t openTime;
|
||||
// epoch millis
|
||||
std::int64_t closeTime;
|
||||
std::int64_t firstId;
|
||||
std::int64_t lastId;
|
||||
std::int64_t count;
|
||||
|
||||
static std::pair<std::size_t, std::size_t> parse(
|
||||
const ccapi::Message &msg,
|
||||
std::vector<BinanceCoinFuturesPriceStatistics> &result);
|
||||
|
||||
void to_security_statistics(
|
||||
domain::SecurityMarketDataStatistics &result) const;
|
||||
};
|
||||
|
||||
// clang-format off
|
||||
#define FOR_EACH(op) \
|
||||
op(symbol) \
|
||||
op(pair) \
|
||||
op(priceChange) \
|
||||
op(priceChangePercent) \
|
||||
op(weightedAvgPrice) \
|
||||
op(lastPrice) \
|
||||
op(lastQty) \
|
||||
op(openPrice) \
|
||||
op(highPrice) \
|
||||
op(lowPrice) \
|
||||
op(volume) \
|
||||
op(baseVolume) \
|
||||
op(openTime) \
|
||||
op(closeTime) \
|
||||
op(firstId) \
|
||||
op(lastId) \
|
||||
op(count)
|
||||
// clang-format on
|
||||
|
||||
SPARK_TO_JSON_IMPL(BinanceCoinFuturesPriceStatistics, FOR_EACH);
|
||||
SPARK_FROM_JSON_IMPL(BinanceCoinFuturesPriceStatistics, FOR_EACH);
|
||||
OSTREAM_JSON_IMPL(BinanceCoinFuturesPriceStatistics)
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#include "binance_coin_futures_price_statistics_adaptor.h"
|
||||
#include "lib/domain/SecurityID.h"
|
||||
#include "lib/domain/SecurityMarketDataStatistics.h"
|
||||
#include "lib/md/IMarketDataListener.h"
|
||||
#include "lib/utils/bts_fatal.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_price_statistics.h"
|
||||
|
||||
#include <ccapi_cpp/ccapi_event.h>
|
||||
#include <ccapi_cpp/ccapi_message.h>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using bts::domain::SecurityID;
|
||||
using bts::domain::SecurityMarketDataStatistics;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#define _ASSERT_MSGF(condition, ...) \
|
||||
bts_assert_msgf( \
|
||||
condition, "BinanceCoinFuturesPriceStatisticsAdaptor::" __VA_ARGS__)
|
||||
#define _FATAL_MSGF(...) \
|
||||
BTS_FATAL_MSGF("BinanceCoinFuturesPriceStatisticsAdaptor::" __VA_ARGS__)
|
||||
#define _LOG(level, ...) \
|
||||
LOG(md, level, "BinanceCoinFuturesPriceStatisticsAdaptor::" __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__)
|
||||
|
||||
#define VENUE_NAME (Venue_Name(Venue::BINANCE))
|
||||
|
||||
struct BinanceCoinFuturesPriceStatisticsAdaptor::PImpl {
|
||||
SecurityID sec_id;
|
||||
IMarketDataListener *listener;
|
||||
};
|
||||
|
||||
BinanceCoinFuturesPriceStatisticsAdaptor::
|
||||
BinanceCoinFuturesPriceStatisticsAdaptor(
|
||||
SecurityID sec_id, IMarketDataListener *listener)
|
||||
: me_(std::make_unique<PImpl>()) {
|
||||
bts_assert(listener != nullptr);
|
||||
me_->sec_id = sec_id;
|
||||
me_->listener = listener;
|
||||
}
|
||||
|
||||
BinanceCoinFuturesPriceStatisticsAdaptor::
|
||||
~BinanceCoinFuturesPriceStatisticsAdaptor() = default;
|
||||
|
||||
void BinanceCoinFuturesPriceStatisticsAdaptor::on_messages(
|
||||
const ccapi::Event &event,
|
||||
ccapi::Session * /*session*/,
|
||||
const vector<const ccapi::Message *> &msgs,
|
||||
const CCApiCorrelationID & /*corr_id*/) {
|
||||
vector<SecurityMarketDataStatistics> stats_recs;
|
||||
for (const auto *msg : msgs) {
|
||||
vector<BinanceCoinFuturesPriceStatistics> binance_stats_recs;
|
||||
const auto [n_hits, n_misses] =
|
||||
BinanceCoinFuturesPriceStatistics::parse(*msg, binance_stats_recs);
|
||||
if (n_misses > 0) {
|
||||
const auto n_total = n_hits + n_misses;
|
||||
_ERROR(
|
||||
"on_messages. Parse failed on {}/{} elements:\n{}", n_misses,
|
||||
n_total, event.toStringPretty());
|
||||
continue;
|
||||
}
|
||||
for (const auto &bsr : binance_stats_recs) {
|
||||
auto &sec_stats = stats_recs.emplace_back();
|
||||
bsr.to_security_statistics(sec_stats);
|
||||
sec_stats.security_id = me_->sec_id;
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (const auto &stats_rec : stats_recs) {
|
||||
me_->listener->on_security_statistics(stats_rec);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/domain/SecurityID.h"
|
||||
#include "server/sparkd/md/ccapi/ICCApiMessageHandler.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace bts::md {
|
||||
class IMarketDataListener;
|
||||
}
|
||||
|
||||
namespace bts::persistence {
|
||||
class IDGenerator;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Adapts Binance Coin Futures '24hr Ticker Price Change Statistics'
|
||||
* updates for an IMarketDataListener, by translating and forwarding event
|
||||
* payloads to the listener via 'IMarketDataListener::on_security_statistics'.
|
||||
*/
|
||||
class BinanceCoinFuturesPriceStatisticsAdaptor : public ICCApiMessageHandler {
|
||||
public:
|
||||
BinanceCoinFuturesPriceStatisticsAdaptor(
|
||||
domain::SecurityID sec_id, IMarketDataListener *listener);
|
||||
|
||||
~BinanceCoinFuturesPriceStatisticsAdaptor();
|
||||
|
||||
void on_messages(
|
||||
const ccapi::Event &event,
|
||||
ccapi::Session *session,
|
||||
const std::vector<const ccapi::Message *> &msgs,
|
||||
const CCApiCorrelationID &corr_id) override;
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me_;
|
||||
};
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
#include "binance_coin_futures_security_requestor.h"
|
||||
#include "lib/api/md/BinanceCoinFuturesMarketDataConfig.pb.h"
|
||||
#include "lib/collections/Contains.h"
|
||||
#include "lib/collections/Remove.h"
|
||||
#include "lib/collections/UnorderedSetFactory.h"
|
||||
#include "lib/core/FMT.h"
|
||||
#include "lib/domain/Security.h"
|
||||
#include "lib/domain/SecurityCriteria.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/persistence/IDGenerator.h"
|
||||
#include "lib/utils/bts_fatal.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_future.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_message_type.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiCorrelationID.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiMessageHandler.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiSession.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <ccapi_cpp/ccapi_macro.h>
|
||||
#include <ccapi_cpp/ccapi_message.h>
|
||||
#include <ccapi_cpp/ccapi_request.h>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using api::domain::Venue;
|
||||
using api::domain::Venue_Name;
|
||||
using api::md::BinanceCoinFuturesMarketDataConfig;
|
||||
using bts::collections::UnorderedSetFactory;
|
||||
using bts::domain::Security;
|
||||
using bts::domain::SecurityCriteria;
|
||||
using bts::domain::SecurityID;
|
||||
using bts::persistence::IDGenerator;
|
||||
using std::string;
|
||||
using std::unordered_set;
|
||||
using std::vector;
|
||||
|
||||
#define _ASSERT_MSGF(condition, ...) \
|
||||
bts_assert_msgf( \
|
||||
condition, "BinanceCoinFuturesSecurityRequestor::" __VA_ARGS__)
|
||||
#define _FATAL_MSGF(...) \
|
||||
BTS_FATAL_MSGF("BinanceCoinFuturesSecurityRequestor::" __VA_ARGS__)
|
||||
#define _LOG(level, ...) \
|
||||
LOG(md, level, "BinanceCoinFuturesSecurityRequestor::" __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__)
|
||||
|
||||
#define VENUE Venue::VENUE_BINANCE_COIN_FUTURES
|
||||
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE_COIN_FUTURES))
|
||||
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES
|
||||
#define VENUE_PRICE_STATS_PATH BINANCE_COIN_FUTURES_PRICE_STATS_PATH
|
||||
#define VENUE_INSTRUMENTS_PATH BINANCE_COIN_FUTURES_INSTRUMENTS_PATH
|
||||
|
||||
#define MESSAGE_TYPE_NAME(x) \
|
||||
std::string { BinanceCoinFuturesMessageType{x}.name() }
|
||||
|
||||
static ccapi::Request exchange_info_req() {
|
||||
auto corr_id = CCApiCorrelationID::from_parts(
|
||||
VENUE_NAME,
|
||||
MESSAGE_TYPE_NAME(BinanceCoinFuturesMessageType::EXCHANGE_INFO));
|
||||
ccapi::Request req{
|
||||
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, CCAPI_VENUE_NAME};
|
||||
req.appendParam(
|
||||
{{CCAPI_HTTP_PROTOCOL, "https"},
|
||||
{CCAPI_HTTP_PORT, "443"},
|
||||
{CCAPI_HTTP_PATH, BINANCE_COIN_FUTURES_INSTRUMENTS_PATH},
|
||||
{CCAPI_HTTP_METHOD, "GET"},
|
||||
{CCAPI_HTTP_HEADERS, "Content-Type:application/json"}});
|
||||
req.setCorrelationId(corr_id.to_string());
|
||||
return 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;
|
||||
}
|
||||
|
||||
struct BinanceCoinFuturesSecurityRequestor::PImpl {
|
||||
// General Notes:
|
||||
// Securities are in the 'symbols' field (list) in the json from
|
||||
// https://dapi.binance.com/dapi/v1/exchangeInfo
|
||||
|
||||
// The session automatically starts/stops in its ctr/dtr
|
||||
CCApiSession *session;
|
||||
|
||||
// 'criteria' and 'excluded_securities' collectively form the 'include
|
||||
// security' predicate. Only securities that are included by the criteria,
|
||||
// and aren't listed in 'excluded_securities', are forwarded to the callback.
|
||||
const SecurityCriteria criteria;
|
||||
const unordered_set<string> excluded_securities;
|
||||
|
||||
unordered_set<string> securities;
|
||||
IDGenerator *const sec_id_store;
|
||||
// True when an 'exchange info' request is in flight
|
||||
bool exch_info_req_pending = false;
|
||||
// True when someone called BinanceCoinFutureRequestor::request while
|
||||
// another request was already in flight. In this case,
|
||||
// 'external_req_pending' is flipped to true, signaling 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 exch_info_handler_proxy;
|
||||
Callback callback;
|
||||
|
||||
explicit PImpl(
|
||||
CCApiSession *const session,
|
||||
const BinanceCoinFuturesMarketDataConfig &cfg,
|
||||
IDGenerator *sec_id_store)
|
||||
: session(session),
|
||||
criteria(SecurityCriteria::from_proto(cfg.security_criteria())),
|
||||
excluded_securities(
|
||||
UnorderedSetFactory<string>::create(cfg.excluded_securities())),
|
||||
sec_id_store(sec_id_store) {
|
||||
exch_info_handler_proxy.callback().bind<&PImpl::on_exchange_info>(*this);
|
||||
}
|
||||
|
||||
bool is_busy() const { return exch_info_req_pending; }
|
||||
|
||||
void request() {
|
||||
external_req_pending = false;
|
||||
exch_info_req_pending = true;
|
||||
const auto req = exchange_info_req();
|
||||
LOG(md, Info, "Requesting securities from venue {}. Request: {}",
|
||||
VENUE_NAME, req.toString());
|
||||
session->request(req, &exch_info_handler_proxy);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parses securities from a ccapi::Message
|
||||
*
|
||||
* @details Only new securities that satisfy the 'SecurityCriteria' are added
|
||||
* to \p added_secs
|
||||
*
|
||||
* @param msg The ccapi::Message to parse
|
||||
*/
|
||||
void parse_secs(const ccapi::Message &msg, vector<Security> &added_secs) {
|
||||
BinanceCoinFuture::parse(msg, added_secs);
|
||||
auto is_sec_excluded = [this](const Security &sec) {
|
||||
return !criteria.includes_or_undefined(sec) ||
|
||||
CONTAINS(excluded_securities, sec.desc()) ||
|
||||
securities.count(sec.desc()) > 0;
|
||||
};
|
||||
REMOVE_IF(added_secs, is_sec_excluded);
|
||||
// Assign security ids
|
||||
for (auto &sec : added_secs) {
|
||||
// Assert they are 0 by default. The parser is not supposed to assign
|
||||
// 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, 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
|
||||
*
|
||||
* @param msgs Vector of ccapi messages containing securities
|
||||
*/
|
||||
void update_securities(const vector<const ccapi::Message *> &msgs) {
|
||||
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->toStringPretty());
|
||||
parse_secs(*msg, added_secs);
|
||||
}
|
||||
auto added_sec_descs = get_sec_descs(added_secs);
|
||||
LOG(md, Info, "Received Binance Coin Futures securities:\n{}",
|
||||
FMT_JOIN(added_sec_descs, "\n"));
|
||||
callback(added_secs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles 'exchange info' update from CCApiSession
|
||||
*/
|
||||
bool on_exchange_info(
|
||||
const ccapi::Event &event,
|
||||
ccapi::Session * /*session*/,
|
||||
const vector<const ccapi::Message *> &msgs,
|
||||
const CCApiCorrelationID & /*corr_id*/) {
|
||||
_INFO(
|
||||
"on_exchange_info. {} event",
|
||||
ccapi::Event::typeToString(event.getType()));
|
||||
switch (event.getType()) {
|
||||
case ccapi::Event::Type::REQUEST_STATUS:
|
||||
break;
|
||||
case ccapi::Event::Type::RESPONSE:
|
||||
update_securities(msgs);
|
||||
exch_info_req_pending = false;
|
||||
if (external_req_pending && !is_busy()) {
|
||||
request();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
_FATAL_MSGF(
|
||||
"on_exchange_info. {} event was unexpected:\n{}",
|
||||
ccapi::Event::typeToString(event.getType()),
|
||||
event.toStringPretty());
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
BinanceCoinFuturesSecurityRequestor::BinanceCoinFuturesSecurityRequestor(
|
||||
CCApiSession *const session,
|
||||
const BinanceCoinFuturesMarketDataConfig &cfg,
|
||||
IDGenerator *sec_id_store)
|
||||
: me_(std::make_unique<PImpl>(session, cfg, sec_id_store)) {}
|
||||
|
||||
BinanceCoinFuturesSecurityRequestor::BinanceCoinFuturesSecurityRequestor(
|
||||
BinanceCoinFuturesSecurityRequestor &&) noexcept = default;
|
||||
BinanceCoinFuturesSecurityRequestor &
|
||||
BinanceCoinFuturesSecurityRequestor::operator=(
|
||||
BinanceCoinFuturesSecurityRequestor &&) noexcept = default;
|
||||
|
||||
BinanceCoinFuturesSecurityRequestor::~BinanceCoinFuturesSecurityRequestor() =
|
||||
default;
|
||||
|
||||
void BinanceCoinFuturesSecurityRequestor::request() {
|
||||
if (is_busy()) {
|
||||
me_->external_req_pending = true;
|
||||
return;
|
||||
}
|
||||
me_->request();
|
||||
}
|
||||
|
||||
bool BinanceCoinFuturesSecurityRequestor::is_busy() const {
|
||||
return me_->is_busy();
|
||||
}
|
||||
|
||||
BinanceCoinFuturesSecurityRequestor::Callback &
|
||||
BinanceCoinFuturesSecurityRequestor::callback() {
|
||||
return me_->callback;
|
||||
}
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/utils/Delegate.h"
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace ccapi {
|
||||
class EventDispatcher;
|
||||
}
|
||||
|
||||
namespace bts::md {
|
||||
class CCApiSession;
|
||||
class IMarketDataListener;
|
||||
} // namespace bts::md
|
||||
|
||||
namespace bts::persistence {
|
||||
class IDGenerator;
|
||||
}
|
||||
|
||||
namespace bts::domain {
|
||||
class Security;
|
||||
class SecurityCriteria;
|
||||
} // namespace bts::domain
|
||||
|
||||
namespace bts::api::md {
|
||||
class BinanceCoinFuturesMarketDataConfig;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Requests securities (futures) from Binance Coin Futures
|
||||
*
|
||||
* @details Uses ccapi infrastructure to send the request
|
||||
*/
|
||||
class BinanceCoinFuturesSecurityRequestor {
|
||||
public:
|
||||
BinanceCoinFuturesSecurityRequestor(
|
||||
CCApiSession *const session,
|
||||
const api::md::BinanceCoinFuturesMarketDataConfig &cfg,
|
||||
persistence::IDGenerator *sec_id_store);
|
||||
|
||||
BinanceCoinFuturesSecurityRequestor(
|
||||
const BinanceCoinFuturesSecurityRequestor &) noexcept = delete;
|
||||
BinanceCoinFuturesSecurityRequestor(
|
||||
BinanceCoinFuturesSecurityRequestor &&) noexcept;
|
||||
BinanceCoinFuturesSecurityRequestor &operator=(
|
||||
const BinanceCoinFuturesSecurityRequestor &) noexcept = delete;
|
||||
BinanceCoinFuturesSecurityRequestor &operator=(
|
||||
BinanceCoinFuturesSecurityRequestor &&) noexcept;
|
||||
|
||||
~BinanceCoinFuturesSecurityRequestor();
|
||||
|
||||
using Callback = core::Delegate<void(std::vector<domain::Security>)>;
|
||||
|
||||
Callback &callback();
|
||||
|
||||
/**
|
||||
* @brief Request securities from the exchange
|
||||
*
|
||||
* @details Does NOT generate a live-updating stream of securities. Callers
|
||||
* must call 'request' periodically to keep their securities in sync with the
|
||||
* active set at the exchange.
|
||||
*/
|
||||
void request();
|
||||
|
||||
/**
|
||||
* @brief Indicates whether or not a request is in-progress
|
||||
*
|
||||
* @details Concurrent requests are not supported
|
||||
*/
|
||||
bool is_busy() const;
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me_;
|
||||
};
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,327 @@
|
||||
#include "binance_coin_futures_subscription.h"
|
||||
#include "lib/api/domain/Venue.pb.h"
|
||||
#include "lib/api/md/BinanceCoinFuturesMarketDataConfig.pb.h"
|
||||
#include "lib/core/FMT.h"
|
||||
#include "lib/domain/Security.h"
|
||||
#include "lib/domain/SecurityCriteria.h"
|
||||
#include "lib/domain/SecurityID.h"
|
||||
#include "lib/io/ProtoPrinter.h"
|
||||
#include "lib/io/QueryParams.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/md/IMarketDataListener.h"
|
||||
#include "lib/persistence/IDGenerator.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_message_type.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_price_statistics_adaptor.h"
|
||||
#include "server/sparkd/md/binance_coin_futures/binance_coin_futures_security_requestor.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiCorrelationID.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiMarketDepthAdaptor.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiSession.h"
|
||||
#include "server/sparkd/md/ccapi/CCApiTradeAdaptor.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 <map>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
using bts::api::domain::SecurityType;
|
||||
using bts::api::domain::Venue;
|
||||
using bts::api::domain::Venue_Name;
|
||||
using bts::api::md::BinanceCoinFuturesMarketDataConfig;
|
||||
using bts::domain::Security;
|
||||
using bts::domain::SecurityCriteria;
|
||||
using bts::domain::SecurityID;
|
||||
using bts::io::ProtoPrinter;
|
||||
using bts::io::QueryParams;
|
||||
using bts::persistence::IDGenerator;
|
||||
using std::pair;
|
||||
using std::string;
|
||||
using std::uint32_t;
|
||||
using std::unique_ptr;
|
||||
using std::unordered_map;
|
||||
using std::vector;
|
||||
|
||||
#define VENUE Venue::VENUE_BINANCE_COIN_FUTURES
|
||||
#define VENUE_NAME (Venue_Name(Venue::VENUE_BINANCE_COIN_FUTURES))
|
||||
#define CCAPI_VENUE_NAME CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES
|
||||
#define VENUE_PRICE_STATS_PATH BINANCE_COIN_FUTURES_PRICE_STATS_PATH
|
||||
|
||||
/**
|
||||
* @brief Apply overrides from our config to a ccapi::SessionConfigs object
|
||||
* that is otherwise populated with defaults
|
||||
*/
|
||||
static ccapi::SessionConfigs mk_session_cfg(
|
||||
const BinanceCoinFuturesMarketDataConfig &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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the docs
|
||||
* @a https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-market-streams/Partial-Book-Depth-Streams
|
||||
*/
|
||||
static string mk_depth_opts(const BinanceCoinFuturesMarketDataConfig &cfg) {
|
||||
QueryParams opts;
|
||||
switch (cfg.num_depth_levels()) {
|
||||
case 5:
|
||||
case 10:
|
||||
case 20:
|
||||
// The exchange only supports these num levels
|
||||
opts[CCAPI_MARKET_DEPTH_MAX] = std::to_string(cfg.num_depth_levels());
|
||||
break;
|
||||
case 0:
|
||||
// Leave num levels unspecified (let exchange choose default)
|
||||
break;
|
||||
default:
|
||||
LOG(md, Warn, "Invalid num depth levels '{}'. Must be one of [5, 10, 20]",
|
||||
cfg.num_depth_levels());
|
||||
break;
|
||||
}
|
||||
|
||||
switch (cfg.depth_throttle_ms()) {
|
||||
case 100:
|
||||
case 250:
|
||||
case 500:
|
||||
// The exchange only supports these throttle speeds
|
||||
opts[CCAPI_MARKET_DEPTH] = std::to_string(cfg.depth_throttle_ms());
|
||||
break;
|
||||
case 0:
|
||||
// Leave throttle unspecified (let exchange choose default)
|
||||
break;
|
||||
default:
|
||||
LOG(md, Warn,
|
||||
"Invalid depth throttle '{}ms'. Must be one of [100, 250, 500])",
|
||||
cfg.depth_throttle_ms());
|
||||
break;
|
||||
}
|
||||
|
||||
return opts.to_string();
|
||||
}
|
||||
|
||||
static ccapi::Subscription mk_depth_sub(
|
||||
const string &sec_desc, const string &opts) {
|
||||
auto corr_id = CCApiCorrelationID::from_parts(
|
||||
VENUE_NAME, BinanceCoinFuturesMessageType::DEPTH, sec_desc);
|
||||
return ccapi::Subscription{
|
||||
CCAPI_VENUE_NAME, sec_desc, CCAPI_MARKET_DEPTH, opts,
|
||||
corr_id.to_string()};
|
||||
}
|
||||
|
||||
static string mk_ticker_opts(
|
||||
const BinanceCoinFuturesMarketDataConfig & /*cfg*/) {
|
||||
// Placeholder (for consistency's sake)
|
||||
return "";
|
||||
}
|
||||
|
||||
static ccapi::Subscription mk_ticker_sub(
|
||||
const string &sec_desc, const string &opts) {
|
||||
auto corr_id = CCApiCorrelationID::from_parts(
|
||||
VENUE_NAME, BinanceCoinFuturesMessageType::TICKER, sec_desc);
|
||||
return ccapi::Subscription{
|
||||
CCAPI_VENUE_NAME, sec_desc, CCAPI_AGG_TRADE, opts, corr_id.to_string()};
|
||||
}
|
||||
|
||||
static CCApiCorrelationID mk_stats_corr_id(const string &desc) {
|
||||
return CCApiCorrelationID::from_parts(
|
||||
VENUE_NAME,
|
||||
BinanceCoinFuturesMessageType(BinanceCoinFuturesMessageType::STATISTICS),
|
||||
desc);
|
||||
}
|
||||
|
||||
// TODO (maybe): Use 'pair' param rather than 'symbol'. Requests with the
|
||||
// former param batch Futures with common symbol/currency pairs together.
|
||||
static ccapi::Request mk_stats_req(const string &sec_desc) {
|
||||
const auto corr_id = mk_stats_corr_id(sec_desc);
|
||||
ccapi::Request req{
|
||||
ccapi::Request::Operation::GENERIC_PUBLIC_REQUEST, CCAPI_VENUE_NAME};
|
||||
req.setCorrelationId(corr_id.to_string());
|
||||
req.appendParam(
|
||||
{{CCAPI_HTTP_PROTOCOL, "https"},
|
||||
{CCAPI_HTTP_PATH, VENUE_PRICE_STATS_PATH},
|
||||
{CCAPI_HTTP_QUERY_STRING, FMT("symbol={}", sec_desc)},
|
||||
{CCAPI_HTTP_METHOD, "GET"},
|
||||
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
||||
return req;
|
||||
}
|
||||
|
||||
struct BinanceCoinFuturesSubscription::PImpl {
|
||||
// General Notes:
|
||||
// All securities are listed in the 'symbols' field of the json response
|
||||
// to the 'exchangeInfo' request.
|
||||
|
||||
unordered_map<SecurityID, unique_ptr<Security>> securities;
|
||||
IDGenerator *sec_id_store;
|
||||
// Don't actually need this, but keeping it around for diagnostic purposes
|
||||
// (i.e., inspection in debugger, temp logs, etc.)
|
||||
BinanceCoinFuturesMarketDataConfig cfg;
|
||||
SecurityCriteria criteria;
|
||||
// The session automatically starts/stops in its ctr/dtr
|
||||
CCApiSession session;
|
||||
IMarketDataListener *listener;
|
||||
BinanceCoinFuturesSecurityRequestor sec_requestor;
|
||||
|
||||
// These aliases are useful for quickly switching the handler types (e.g.,
|
||||
// a special handler that logs messages for testing/diagnostic purposes)
|
||||
using DepthHandler = CCApiMarketDepthAdaptor;
|
||||
using TickerHandler = CCApiTradeAdaptor;
|
||||
using StatsHandler = BinanceCoinFuturesPriceStatisticsAdaptor;
|
||||
|
||||
unordered_map<string, DepthHandler> depth_handlers;
|
||||
unordered_map<string, TickerHandler> ticker_handlers;
|
||||
unordered_map<string, StatsHandler> stats_handlers;
|
||||
|
||||
explicit PImpl(
|
||||
ccapi::EventDispatcher *dispatcher,
|
||||
BinanceCoinFuturesMarketDataConfig cfg,
|
||||
IDGenerator *sec_id_store,
|
||||
IMarketDataListener *listener)
|
||||
: sec_id_store(sec_id_store), cfg(std::move(cfg)),
|
||||
criteria(SecurityCriteria::from_proto(this->cfg.security_criteria())),
|
||||
session(dispatcher, mk_session_cfg(this->cfg), {}), listener(listener),
|
||||
sec_requestor(&session, this->cfg, sec_id_store) {
|
||||
LOG(md, Info, "Initializing BinanceCoinFuturesSubscription:\n{}",
|
||||
ProtoPrinter::to_string(this->cfg));
|
||||
sec_requestor.callback().bind<&PImpl::on_securities>(*this);
|
||||
sec_requestor.request();
|
||||
}
|
||||
|
||||
SecurityID get_sec_id(SecurityType sec_type, const string &sec_desc) {
|
||||
return SecurityID{sec_id_store->get_or_add(VENUE, sec_type, sec_desc)};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Transforms a security desc from the 'exchangeInfo' response to the
|
||||
* desc needed for security-based websocket requests (depth, ticker, etc.)
|
||||
*/
|
||||
string get_sec_desc_for_reqs(const string &sec_desc) {
|
||||
for (const auto &sdf : cfg.security_desc_formattings()) {
|
||||
std::smatch match;
|
||||
std::regex rgx(sdf.expression());
|
||||
if (std::regex_search(sec_desc, match, rgx)) {
|
||||
return std::regex_replace(sec_desc, rgx, sdf.format());
|
||||
}
|
||||
}
|
||||
return 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);
|
||||
bts_assert_msgf(
|
||||
is_new, "Depth handler already created for '{}'", sec_desc);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
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);
|
||||
bts_assert_msgf(
|
||||
is_new, "Ticker handler already created for '{}'", sec_desc);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
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);
|
||||
bts_assert_msgf(
|
||||
is_new, "Stats handler already created for '{}'", sec_desc);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Subscribes to depth, ticker, and price data for a list of
|
||||
* securities
|
||||
*/
|
||||
template <class SecDescs>
|
||||
void subscribe_market_data(SecDescs securities) {
|
||||
const auto depth_opts = mk_depth_opts(cfg);
|
||||
const auto ticker_opts = mk_ticker_opts(cfg);
|
||||
|
||||
// Batch subscribe/request ticker, depth, and stats
|
||||
CCApiSession::BatchSubscription depth_subs;
|
||||
CCApiSession::BatchSubscription ticker_subs;
|
||||
CCApiSession::BatchRequest stats_reqs;
|
||||
|
||||
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(type, name)});
|
||||
ticker_subs.push_back(
|
||||
{mk_ticker_sub(sec_desc_for_reqs, ticker_opts),
|
||||
&add_ticker_handler(type, name)});
|
||||
stats_reqs.push_back(
|
||||
{mk_stats_req(name), &add_stats_handler(type, name)});
|
||||
}
|
||||
|
||||
session.subscribe(
|
||||
depth_subs, {ccapi::Message::Type::MARKET_DATA_EVENTS_MARKET_DEPTH});
|
||||
session.subscribe(
|
||||
ticker_subs, {ccapi::Message::Type::MARKET_DATA_EVENTS_AGG_TRADE});
|
||||
session.request(
|
||||
stats_reqs, {ccapi::Message::Type::GENERIC_PUBLIC_REQUEST});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the securities map and subscribes market data for newly arrived
|
||||
* securities
|
||||
*/
|
||||
void on_securities(vector<Security> secs) {
|
||||
// 'sec_descs' is used to make depth subscriptions
|
||||
vector<pair<SecurityType, string>> sec_descs;
|
||||
sec_descs.reserve(secs.size());
|
||||
// 'sec_ptrs' is passed to IMarketDataListeners
|
||||
vector<const Security *> sec_ptrs;
|
||||
sec_ptrs.reserve(secs.size());
|
||||
|
||||
for (auto &s : secs) {
|
||||
auto id = s.id();
|
||||
auto desc = s.desc();
|
||||
auto [it, is_new] = securities.try_emplace(
|
||||
id, std::make_unique<Security>(std::move(s)));
|
||||
bts_assert_msgf(
|
||||
is_new, "Received duplicate Binance Coin Future '{}'", 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());
|
||||
}
|
||||
|
||||
listener->on_securities(sec_ptrs);
|
||||
subscribe_market_data(sec_descs);
|
||||
}
|
||||
};
|
||||
|
||||
BinanceCoinFuturesSubscription::BinanceCoinFuturesSubscription(
|
||||
ccapi::EventDispatcher *dispatcher,
|
||||
BinanceCoinFuturesMarketDataConfig cfg,
|
||||
IDGenerator *sec_id_store,
|
||||
IMarketDataListener *listener)
|
||||
: me_(std::make_unique<PImpl>(
|
||||
dispatcher, std::move(cfg), sec_id_store, listener)) {}
|
||||
|
||||
BinanceCoinFuturesSubscription::BinanceCoinFuturesSubscription(
|
||||
BinanceCoinFuturesSubscription &&) noexcept = default;
|
||||
BinanceCoinFuturesSubscription &BinanceCoinFuturesSubscription::operator=(
|
||||
BinanceCoinFuturesSubscription &&) noexcept = default;
|
||||
|
||||
BinanceCoinFuturesSubscription::~BinanceCoinFuturesSubscription() = default;
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace ccapi {
|
||||
class EventDispatcher;
|
||||
}
|
||||
|
||||
namespace bts::api::md {
|
||||
class BinanceCoinFuturesMarketDataConfig;
|
||||
}
|
||||
|
||||
namespace bts::md {
|
||||
class IMarketDataListener;
|
||||
}
|
||||
|
||||
namespace bts::persistence {
|
||||
class IDGenerator;
|
||||
}
|
||||
|
||||
namespace bts::md::binance_coin_futures {
|
||||
|
||||
/**
|
||||
* @brief Subscribes to market data at Binance Coin Futures
|
||||
*
|
||||
* @a https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Exchange-Information
|
||||
*/
|
||||
class BinanceCoinFuturesSubscription {
|
||||
public:
|
||||
BinanceCoinFuturesSubscription(
|
||||
ccapi::EventDispatcher *dispatcher,
|
||||
api::md::BinanceCoinFuturesMarketDataConfig cfg,
|
||||
persistence::IDGenerator *sec_id_store,
|
||||
IMarketDataListener *listener);
|
||||
|
||||
BinanceCoinFuturesSubscription(
|
||||
const BinanceCoinFuturesSubscription &) noexcept = delete;
|
||||
BinanceCoinFuturesSubscription(BinanceCoinFuturesSubscription &&) noexcept;
|
||||
BinanceCoinFuturesSubscription &operator=(
|
||||
const BinanceCoinFuturesSubscription &) noexcept = delete;
|
||||
BinanceCoinFuturesSubscription &operator=(
|
||||
BinanceCoinFuturesSubscription &&) noexcept;
|
||||
|
||||
~BinanceCoinFuturesSubscription();
|
||||
|
||||
void add_listener(IMarketDataListener *listener);
|
||||
void remove_listener(IMarketDataListener *listener);
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me_;
|
||||
};
|
||||
|
||||
} // namespace bts::md::binance_coin_futures
|
||||
Reference in new issue
Block a user