Files
spark/src/lib/md/MDConsumerHandle.cpp
T
2018-05-18 16:57:03 -04:00

339 lines
11 KiB
C++

#ifndef NO_CPP0X
#include "MDConsumerHandle.h"
#include "lib/utils/sane_algorithm.h"
#include "lib/domain_model/Security.h"
#define never bts_assert(false)
namespace bts {
namespace md {
MDConsumerHandle::MDConsumerHandle() {
memset(this, 0, sizeof(MDConsumerHandle));
_type = HANDLETYPE_VOID;
static_assert(sizeof(MDConsumerHandle) <= 32, "");
}
MDConsumerHandle::MDConsumerHandle(const std::shared_ptr<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() {}
void MDConsumerHandle::init(const ColdHeader& cheader, const ColdEntry& centry, const void* pvhot) {
set_cold(&cheader, &centry);
set_hot(pvhot);
}
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.bid.load();
out_ask = hot.ask.load();
++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) {
bid[x] = hot.bid(x).load();
ask[x] = hot.ask(x).load();
}
++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;
uint16_t 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();
}
}
double try_take1() {
if (head >= levels.size()) return os::nan();
if (levels[head].size >= qty) {
levels[head].size -= qty;
return levels[head].price * price_mult;
}
else {
double price = 0;
size_t count = 0;
while(count < qty) {
if (levels[head].size >= 1) {
price += levels[head].price;
levels[head].size -= 1;
count += 1;
}
else {
head++;
if (head >= levels.size()) return os::nan();
}
}
return (price / qty) * price_mult;
}
}
};
void copy_depth(size_t count, api::Side side, const api::ContractSpecification& spec, std::vector<DepthTraversal>& leg_travs, Level* out_price) {
size_t out_index = 0;
bool first = true;
while(out_index < count) {
double price = 0.0;
for (auto& dt : leg_travs) {
double temp = dt.try_take1();
price += temp;
}
if (os::is_nan(price)) {
// 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;
}
// 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 += 1;
}
else {
out_index += 1;
if (out_index < count) {
out_price[out_index].price = price;
out_price[out_index].size = 1;
}
}
}
}
TimeStamp copy_depth(const SyntheticStrategy& synth, size_t count, PriceSize* bid, PriceSize* ask) {
std::vector<DepthTraversal> bid_leg_travs;
std::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;
HandleReadResult r = synth.legs[x].get_depth(t, count, &bids[0], &asks[0]);
if (r == HandleReadResult::BUSY || t == TimeStamp::invalid()) return TimeStamp::invalid();
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_depth(count, api::SIDE_BUY, spec, bid_leg_travs, scratch.data());
for (size_t x = 0; x < count; ++x) {
bid[x] = PriceSize::from_double<7>(scratch[x].price, scratch[x].size);
}
memset(scratch.data(), 0, sizeof(scratch));
copy_depth(count, api::SIDE_SELL, spec, ask_leg_travs, scratch.data());
for (size_t x = 0; x < count; ++x) {
ask[x] = PriceSize::from_double<7>(scratch[x].price, scratch[x].size);
}
return rv;
}
/////////////////////////////
// END SYNTHETIC DEPTH
/////////////////////////////
TimeStamp MDConsumerHandle::last_market_update() const {
switch(_type) {
case HANDLETYPE_VOID:
return TimeStamp::invalid();
case HANDLETYPE_DEPTH:
return book.hot->time();
case HANDLETYPE_BBO:
return bbo.hot->time();
case HANDLETYPE_SYNTHETIC:
return sane::max<TimeStamp>(synthetic.def->legs, [](const MDConsumerHandle& h) { return h.last_market_update(); });
}
never;
}
bool MDConsumerHandle::get_customer_bbo(TimeStamp& time, PriceSize& out_bid, PriceSize& out_ask) const {
switch(_type) {
case HANDLETYPE_SYNTHETIC:
case HANDLETYPE_VOID:
return false;
case HANDLETYPE_DEPTH:
case HANDLETYPE_BBO: {
const ColdEntry* pcold = (_type == HANDLETYPE_BBO) ? bbo.cdata : book.cdata;
// This can loop forever if publisher crashes with an invalid time in shm
// good thing nobody uses customer_bbo
bool result = false;
while(pcold->customer_bbo_updated > time || time == TimeStamp::invalid()) {
time = pcold->customer_bbo_updated;
out_bid = pcold->customer_bid.load();
out_ask = pcold->customer_ask.load();
result = true;
}
return result;
}
}
never;
}
bool MDConsumerHandle::get_last_trade(TimeStamp& time, PriceSize& trade, datetime::LLDateTime& trade_timestamp, size_t* total_volume) 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 = false;
while (pcold->last_trade_updated > time) {
time = pcold->last_trade_updated;
trade = pcold->last_trade.load();
trade_timestamp = pcold->last_trade_time;
if (total_volume) { *total_volume = pcold->total_volume; }
result = true;
}
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;
}
uint16_t MDConsumerHandle::sequence() const {
switch(_type) {
case HANDLETYPE_VOID: return 0;
case HANDLETYPE_DEPTH: return book.hot->sequence;
case HANDLETYPE_BBO: return bbo.hot->sequence;
case HANDLETYPE_SYNTHETIC:
bts_assert(!synthetic.def->legs.empty());
return sane::min_by<MDConsumerHandle, TimeStamp>(synthetic.def->legs, [](const MDConsumerHandle& h) { return h.last_market_update(); })->sequence();
}
never;
}
}}//namespace
#endif