Files
spark/src/lib/md/MDConsumerHandle.cpp
T
John Colvin f4f67d4289 Let the ui convert synth net change to n ticks
Whether or not to display a price in dollar or n ticks form is a display
setting, and furthermore the front end assumes all prices are in dollar
form
2021-10-25 13:27:12 -04:00

458 lines
13 KiB
C++

#ifndef NO_CPP0X
#include "MDConsumerHandle.h"
#include "MBOProcessor.h"
#include "lib/domain_model/Security.h"
#include <boost/container/small_vector.hpp>
#define never bts_assert(false)
template <class T> using small_vector = boost::container::small_vector<T, 4>;
namespace bts {
namespace md {
MDConsumerHandle::MDConsumerHandle() {
memset(this, 0, sizeof(MDConsumerHandle));
_type = HANDLETYPE_VOID;
static_assert(sizeof(MDConsumerHandle) <= 40, "");
}
MDConsumerHandle::MDConsumerHandle(
const std::shared_ptr<const SyntheticStrategy> &def) {
memset(this, 0, sizeof(MDConsumerHandle));
synthetic.def = def;
_type = HANDLETYPE_SYNTHETIC;
for (size_t x = 0; x < def->legs.size(); ++x) {
bts_assert(
def->legs[x].key() ==
def->security.synthetic().legs(x).security().id());
}
}
MDConsumerHandle::MDConsumerHandle(const MDConsumerHandle &other) {
memset(this, 0, sizeof(MDConsumerHandle));
_type = HANDLETYPE_VOID;
*this = other;
}
MDConsumerHandle::MDConsumerHandle(
const ColdHeader &cheader,
const ColdEntry &centry,
const void *pvhot,
const MBOReader *mbo) {
init(cheader, centry, pvhot, mbo);
}
MDConsumerHandle::~MDConsumerHandle() {}
void MDConsumerHandle::init(
const ColdHeader &cheader,
const ColdEntry &centry,
const void *pvhot,
const MBOReader *mbo) {
set_cold(&cheader, &centry);
set_hot(pvhot);
set_mbo(mbo);
}
TimeStamp
copy_bbo(const HotEntry &hot, PriceSize &out_bid, PriceSize &out_ask) {
// We expect the time, in_bid and in_ask to be changing (rapidly)
//
TimeStamp t;
int attempts = 0;
// If the publisher crashed and left TimeStamp::invalid() in memory we need
// to be able to escape the loop This max_attempts allows get_bbo() to return
// 'false' in this case so the calling thread can continue and hopefully
// check the heartbeat.
const int max_attempts = 1619200;
do {
t = hot.time();
out_bid = hot.book.bid();
out_ask = hot.book.ask();
++attempts;
} while ((t != hot.time() || t == TimeStamp::invalid()) &&
attempts < max_attempts);
if (attempts >= max_attempts) {
return TimeStamp::invalid();
}
return t;
}
TimeStamp copy_depth(
const HotDepthEntry &hot, size_t count, PriceSize *bid, PriceSize *ask) {
TimeStamp t;
int attempts = 0;
const int max_attempts = 1619200;
do {
t = hot.time();
for (size_t x = 0; x < count; ++x) {
hot.read_direct(x, &bid[x], &ask[x]);
}
++attempts;
} while ((t != hot.time() || t == TimeStamp::invalid()) &&
attempts < max_attempts);
if (attempts >= max_attempts) {
return TimeStamp::invalid();
}
return t;
}
/////////////////////////////
// SYNTHETIC DEPTH
/////////////////////////////
struct Level {
double price;
double size;
};
struct DepthTraversal {
std::array<Level, COCONUT_MAX_DEPTH> levels;
size_t head;
api::Side side;
double qty, price_mult;
DepthTraversal(
api::Side side,
double qty,
double price_mult,
const PriceSize *depth,
size_t depth_count)
: levels(), head(0), side(side), qty(qty), price_mult(price_mult) {
// Copy prices into mutable storage
for (size_t x = 0; x < depth_count; ++x) {
levels[x].price = depth[x].price();
levels[x].size = depth[x].size();
}
}
#ifdef PRECISE_SYNTHETICS
double available_size() const {
double available = 0.0;
auto cur = head;
bool partial = false;
while (cur < levels.size() && available < 1) {
available += levels[cur].size / qty;
if (available < 1.0)
partial = true;
++cur;
}
if (partial && available >= 1.0)
return 1.0;
return available;
}
double consume(double size) {
bts_assert_d(size <= available_size());
double take = size * qty;
double price = 0.0;
while (take > 0) {
if (levels[head].size >= take) {
price += levels[head].price * price_mult * (take / qty);
levels[head].size -= take;
if (levels[head].size <= 0)
++head;
break;
} else {
double available = levels[head].size;
price += levels[head].price * price_mult * (available / qty);
levels[head].size = 0;
++head;
take -= available;
}
}
return price / size;
}
#else
double available_size() const {
double available = 0.0;
auto cur = head;
while (cur < levels.size() && available < 1) {
available += levels[cur].size / qty;
++cur;
}
return available;
}
double consume(double size) {
bts_assert_d(size <= available_size());
double take = size * qty;
double price = 0.0;
while (take > 0) {
if (levels[head].size >= take) {
price = levels[head].price * price_mult;
levels[head].size -= take;
if (levels[head].size <= 0)
++head;
break;
} else {
double available = levels[head].size;
price = levels[head].price * price_mult;
levels[head].size = 0;
++head;
take -= available;
}
}
return price;
}
#endif
};
void copy_synthetic_side(
size_t count,
api::Side side,
const api::ContractSpecification &spec,
small_vector<DepthTraversal> &leg_travs,
Level *out_price) {
size_t out_index = 0;
bool first = true;
while (out_index < count) {
double price = 0.0;
// Find the leg with the minimum available size
double size = std::numeric_limits<double>().max();
for (const auto &dt : leg_travs) {
auto sz = dt.available_size();
// If we can't get 1.0 from any leg we're done
if (sz <= size)
size = sz;
if (size < 1.0)
break;
}
size = (int64_t)size;
if (size < 1.0) {
// We've run out of book so we nan out any remaining levels and finish
size_t start = first ? out_index : out_index + 1;
for (size_t x = start; x < count; ++x) {
out_price[x].price = os::nan();
out_price[x].size = 0;
}
return;
}
// Take that size from each leg
for (auto &dt : leg_travs) {
double temp = dt.consume(size);
price += temp;
}
bts_assert_d(!os::is_nan(price));
// Round to tick size
price = securities::checked_round_to_quote_price(spec, price, side);
if (first) {
first = false;
out_price[out_index].price = price;
}
if (price == out_price[out_index].price) {
out_price[out_index].size += size;
} else {
out_index += 1;
if (out_index < count) {
out_price[out_index].price = price;
out_price[out_index].size = size;
}
}
}
}
const spark::LegSpreaderParams &
get_spreader_params(const SyntheticStrategy &synth, security_key key) {
auto strategy = synth.strategy.get();
if (strategy) {
auto iter = strategy->leg_params_map().find(key);
if (iter != strategy->leg_params_map().end()) {
return iter->second;
}
}
return spark::LegSpreaderParams::default_instance();
}
TimeStamp copy_synthetic_depth(
const SyntheticStrategy &synth,
size_t count,
PriceSize *bid,
PriceSize *ask) {
small_vector<DepthTraversal> bid_leg_travs;
small_vector<DepthTraversal> ask_leg_travs;
bid_leg_travs.reserve(synth.legs.size());
ask_leg_travs.reserve(synth.legs.size());
TimeStamp rv = std::numeric_limits<TimeStamp>::min();
for (size_t x = 0; x < synth.legs.size(); ++x) {
std::array<PriceSize, COCONUT_MAX_DEPTH> bids, asks;
TimeStamp t;
const spark::LegSpreaderParams &leg_params =
get_spreader_params(synth, synth.legs[x].key());
auto mdtype = leg_params.market_data_type();
HandleReadResult r;
if (mdtype == spark::LegSpreaderParams::DIRECT) {
r = synth.legs[x].get_direct_book(t, count, &bids[0], &asks[0]);
} else {
r = synth.legs[x].get_book(t, count, &bids[0], &asks[0]);
}
if (r == HandleReadResult::BUSY || t == TimeStamp::invalid())
return TimeStamp::invalid();
// NET Change
if (synth.security.synthetic().price_calc() ==
api::SyntheticContract::PRICECALC_NET_CHANGE) {
auto settle = synth.legs[x].settlement_price();
for (size_t d = 0; d < COCONUT_MAX_DEPTH; ++d) {
bids[d] = {bids[d].int_price() - settle, bids[d].size()};
asks[d] = {asks[d].int_price() - settle, asks[d].size()};
}
}
rv = std::max(rv, t);
const auto &leg = synth.security.synthetic().legs(x);
const auto &eff_bid = leg.side() == api::SIDE_BUY ? bids : asks;
const auto &eff_ask = leg.side() == api::SIDE_BUY ? asks : bids;
bid_leg_travs.push_back(DepthTraversal(
leg.side(), leg.quantity(), leg.price_multiplier(), &eff_bid[0],
eff_bid.size()));
ask_leg_travs.push_back(DepthTraversal(
leg.side(), leg.quantity(), leg.price_multiplier(), &eff_ask[0],
eff_ask.size()));
}
std::array<Level, COCONUT_MAX_DEPTH> scratch{};
const auto &spec = synth.security.contract_spec();
copy_synthetic_side(
count, api::SIDE_BUY, spec, bid_leg_travs, scratch.data());
for (size_t x = 0; x < count; ++x) {
bid[x] = PriceSize_from_double<11>(scratch[x].price, scratch[x].size);
}
memset(scratch.data(), 0, sizeof(scratch));
copy_synthetic_side(
count, api::SIDE_SELL, spec, ask_leg_travs, scratch.data());
for (size_t x = 0; x < count; ++x) {
ask[x] = PriceSize_from_double<11>(scratch[x].price, scratch[x].size);
}
return rv;
}
/////////////////////////////
// END SYNTHETIC DEPTH
/////////////////////////////
bool MDConsumerHandle::get_last_trade(
TimeStamp &time,
PriceSize &trade,
datetime::LLDateTime &trade_timestamp,
size_t *total_volume,
int *from_spread) const {
switch (_type) {
case HANDLETYPE_VOID:
return false;
case HANDLETYPE_DEPTH:
case HANDLETYPE_BBO: {
const ColdEntry *pcold =
(_type == HANDLETYPE_BBO) ? bbo.cdata : book.cdata;
bool result = pcold->last_trade.load_if_new(time, trade);
if (result) {
trade_timestamp = pcold->last_trade_time;
if (total_volume) {
*total_volume = pcold->total_volume;
}
if (from_spread) {
*from_spread = pcold->from_spread;
}
}
return result;
}
case HANDLETYPE_SYNTHETIC:
return false;
}
never;
}
TimeStamp MDConsumerHandle::misc_timestamp() const {
switch (_type) {
case HANDLETYPE_SYNTHETIC:
case HANDLETYPE_VOID:
return std::numeric_limits<TimeStamp>::min();
case HANDLETYPE_DEPTH:
return book.cdata->misc.misc_timestamp;
case HANDLETYPE_BBO:
return bbo.cdata->misc.misc_timestamp;
}
never;
}
MiscData MDConsumerHandle::misc() const {
switch (_type) {
case HANDLETYPE_SYNTHETIC:
case HANDLETYPE_VOID:
return MiscData();
case HANDLETYPE_DEPTH:
return book.cdata->misc;
case HANDLETYPE_BBO:
return bbo.cdata->misc;
}
never;
}
bool is_heart_beat_ok(const ColdHeader &);
bool MDConsumerHandle::is_heart_beating() const {
switch (_type) {
case HANDLETYPE_VOID:
return true;
case HANDLETYPE_DEPTH:
return is_heart_beat_ok(*book.cheader);
case HANDLETYPE_BBO:
return is_heart_beat_ok(*bbo.cheader);
case HANDLETYPE_SYNTHETIC:
return sane::true_for_all(
synthetic.def->legs,
[](const MDConsumerHandle &h) { return h.is_heart_beating(); });
}
never;
}
TimeStamp MDConsumerHandle::heartbeat() const {
switch (_type) {
case HANDLETYPE_VOID:
return TimeStamp::now();
case HANDLETYPE_DEPTH:
return book.cheader->heartbeat;
case HANDLETYPE_BBO:
return bbo.cheader->heartbeat;
case HANDLETYPE_SYNTHETIC:
return sane::min<TimeStamp>(
synthetic.def->legs,
[](const MDConsumerHandle &h) { return h.heartbeat(); });
}
never;
}
CoconutSecurityStatus MDConsumerHandle::status() const {
switch (_type) {
case HANDLETYPE_VOID:
return CoconutSecurityStatus::COCONUTSECURITYSTATUS_OK;
case HANDLETYPE_DEPTH:
return (CoconutSecurityStatus)book.hot->status;
case HANDLETYPE_BBO:
return (CoconutSecurityStatus)bbo.hot->status;
case HANDLETYPE_SYNTHETIC: {
for (const auto &handle : synthetic.def->legs) {
auto status = handle.status();
if (status != CoconutSecurityStatus::COCONUTSECURITYSTATUS_OK) {
return status;
}
}
}
}
never;
}
std::unique_ptr<MBOSnapshot, std::function<void(MBOSnapshot *)>>
MDConsumerHandle::get_mbo() const {
if (_type == HANDLETYPE_DEPTH) {
MBOSnapshot *snapshot = book.mbo->acquire_snapshot(SecurityKey(key()));
if (snapshot != nullptr) {
return {snapshot, [mbo = book.mbo](auto *s) {
mbo->release_snapshot(&s);
}};
}
}
return nullptr;
}
} // namespace md
} // namespace bts
#endif