refactor: Break md relay/query server code up into smaller files
To make code navigation easier. This was a difficulty which I recently confronted, while investigating a bug that prevented synthetics from showing up the ui.
This commit is contained in:
1 parent
51be818dff
commit
e6d41cf01a
45 files changed
+2110
-1780
No files matched your search
@@ -8,7 +8,7 @@
|
||||
#include "spark/md/MBOServiceServer.h"
|
||||
#include "spark/md/MDClient.h"
|
||||
#include "spark/md/SyntheticSecurityService.h"
|
||||
#include "spark/md/relay/QueryServer.h"
|
||||
#include "spark/md/relay/query_server.h"
|
||||
#include "spark/md/service/MarketDataServiceServer.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
#include "spark/metrics/system_metrics.h"
|
||||
@@ -22,7 +22,6 @@
|
||||
#include "spark/quickbus/core/Quickbus.h"
|
||||
#include "spark/tracing/PerfLog.h"
|
||||
#include "spark/utils/Dispatcher.h"
|
||||
#include "md/cmds/Run.h"
|
||||
#include "sparkd/algo/AlgoDefinitionServiceServer.h"
|
||||
#include "sparkd/analytics/AnalyticsServiceServer.h"
|
||||
#include "sparkd/cmds/md/cmds/Cleanup.h"
|
||||
@@ -41,7 +40,6 @@
|
||||
#include "sparkd/user/AuthServiceServer.h"
|
||||
#include "system/logging/logging.h"
|
||||
|
||||
|
||||
namespace bts::cmds {
|
||||
|
||||
static void execute() {
|
||||
@@ -53,8 +51,7 @@ static void execute() {
|
||||
auto qb_cfg = config::get<config::QuickbusCfg>().node();
|
||||
auto &ports = config::get<config::Ports>();
|
||||
qb_cfg.set_my_port(ports.qbus_port());
|
||||
qbus::Quickbus quickbus(
|
||||
qb_cfg, qbus::QuickbusThreadOptions::DEFERRED_START);
|
||||
qbus::Quickbus quickbus(qb_cfg, qbus::QuickbusThreadOptions::DEFERRED_START);
|
||||
api::ServiceContext sc(&quickbus);
|
||||
|
||||
trace::PerfLog perf_log;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include "spark/config/protos/quickbus_cfg.pb.h"
|
||||
#include "spark/md/MDClient.h"
|
||||
#include "spark/md/SyntheticSecurityService.h"
|
||||
#include "spark/md/relay/QueryServer.h"
|
||||
#include "spark/md/relay/query_server.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
#include "spark/metrics/system_metrics.h"
|
||||
#include "spark/quickbus/core/Quickbus.h"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "Record.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
namespace bts::cmds::md::cmds {
|
||||
@@ -8,13 +9,14 @@ struct Record::Args {
|
||||
std::string path;
|
||||
};
|
||||
|
||||
Record::Record() :
|
||||
CLI::App("Record market data to a file", "record"),
|
||||
_args(new Record::Args()) {
|
||||
Record::Record()
|
||||
: CLI::App("Record market data to a file", "record"),
|
||||
_args(new Record::Args()) {
|
||||
add_option("out,--out", _args->path, "Output file");
|
||||
callback([&] {
|
||||
boost::filesystem::path p(_args->path);
|
||||
bts::md::record_everything(p.parent_path().string(), p.filename().string());
|
||||
bts::md::record_everything(
|
||||
p.parent_path().string(), p.filename().string());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include "Relay.h"
|
||||
#include "spark/md/relay/RelayClient.h"
|
||||
#include "spark/md/relay/relay_control.h"
|
||||
|
||||
namespace bts::cmds::md::cmds {
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
#include "Replay.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/config/protos/market_data.pb.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
|
||||
namespace bts::cmds::md::cmds {
|
||||
|
||||
Replay::Replay() :
|
||||
CLI::App("Replay recorded market data", "replay") {
|
||||
Replay::Replay() : CLI::App("Replay recorded market data", "replay") {
|
||||
callback([] {
|
||||
auto naggle_ms = config::get<bts::md::RelayOptions>().naggle_ms();
|
||||
const auto &options = config::get<bts::md::ReplayOptions>();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include "Print.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
|
||||
namespace bts::cmds::md::cmds::rec_tool::cmds {
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include "Trace.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
|
||||
namespace bts::cmds::md::cmds::rec_tool::cmds {
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include "Unprint.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
|
||||
namespace bts::cmds::md::cmds::rec_tool::cmds {
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#include <quickfix/SessionSettings.h>
|
||||
#include <quickfix/SocketAcceptor.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
@@ -22,13 +21,9 @@
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/md/IntPrice.h"
|
||||
#include "spark/md/MBOProcessor.h"
|
||||
#include "spark/md/relay/RelayClient.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/utils/bts_chrono.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
#include <quickfix/FileLog.h>
|
||||
|
||||
#include <set>
|
||||
|
||||
namespace bts {
|
||||
namespace sim {
|
||||
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "MDConsumer.h"
|
||||
#include "MBOProcessor.h"
|
||||
#include "MemorySegmentUtils.h"
|
||||
#include "SecurityCache.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/config/protos/market_data.pb.h"
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/md/ShmSegmentName.h"
|
||||
#include "spark/domain_model/Security.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/utils/SharedList.h"
|
||||
#include "spark/utils/WaitFreeQueue.h"
|
||||
#include "spark/utils/bts_chrono.h"
|
||||
#include "spark/utils/sane_algorithm.h"
|
||||
#include "spark/md/md_consumer_channel.h"
|
||||
#include "spark/md/md_consumer_inst.h"
|
||||
#include "system/logging/logging.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -20,7 +14,6 @@
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <tbb/queuing_mutex.h>
|
||||
#include <tuple>
|
||||
|
||||
using namespace std;
|
||||
using namespace bts::api;
|
||||
@@ -62,279 +55,8 @@ MutSecurityPtr convert_psecurity(const FixedSecurity &security) {
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Represents one pair of shared memory segments for a single Symbol+type
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
struct QueueStruct {
|
||||
utils::WaitFreeQueue<co2::TradeMessage> _trade_queue;
|
||||
utils::WaitFreeQueue<ColdHeader::RFQBuffer> _rfq_queue;
|
||||
QueueStruct(const ColdHeader &header)
|
||||
: _trade_queue(
|
||||
(void *)header.trade_buffer, BTS_ARRAYSIZE(header.trade_buffer)),
|
||||
_rfq_queue(
|
||||
(void *)header.rfq_buffer, BTS_ARRAYSIZE(header.rfq_buffer)) {}
|
||||
};
|
||||
|
||||
bool is_heart_beat_ok(const ColdHeader &);
|
||||
|
||||
// this is for a <symbol, type, exchange> tuple
|
||||
class MDConsumerInst {
|
||||
public:
|
||||
MDConsumerInst(
|
||||
const string &symbol, SecurityType type, Venue exchange, bool shared)
|
||||
: _symbol(symbol), _type(type), _exchange(exchange), _security_count(0),
|
||||
_found_keys(), _hot(), _hot_depth(),
|
||||
_cold(ShmSegmentName::cold_name(symbol, type, exchange), shared),
|
||||
_queues() {
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::MDConsumerInst symbol: {} venue: {} type: {}",
|
||||
symbol, static_cast<int>(exchange), static_cast<int>(type));
|
||||
if (enable_depth(symbol, type)) {
|
||||
_hot_depth.reset(new utils::SharedListReader<HotHeader, HotDepthEntry>(
|
||||
ShmSegmentName::hot_name(symbol, type, exchange), shared));
|
||||
} else {
|
||||
_hot.reset(new utils::SharedListReader<HotHeader, HotEntry>(
|
||||
ShmSegmentName::hot_name(symbol, type, exchange), shared));
|
||||
}
|
||||
}
|
||||
~MDConsumerInst() {
|
||||
if (_queues)
|
||||
delete _queues;
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
size_t walk_sec_list(
|
||||
CB cb,
|
||||
const string &symbol = "",
|
||||
SecurityType type = SECURITYTYPE_UNSET) {
|
||||
size_t result = 0;
|
||||
_cold.all_entries([&symbol, type, &cb, &result](const ColdEntry &entry) {
|
||||
// not sure this double check is needed since the caller also filters
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
match_type(entry.security.type, type) &&
|
||||
match_symbol(entry.security.symbol(), symbol)) {
|
||||
cb(convert_psecurity(entry.security));
|
||||
++result;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
const void *find_hot(
|
||||
utils::SharedListReader<HotHeader, T> *phot, security_key key) {
|
||||
const void *hot_entry = nullptr;
|
||||
phot->all_entries([&](const T &entry) {
|
||||
if (entry.key == key) {
|
||||
hot_entry = &entry;
|
||||
}
|
||||
});
|
||||
return hot_entry;
|
||||
}
|
||||
|
||||
bool find_handle(
|
||||
security_key key, const ColdEntry **ppcold, const void **ppvhot) {
|
||||
*ppcold = nullptr;
|
||||
*ppvhot = nullptr;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (entry.security.key == key) {
|
||||
*ppcold = &entry;
|
||||
}
|
||||
});
|
||||
|
||||
// Only search the hot list if we found cold
|
||||
if (*ppcold) {
|
||||
// It is possible that cold is initialized and hot is not yet due to
|
||||
// race between process mapped memory being visible
|
||||
size_t count = 0;
|
||||
do {
|
||||
++count;
|
||||
*ppvhot = cold_header().has_depth ? find_hot(_hot_depth.get(), key)
|
||||
: find_hot(_hot.get(), key);
|
||||
if (!*ppvhot) {
|
||||
std::this_thread::sleep_for(1ms);
|
||||
if (count == 4096)
|
||||
LOG(md, Error, "Waiting an awfully long time for key: {}",
|
||||
key);
|
||||
if (count == 60000) {
|
||||
LOG(md, Error,
|
||||
"Waited far too long for key: {} security discovery may "
|
||||
"be hung."
|
||||
" symbol: {} type: {}",
|
||||
key, std::string((*ppcold)->security.symbol()),
|
||||
SecurityType_Name((*ppcold)->security.type));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} while (!*ppvhot);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
return false;
|
||||
}
|
||||
|
||||
btree::map<security_key, tuple<const ColdEntry *, const void *>>
|
||||
search_handles(const std::set<security_key> &keys) {
|
||||
btree::map<security_key, tuple<const ColdEntry *, const void *>> result;
|
||||
// Walk hot and cold lists and fill in any found handles
|
||||
if (!_cold.is_initialized())
|
||||
return result;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (keys.find(entry.security.key) != keys.end()) {
|
||||
result.insert(std::make_pair(
|
||||
entry.security.key, make_tuple(&entry, nullptr)));
|
||||
}
|
||||
});
|
||||
// Do the same for hot
|
||||
if (_hot_depth) {
|
||||
_hot_depth->all_entries([&](const HotDepthEntry &entry) {
|
||||
auto iter = result.find(entry.key);
|
||||
if (iter != result.end()) {
|
||||
iter->second = make_tuple(get<0>(iter->second), &entry);
|
||||
}
|
||||
});
|
||||
} else if (_hot) {
|
||||
_hot->all_entries([&](const HotEntry &entry) {
|
||||
auto iter = result.find(entry.key);
|
||||
if (iter != result.end()) {
|
||||
iter->second = make_tuple(get<0>(iter->second), &entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
void scan_new_securities(CB cb) {
|
||||
// If the ver matches no securities have been added
|
||||
if (_security_count == cold_header().security_count)
|
||||
return;
|
||||
_security_count = cold_header().security_count;
|
||||
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::scan_new_securities rcvd entry: {} key: {}",
|
||||
std::string(entry.security.security_desc()), entry.security.key);
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
_found_keys.count(entry.security.key) == 0) {
|
||||
_found_keys.insert(entry.security.key);
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::scan_new_securities firing cb entry: {}",
|
||||
std::string(entry.security.security_desc()));
|
||||
cb(entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void forget_security(security_key key) {
|
||||
_security_count -= _found_keys.erase(key);
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
void walk_old_securities(CB cb) {
|
||||
// Fire callback only for securities which *have* been seen already
|
||||
if (_found_keys.empty())
|
||||
return;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
_found_keys.count(entry.security.key) != 0) {
|
||||
cb(entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
uint32_t security_count() { return cold_header().security_count; }
|
||||
|
||||
const ColdHeader &cold_header() { return _cold.header(); }
|
||||
const HotHeader &hot_header() {
|
||||
return (has_depth() ? _hot_depth->header() : _hot->header());
|
||||
}
|
||||
bool has_depth() { return cold_header().has_depth; }
|
||||
const string &symbol() const { return _symbol; }
|
||||
SecurityType type() const { return _type; }
|
||||
Venue exchange() const { return _exchange; }
|
||||
|
||||
//
|
||||
// Queued data
|
||||
|
||||
int64_t read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
int64_t excursor) {
|
||||
if (init_queues()) {
|
||||
bts_assert(_queues);
|
||||
utils::WaitFreeQueue<co2::TradeMessage>::Cursor cursor(
|
||||
_queues->_trade_queue, excursor);
|
||||
bool overrun;
|
||||
cursor.read(trades, &overrun);
|
||||
// Preserve the overrun flag in the message
|
||||
if (overrun && !trades.empty()) {
|
||||
trades.begin()->set_gap(true);
|
||||
}
|
||||
return cursor.current_position();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int64_t read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> &rfqs,
|
||||
int64_t extcursor) {
|
||||
if (init_queues()) {
|
||||
bts_assert(_queues);
|
||||
bool overrun;
|
||||
vector<ColdHeader::RFQBuffer> temp_result;
|
||||
utils::WaitFreeQueue<ColdHeader::RFQBuffer>::Cursor cursor(
|
||||
_queues->_rfq_queue, extcursor);
|
||||
cursor.read(temp_result, &overrun);
|
||||
// deserialize the rfqs
|
||||
for (const auto &entry : temp_result) {
|
||||
rfqs.Add()->ParsePartialFromArray(&entry[0], entry.size());
|
||||
}
|
||||
if (overrun && rfqs.size() > 0) {
|
||||
rfqs.begin()->set_gap(true);
|
||||
}
|
||||
return cursor.current_position();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool is_heart_beating() {
|
||||
// Channel Heartbeat - not in a tight loop
|
||||
if (!_cold.is_initialized())
|
||||
return true;
|
||||
return is_heart_beat_ok(cold_header());
|
||||
}
|
||||
|
||||
void dump_shm_to(const char *directory) const {
|
||||
_cold.dump_to(directory);
|
||||
if (_hot) {
|
||||
_hot->dump_to(directory);
|
||||
}
|
||||
if (_hot_depth) {
|
||||
_hot_depth->dump_to(directory);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
bool init_queues() {
|
||||
if (_queues)
|
||||
return true;
|
||||
if (!_cold.is_initialized())
|
||||
return false;
|
||||
// double assignment is OK. Leak instead of lock.
|
||||
_queues = new QueueStruct(_cold.header());
|
||||
return true;
|
||||
}
|
||||
|
||||
string _symbol;
|
||||
SecurityType _type;
|
||||
Venue _exchange;
|
||||
size_t _security_count;
|
||||
set<security_key> _found_keys;
|
||||
unique_ptr<utils::SharedListReader<HotHeader, HotEntry>> _hot;
|
||||
unique_ptr<utils::SharedListReader<HotHeader, HotDepthEntry>> _hot_depth;
|
||||
utils::SharedListReader<ColdHeader, ColdEntry> _cold;
|
||||
QueueStruct *_queues;
|
||||
};
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Instance for synthetic securities (no shm)
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -1082,64 +804,6 @@ MDConsumerChannel MDConsumer::get_channel(const UserSymbol &u) const {
|
||||
}
|
||||
void MDConsumer::dump_shm_to(const char *p) const { _pimpl->dump_shm_to(p); }
|
||||
|
||||
MDConsumerChannel::MDConsumerChannel(const shared_ptr<MDConsumerInst> &inst)
|
||||
: _pimpl(inst) {}
|
||||
int64_t MDConsumerChannel::read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
int64_t cursor) {
|
||||
return _pimpl->read_trades(trades, cursor);
|
||||
}
|
||||
int64_t MDConsumerChannel::read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> "es,
|
||||
int64_t cursor) {
|
||||
return _pimpl->read_rfqs(quotes, cursor);
|
||||
}
|
||||
const std::string &MDConsumerChannel::symbol() const {
|
||||
return _pimpl->symbol();
|
||||
}
|
||||
SecurityType MDConsumerChannel::type() const { return _pimpl->type(); }
|
||||
Venue MDConsumerChannel::exchange() const { return _pimpl->exchange(); }
|
||||
|
||||
bool MDConsumerChannel::is_heart_beating() const {
|
||||
return _pimpl->is_heart_beating();
|
||||
}
|
||||
bool MDConsumerChannel::is_initialized() const {
|
||||
return _pimpl && security_count() > 0;
|
||||
}
|
||||
TimeStamp MDConsumerChannel::create_time() const {
|
||||
return _pimpl ? _pimpl->cold_header().create_time : TimeStamp::invalid();
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::security_count() const {
|
||||
return _pimpl->cold_header().security_count;
|
||||
}
|
||||
size_t MDConsumerChannel::direct_count() const {
|
||||
return is_initialized() ? _pimpl->hot_header().direct_count : 0;
|
||||
}
|
||||
size_t MDConsumerChannel::implied_count() const {
|
||||
return is_initialized() ? _pimpl->hot_header().implied_count : 0;
|
||||
}
|
||||
size_t MDConsumerChannel::trade_count() const {
|
||||
return _pimpl->cold_header().trade_count;
|
||||
}
|
||||
size_t MDConsumerChannel::rfq_count() const {
|
||||
return _pimpl->cold_header().rfq_count;
|
||||
}
|
||||
size_t MDConsumerChannel::gap_count() const {
|
||||
return _pimpl->cold_header().gap_count;
|
||||
}
|
||||
|
||||
bool is_heart_beat_ok(const ColdHeader &header) {
|
||||
uint32_t s_heartbeat_ms = header.heartbeat_ms;
|
||||
bool s_disable_heartbeat = header.disable_heartbeat;
|
||||
uint32_t s_grace_period_ms = header.heartbeat_boot_seconds * 1000;
|
||||
TimeStamp hb = header.heartbeat;
|
||||
TimeStamp now = TimeStamp::now();
|
||||
return (header.version == shm_version) &&
|
||||
(s_disable_heartbeat || (now - hb).milliseconds() < s_heartbeat_ms ||
|
||||
(now - header.create_time).milliseconds() < s_grace_period_ms);
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/utils/bts_export.h"
|
||||
#include "spark/utils/bts_no_copy.h"
|
||||
|
||||
#include "ISyntheticSecurityService.h"
|
||||
#include "MDConsumerHandle.h"
|
||||
#include "SecurityPtr.h"
|
||||
@@ -79,40 +76,5 @@ class MDConsumer {
|
||||
std::shared_ptr<MDConsumerImpl> _pimpl;
|
||||
};
|
||||
|
||||
class BTS_EXPORT MDConsumerChannel {
|
||||
std::shared_ptr<MDConsumerInst> _pimpl;
|
||||
|
||||
public:
|
||||
MDConsumerChannel(const std::shared_ptr<MDConsumerInst> &inst);
|
||||
|
||||
const std::string &symbol() const;
|
||||
SecurityType type() const;
|
||||
Venue exchange() const;
|
||||
bool is_initialized() const;
|
||||
utils::TimeStamp create_time() const;
|
||||
|
||||
// Scan for new trades. If overrun is true some trades were lost
|
||||
int64_t read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
int64_t cursor);
|
||||
// Scan for new rfqs. If overrun=true some entries were lost
|
||||
int64_t read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> "es,
|
||||
int64_t cursor);
|
||||
|
||||
// Check the heartbeat has not passed the threshhold
|
||||
// (PublisherOptions.heartbeat_ms)
|
||||
bool is_heart_beating() const;
|
||||
|
||||
//
|
||||
// Statistic counters
|
||||
size_t security_count() const;
|
||||
size_t direct_count() const;
|
||||
size_t implied_count() const;
|
||||
size_t trade_count() const;
|
||||
size_t rfq_count() const;
|
||||
size_t gap_count() const;
|
||||
};
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
@@ -5,10 +5,12 @@
|
||||
#include "common.h"
|
||||
#include "spark/domain/DomainSecurityUtils.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/md/md_consumer_channel.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/utils/Dispatcher.h"
|
||||
#include "spark/md/relay/relay_control.h"
|
||||
#include "spark/md/relay/relay_scanner_thread.h"
|
||||
#include "spark/utils/defer.h"
|
||||
#include "relay/RelayClient.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <set>
|
||||
#include <string>
|
||||
@@ -96,18 +98,18 @@ void safe_call_clr_callback(
|
||||
const char *buffer,
|
||||
size_t buffer_size,
|
||||
MDConsumerHandle &handle) {
|
||||
// Protect against clr shutting down
|
||||
#ifdef _WIN32
|
||||
// Protect against clr shutting down
|
||||
#ifdef _WIN32
|
||||
__try {
|
||||
cb(key, buffer, buffer_size, &handle);
|
||||
} __except (EXCEPTION_CONTINUE_EXECUTION) {
|
||||
}
|
||||
#else
|
||||
#else
|
||||
__try {
|
||||
cb(key, buffer, buffer_size, &handle);
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
CAPI void md_consumer_set_on_security(MDConsumer *consumer, security_cb cb) {
|
||||
@@ -131,7 +133,7 @@ CAPI bool md_consumer_is_heart_beating(const ColdHeader *header) {
|
||||
typedef void (*raw_receive_pb)(const char *, size_t);
|
||||
CAPI int md_consumer_read_trades_linux(
|
||||
MDConsumer *consumer,
|
||||
const char* symbol,
|
||||
const char *symbol,
|
||||
int venue_i,
|
||||
int type_i,
|
||||
int64_t &cursor,
|
||||
@@ -142,8 +144,7 @@ CAPI int md_consumer_read_trades_linux(
|
||||
google::protobuf::Arena arena;
|
||||
co2::TradeList *ptrades =
|
||||
google::protobuf::Arena::CreateMessage<co2::TradeList>(&arena);
|
||||
auto channel =
|
||||
consumer->get_channel(symbol, type, venue);
|
||||
auto channel = consumer->get_channel(symbol, type, venue);
|
||||
if (channel.is_initialized()) {
|
||||
cursor = channel.read_trades(*ptrades->mutable_items(), cursor);
|
||||
std::string buffer;
|
||||
|
||||
@@ -78,6 +78,19 @@ PriceSize PriceSize_from_double(double price, Size size) {
|
||||
return {IntPrice_from_double<PRECISION>(price), size};
|
||||
}
|
||||
|
||||
inline PriceSize PriceSize_from_proto(const co2::PriceSizeMessage &psm) {
|
||||
return psm.size() > 0
|
||||
? PriceSize({psm.mantissa(), (int8_t)psm.exponent()}, psm.size())
|
||||
: NO_MARKET;
|
||||
}
|
||||
|
||||
inline PriceSize PriceSize_from_proto_book(
|
||||
const google::protobuf::RepeatedPtrField<co2::PriceSizeMessage> &side,
|
||||
int index) {
|
||||
return side.size() > index ? PriceSize_from_proto(side.Get(index))
|
||||
: NO_MARKET;
|
||||
}
|
||||
|
||||
typedef utils::Optimistic<PriceSize> AtomicPriceSize;
|
||||
|
||||
void to_json(nlohmann::json &j, const PriceSize &ps);
|
||||
|
||||
@@ -366,5 +366,16 @@ inline void to_json(nlohmann::json &j, const ColdEntry &c) {
|
||||
j["deleted"] = core::BoolName::yes_no(c.deleted);
|
||||
}
|
||||
|
||||
inline bool is_heart_beat_ok(const ColdHeader &header) {
|
||||
uint32_t s_heartbeat_ms = header.heartbeat_ms;
|
||||
bool s_disable_heartbeat = header.disable_heartbeat;
|
||||
uint32_t s_grace_period_ms = header.heartbeat_boot_seconds * 1000;
|
||||
TimeStamp hb = header.heartbeat;
|
||||
TimeStamp now = TimeStamp::now();
|
||||
return (header.version == shm_version) &&
|
||||
(s_disable_heartbeat || (now - hb).milliseconds() < s_heartbeat_ms ||
|
||||
(now - header.create_time).milliseconds() < s_grace_period_ms);
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
@@ -23,15 +23,18 @@ namespace bts::md {
|
||||
class SymbolLoader {
|
||||
public:
|
||||
static std::set<UserSymbol> load(
|
||||
const bts::domain::SecurityCriteria &filter = {});
|
||||
const bts::domain::SecurityCriteria &include = {},
|
||||
const bts::domain::SecurityCriteria &exclude = {});
|
||||
|
||||
static std::size_t load(
|
||||
std::set<UserSymbol> &result,
|
||||
const bts::domain::SecurityCriteria &filter = {});
|
||||
const bts::domain::SecurityCriteria &include = {},
|
||||
const bts::domain::SecurityCriteria &exclude = {});
|
||||
|
||||
static std::size_t load(
|
||||
std::vector<UserSymbol> &result,
|
||||
const bts::domain::SecurityCriteria &filter = {});
|
||||
const bts::domain::SecurityCriteria &include = {},
|
||||
const bts::domain::SecurityCriteria &exclude = {});
|
||||
|
||||
private:
|
||||
SymbolLoader(const SymbolLoader &);
|
||||
@@ -99,17 +102,23 @@ inline void SymbolLoader::add_symbols(
|
||||
}
|
||||
|
||||
inline std::set<UserSymbol> SymbolLoader::load(
|
||||
const bts::domain::SecurityCriteria &filter) {
|
||||
const bts::domain::SecurityCriteria &include,
|
||||
const bts::domain::SecurityCriteria &exclude) {
|
||||
std::set<UserSymbol> result;
|
||||
load(result, filter);
|
||||
load(result, include);
|
||||
if (exclude.is_defined()) {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::size_t SymbolLoader::load(
|
||||
std::set<UserSymbol> &result, const bts::domain::SecurityCriteria &filter) {
|
||||
std::set<UserSymbol> &result,
|
||||
const bts::domain::SecurityCriteria &include,
|
||||
const bts::domain::SecurityCriteria &exclude) {
|
||||
const auto orig_sz = result.size();
|
||||
const auto &cfg = config::get<config::system_symbols::Symbols>();
|
||||
const bool include_all = !filter.is_defined();
|
||||
const bool include_all = !include.is_defined();
|
||||
const bool exclude_none = !exclude.is_defined();
|
||||
for (const auto &vcfg : cfg.venues()) {
|
||||
domain::protobufs::Venue venue;
|
||||
if (!parse_venue(vcfg.name(), &venue)) {
|
||||
@@ -117,20 +126,25 @@ inline std::size_t SymbolLoader::load(
|
||||
vcfg.name());
|
||||
continue;
|
||||
}
|
||||
if (include_all || filter.includes(venue, SEC_TYPE(SPOT))) {
|
||||
if ((include_all || include.includes(venue, SEC_TYPE(SPOT))) &&
|
||||
(exclude_none || !exclude.includes(venue, SEC_TYPE(SPOT)))) {
|
||||
add_symbols(vcfg.spot(), venue, SEC_TYPE(SPOT), result);
|
||||
}
|
||||
if (include_all || filter.includes(venue, SEC_TYPE(FUTURE))) {
|
||||
if ((include_all || include.includes(venue, SEC_TYPE(FUTURE))) &&
|
||||
(exclude_none || !exclude.includes(venue, SEC_TYPE(FUTURE)))) {
|
||||
add_symbols(vcfg.future(), venue, SEC_TYPE(FUTURE), result);
|
||||
}
|
||||
if (include_all || filter.includes(venue, SEC_TYPE(OPTION))) {
|
||||
if ((include_all || include.includes(venue, SEC_TYPE(OPTION))) &&
|
||||
(exclude_none || !exclude.includes(venue, SEC_TYPE(OPTION)))) {
|
||||
add_symbols(vcfg.option(), venue, SEC_TYPE(OPTION), result);
|
||||
}
|
||||
if (include_all || filter.includes(venue, SEC_TYPE(SPREAD))) {
|
||||
if ((include_all || include.includes(venue, SEC_TYPE(SPREAD))) &&
|
||||
(exclude_none || !exclude.includes(venue, SEC_TYPE(SPREAD)))) {
|
||||
add_symbols(vcfg.spread(), venue, SEC_TYPE(SPREAD), result);
|
||||
}
|
||||
if (include_all || (venue_has_synths(venue) &&
|
||||
filter.includes(venue, SEC_TYPE(SYNTHETIC)))) {
|
||||
if ((include_all || (venue_has_synths(venue) &&
|
||||
include.includes(venue, SEC_TYPE(SYNTHETIC)))) &&
|
||||
(exclude_none || !exclude.includes(venue, SEC_TYPE(SYNTHETIC)))) {
|
||||
add_symbols(vcfg.spot(), VENUE(BTS), SEC_TYPE(SYNTHETIC), result);
|
||||
add_symbols(vcfg.future(), VENUE(BTS), SEC_TYPE(SYNTHETIC), result);
|
||||
add_symbols(vcfg.option(), VENUE(BTS), SEC_TYPE(SYNTHETIC), result);
|
||||
@@ -142,9 +156,10 @@ inline std::size_t SymbolLoader::load(
|
||||
|
||||
inline std::size_t SymbolLoader::load(
|
||||
std::vector<UserSymbol> &result,
|
||||
const bts::domain::SecurityCriteria &filter) {
|
||||
const bts::domain::SecurityCriteria &include,
|
||||
const bts::domain::SecurityCriteria &exclude) {
|
||||
std::set<UserSymbol> result_set;
|
||||
auto n_loaded = load(result_set, filter);
|
||||
auto n_loaded = load(result_set, include, exclude);
|
||||
result.insert(result.end(), result_set.begin(), result_set.end());
|
||||
return n_loaded;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "md_consumer_channel.h"
|
||||
#include "spark/md/md_consumer_inst.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using std::int64_t;
|
||||
using std::shared_ptr;
|
||||
using std::size_t;
|
||||
|
||||
MDConsumerChannel::MDConsumerChannel(const shared_ptr<MDConsumerInst> &inst)
|
||||
: _pimpl(inst) {}
|
||||
|
||||
int64_t MDConsumerChannel::read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
int64_t cursor) {
|
||||
return _pimpl->read_trades(trades, cursor);
|
||||
}
|
||||
|
||||
int64_t MDConsumerChannel::read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> "es,
|
||||
int64_t cursor) {
|
||||
return _pimpl->read_rfqs(quotes, cursor);
|
||||
}
|
||||
|
||||
const std::string &MDConsumerChannel::symbol() const {
|
||||
return _pimpl->symbol();
|
||||
}
|
||||
|
||||
SecurityType MDConsumerChannel::type() const { return _pimpl->type(); }
|
||||
|
||||
Venue MDConsumerChannel::exchange() const { return _pimpl->exchange(); }
|
||||
|
||||
bool MDConsumerChannel::is_heart_beating() const {
|
||||
return _pimpl->is_heart_beating();
|
||||
}
|
||||
bool MDConsumerChannel::is_initialized() const {
|
||||
return _pimpl && security_count() > 0;
|
||||
}
|
||||
|
||||
utils::TimeStamp MDConsumerChannel::create_time() const {
|
||||
return _pimpl ? _pimpl->cold_header().create_time
|
||||
: utils::TimeStamp::invalid();
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::security_count() const {
|
||||
return _pimpl->cold_header().security_count;
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::direct_count() const {
|
||||
return is_initialized() ? _pimpl->hot_header().direct_count : 0;
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::implied_count() const {
|
||||
return is_initialized() ? _pimpl->hot_header().implied_count : 0;
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::trade_count() const {
|
||||
return _pimpl->cold_header().trade_count;
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::rfq_count() const {
|
||||
return _pimpl->cold_header().rfq_count;
|
||||
}
|
||||
|
||||
size_t MDConsumerChannel::gap_count() const {
|
||||
return _pimpl->cold_header().gap_count;
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <google/protobuf/repeated_field.h>
|
||||
#include <memory>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
class MDConsumerInst;
|
||||
|
||||
class BTS_EXPORT MDConsumerChannel {
|
||||
std::shared_ptr<MDConsumerInst> _pimpl;
|
||||
|
||||
public:
|
||||
MDConsumerChannel(const std::shared_ptr<MDConsumerInst> &inst);
|
||||
|
||||
const std::string &symbol() const;
|
||||
SecurityType type() const;
|
||||
Venue exchange() const;
|
||||
bool is_initialized() const;
|
||||
utils::TimeStamp create_time() const;
|
||||
|
||||
// Scan for new trades. If overrun is true some trades were lost
|
||||
std::int64_t read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
std::int64_t cursor);
|
||||
// Scan for new rfqs. If overrun=true some entries were lost
|
||||
std::int64_t read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> "es,
|
||||
std::int64_t cursor);
|
||||
|
||||
// Check the heartbeat has not passed the threshhold
|
||||
// (PublisherOptions.heartbeat_ms)
|
||||
bool is_heart_beating() const;
|
||||
|
||||
//
|
||||
// Statistic counters
|
||||
std::size_t security_count() const;
|
||||
std::size_t direct_count() const;
|
||||
std::size_t implied_count() const;
|
||||
std::size_t trade_count() const;
|
||||
std::size_t rfq_count() const;
|
||||
std::size_t gap_count() const;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
Whitespace-only changes.
@@ -0,0 +1,284 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/md/MemorySegmentUtils.h"
|
||||
#include "spark/md/Shm/FixedSecurity.h"
|
||||
#include "spark/md/Shm/MDStructure.h"
|
||||
#include "spark/md/ShmSegmentName.h"
|
||||
#include "spark/md/queue_struct.h"
|
||||
#include "spark/utils/SharedList.h"
|
||||
#include <btree/map.h>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
// this is for a <symbol, type, exchange> tuple
|
||||
class MDConsumerInst {
|
||||
public:
|
||||
MDConsumerInst(
|
||||
const std::string &symbol,
|
||||
api::SecurityType type,
|
||||
api::Venue exchange,
|
||||
bool shared)
|
||||
: _symbol(symbol), _type(type), _exchange(exchange), _security_count(0),
|
||||
_found_keys(), _hot(), _hot_depth(),
|
||||
_cold(ShmSegmentName::cold_name(symbol, type, exchange), shared),
|
||||
_queues() {
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::MDConsumerInst symbol: {} venue: {} type: {}",
|
||||
symbol, static_cast<int>(exchange), static_cast<int>(type));
|
||||
if (enable_depth(symbol, type)) {
|
||||
_hot_depth.reset(new utils::SharedListReader<HotHeader, HotDepthEntry>(
|
||||
ShmSegmentName::hot_name(symbol, type, exchange), shared));
|
||||
} else {
|
||||
_hot.reset(new utils::SharedListReader<HotHeader, HotEntry>(
|
||||
ShmSegmentName::hot_name(symbol, type, exchange), shared));
|
||||
}
|
||||
}
|
||||
~MDConsumerInst() {
|
||||
if (_queues)
|
||||
delete _queues;
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
size_t walk_sec_list(
|
||||
CB cb,
|
||||
const std::string &symbol = "",
|
||||
SecurityType type = api::SECURITYTYPE_UNSET) {
|
||||
size_t result = 0;
|
||||
_cold.all_entries([&symbol, type, &cb, &result](const ColdEntry &entry) {
|
||||
(void)cb;
|
||||
// not sure this double check is needed since the caller also filters
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
(entry.security.type == type || type == api::SECURITYTYPE_UNSET) &&
|
||||
(symbol.empty() || entry.security.symbol() == symbol)) {
|
||||
auto psec = std::make_shared<Security>();
|
||||
convert_security(entry.security, psec.get());
|
||||
// cb(convert_psecurity(entry.security));
|
||||
++result;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
const void *find_hot(
|
||||
utils::SharedListReader<HotHeader, T> *phot, security_key key) {
|
||||
const void *hot_entry = nullptr;
|
||||
phot->all_entries([&](const T &entry) {
|
||||
if (entry.key == key) {
|
||||
hot_entry = &entry;
|
||||
}
|
||||
});
|
||||
return hot_entry;
|
||||
}
|
||||
|
||||
bool find_handle(
|
||||
security_key key, const ColdEntry **ppcold, const void **ppvhot) {
|
||||
*ppcold = nullptr;
|
||||
*ppvhot = nullptr;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (entry.security.key == key) {
|
||||
*ppcold = &entry;
|
||||
}
|
||||
});
|
||||
|
||||
// Only search the hot list if we found cold
|
||||
if (*ppcold) {
|
||||
// It is possible that cold is initialized and hot is not yet due to
|
||||
// race between process mapped memory being visible
|
||||
size_t count = 0;
|
||||
do {
|
||||
++count;
|
||||
*ppvhot = cold_header().has_depth ? find_hot(_hot_depth.get(), key)
|
||||
: find_hot(_hot.get(), key);
|
||||
if (!*ppvhot) {
|
||||
std::this_thread::sleep_for(1ms);
|
||||
if (count == 4096)
|
||||
LOG(md, Error, "Waiting an awfully long time for key: {}",
|
||||
key);
|
||||
if (count == 60000) {
|
||||
LOG(md, Error,
|
||||
"Waited far too long for key: {} security discovery may "
|
||||
"be hung."
|
||||
" symbol: {} type: {}",
|
||||
key, std::string((*ppcold)->security.symbol()),
|
||||
SecurityType_Name((*ppcold)->security.type));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} while (!*ppvhot);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
return false;
|
||||
}
|
||||
|
||||
btree::map<security_key, std::tuple<const ColdEntry *, const void *>>
|
||||
search_handles(const std::set<security_key> &keys) {
|
||||
btree::map<security_key, std::tuple<const ColdEntry *, const void *>>
|
||||
result;
|
||||
// Walk hot and cold lists and fill in any found handles
|
||||
if (!_cold.is_initialized())
|
||||
return result;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (keys.find(entry.security.key) != keys.end()) {
|
||||
result.insert(std::make_pair(
|
||||
entry.security.key, std::make_tuple(&entry, nullptr)));
|
||||
}
|
||||
});
|
||||
// Do the same for hot
|
||||
if (_hot_depth) {
|
||||
_hot_depth->all_entries([&](const HotDepthEntry &entry) {
|
||||
auto iter = result.find(entry.key);
|
||||
if (iter != result.end()) {
|
||||
iter->second = std::make_tuple(get<0>(iter->second), &entry);
|
||||
}
|
||||
});
|
||||
} else if (_hot) {
|
||||
_hot->all_entries([&](const HotEntry &entry) {
|
||||
auto iter = result.find(entry.key);
|
||||
if (iter != result.end()) {
|
||||
iter->second = std::make_tuple(get<0>(iter->second), &entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
void scan_new_securities(CB cb) {
|
||||
// If the ver matches no securities have been added
|
||||
if (_security_count == cold_header().security_count)
|
||||
return;
|
||||
_security_count = cold_header().security_count;
|
||||
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::scan_new_securities rcvd entry: {} key: {}",
|
||||
std::string(entry.security.security_desc()), entry.security.key);
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
_found_keys.count(entry.security.key) == 0) {
|
||||
_found_keys.insert(entry.security.key);
|
||||
LOG(md, Diag,
|
||||
"MDConsumerInst::scan_new_securities firing cb entry: {}",
|
||||
std::string(entry.security.security_desc()));
|
||||
cb(entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void forget_security(security_key key) {
|
||||
_security_count -= _found_keys.erase(key);
|
||||
}
|
||||
|
||||
template <typename CB>
|
||||
void walk_old_securities(CB cb) {
|
||||
// Fire callback only for securities which *have* been seen already
|
||||
if (_found_keys.empty())
|
||||
return;
|
||||
_cold.all_entries([&](const ColdEntry &entry) {
|
||||
if (entry.security.key != invalid_security_key &&
|
||||
_found_keys.count(entry.security.key) != 0) {
|
||||
cb(entry);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
uint32_t security_count() { return cold_header().security_count; }
|
||||
|
||||
const ColdHeader &cold_header() { return _cold.header(); }
|
||||
const HotHeader &hot_header() {
|
||||
return (has_depth() ? _hot_depth->header() : _hot->header());
|
||||
}
|
||||
bool has_depth() { return cold_header().has_depth; }
|
||||
const std::string &symbol() const { return _symbol; }
|
||||
SecurityType type() const { return _type; }
|
||||
Venue exchange() const { return _exchange; }
|
||||
|
||||
//
|
||||
// Queued data
|
||||
|
||||
int64_t read_trades(
|
||||
google::protobuf::RepeatedPtrField<co2::TradeMessage> &trades,
|
||||
int64_t excursor) {
|
||||
if (init_queues()) {
|
||||
bts_assert(_queues);
|
||||
utils::WaitFreeQueue<co2::TradeMessage>::Cursor cursor(
|
||||
_queues->_trade_queue, excursor);
|
||||
bool overrun;
|
||||
cursor.read(trades, &overrun);
|
||||
// Preserve the overrun flag in the message
|
||||
if (overrun && !trades.empty()) {
|
||||
trades.begin()->set_gap(true);
|
||||
}
|
||||
return cursor.current_position();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::int64_t read_rfqs(
|
||||
google::protobuf::RepeatedPtrField<co2::QuoteRequestMessage> &rfqs,
|
||||
std::int64_t extcursor) {
|
||||
if (init_queues()) {
|
||||
bts_assert(_queues);
|
||||
bool overrun;
|
||||
std::vector<ColdHeader::RFQBuffer> temp_result;
|
||||
utils::WaitFreeQueue<ColdHeader::RFQBuffer>::Cursor cursor(
|
||||
_queues->_rfq_queue, extcursor);
|
||||
cursor.read(temp_result, &overrun);
|
||||
// deserialize the rfqs
|
||||
for (const auto &entry : temp_result) {
|
||||
rfqs.Add()->ParsePartialFromArray(&entry[0], entry.size());
|
||||
}
|
||||
if (overrun && rfqs.size() > 0) {
|
||||
rfqs.begin()->set_gap(true);
|
||||
}
|
||||
return cursor.current_position();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool is_heart_beating() {
|
||||
// Channel Heartbeat - not in a tight loop
|
||||
if (!_cold.is_initialized()) {
|
||||
return true;
|
||||
}
|
||||
return is_heart_beat_ok(cold_header());
|
||||
}
|
||||
|
||||
void dump_shm_to(const char *directory) const {
|
||||
_cold.dump_to(directory);
|
||||
if (_hot) {
|
||||
_hot->dump_to(directory);
|
||||
}
|
||||
if (_hot_depth) {
|
||||
_hot_depth->dump_to(directory);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
bool init_queues() {
|
||||
if (_queues)
|
||||
return true;
|
||||
if (!_cold.is_initialized())
|
||||
return false;
|
||||
// double assignment is OK. Leak instead of lock.
|
||||
_queues = new QueueStruct(_cold.header());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string _symbol;
|
||||
SecurityType _type;
|
||||
Venue _exchange;
|
||||
size_t _security_count;
|
||||
std::set<security_key> _found_keys;
|
||||
std::unique_ptr<utils::SharedListReader<HotHeader, HotEntry>> _hot;
|
||||
std::unique_ptr<utils::SharedListReader<HotHeader, HotDepthEntry>>
|
||||
_hot_depth;
|
||||
utils::SharedListReader<ColdHeader, ColdEntry> _cold;
|
||||
QueueStruct *_queues;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/shm/cold_header.h"
|
||||
#include "spark/utils/WaitFreeQueue.h"
|
||||
#include "system/bts_array_size.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct QueueStruct {
|
||||
utils::WaitFreeQueue<co2::TradeMessage> _trade_queue;
|
||||
utils::WaitFreeQueue<ColdHeader::RFQBuffer> _rfq_queue;
|
||||
QueueStruct(const ColdHeader &header)
|
||||
: _trade_queue(
|
||||
(void *)header.trade_buffer, BTS_ARRAYSIZE(header.trade_buffer)),
|
||||
_rfq_queue(
|
||||
(void *)header.rfq_buffer, BTS_ARRAYSIZE(header.rfq_buffer)) {}
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -1,758 +0,0 @@
|
||||
#include "spark/domain/DomainSecurityUtils.h"
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/utils/bts_assert.h"
|
||||
#ifndef _WIN32
|
||||
#include "QueryServer.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/utils/AuthToken.h"
|
||||
#include "spark/utils/Dispatcher.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
#include "spark/utils/helper_macros.h"
|
||||
|
||||
#include "../MBOProcessor.h"
|
||||
#include "../MDClient.h"
|
||||
#include "../MDConsumer.h"
|
||||
|
||||
#include "system/logging/logging.h"
|
||||
|
||||
#include "spark/api/apicore.pb.h"
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/api/service_helpers/AdminServiceUtils.h"
|
||||
#include "spark/api/services/AdminService.client.pb.h"
|
||||
#include "spark/api/services/MarketDataRelay.server.pb.h"
|
||||
#include "spark/config/protos/cme_reference_data.pb.h"
|
||||
#include "spark/md/SecurityCache.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/utils/ConcurrentAppendCollection.h"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
#ifndef _WIN32
|
||||
#include "spark/metrics/metrics.h"
|
||||
#endif
|
||||
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <google/protobuf/arena.h>
|
||||
|
||||
using namespace bts::co2;
|
||||
using bts::domain::DomainSecurityUtils;
|
||||
using std::shared_ptr;
|
||||
using std::string;
|
||||
using std::unique_ptr;
|
||||
|
||||
namespace bts {
|
||||
namespace md {
|
||||
|
||||
/*
|
||||
* NORMAL OPERATION:
|
||||
* Client sends time=0 to server
|
||||
* Server sends complete snapshot back (time=502)
|
||||
* client sends time=502 to server
|
||||
* Server sends any changes that have happened after time=502 and any securities
|
||||
* discovered since time=502
|
||||
*
|
||||
* ERROR RECOVERY:
|
||||
* Client sends time=0 to server
|
||||
* Server sends complete snapshot back (time=502)
|
||||
* Server detects heartbeat failure and recovers. All timestamps > 502
|
||||
* Client sends time=502 to server
|
||||
* Server sends complete snapshot back (time=605)
|
||||
* - Since the server shared memory has been recreated the client will
|
||||
* automatically overwrite all stale data.
|
||||
* - If a security has been deleted the client will leave it frozen (OK)
|
||||
*
|
||||
* We scan for bad heartbeats on a different time
|
||||
* If a bad heartbeat is detected we try to construct a new Consumer
|
||||
* When a good consumer is created we std::move the old consumer and handles to
|
||||
* delayed queue for deletion This way we don't have to lock anything during the
|
||||
* recovery process because all pointers will remain valid for the duration of
|
||||
* existing calls.
|
||||
*
|
||||
*/
|
||||
struct DatedHandle {
|
||||
TimeStamp discovered;
|
||||
MDConsumerHandle handle;
|
||||
};
|
||||
|
||||
struct MDConsumerGroup {
|
||||
// probably just have to send the consumer in from outside
|
||||
MDConsumerGroup(
|
||||
const UserSymbol &symbol,
|
||||
const MDConsumer &consumer,
|
||||
metrics::MetricsContainer &stats)
|
||||
: symbol(symbol), channel(consumer.get_channel(symbol)), handles(),
|
||||
mic() {
|
||||
set_consumer(consumer);
|
||||
|
||||
// create and publish a stat for this group
|
||||
#ifndef _WIN32
|
||||
if (symbol.type() != SecurityType::SECURITYTYPE_SYNTHETIC) {
|
||||
std::vector<metrics::Label> labels;
|
||||
labels.push_back({"symbol", symbol.symbol()});
|
||||
labels.push_back(
|
||||
{"type",
|
||||
SecurityType_Name(symbol.type()).substr(13) /*SECURITYTYPE_*/});
|
||||
labels.push_back(
|
||||
{"exch", Venue_Name(symbol.exchange()).substr(6) /*VENUE_*/});
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_book_updates",
|
||||
[=, this]() {
|
||||
return channel.direct_count() + channel.implied_count();
|
||||
},
|
||||
labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_security_count",
|
||||
[=, this]() { return channel.security_count(); }, labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_trade_count",
|
||||
[=, this]() { return channel.trade_count(); }, labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricD>(
|
||||
"spark_md_gap_count",
|
||||
[=, this]() {
|
||||
auto g = channel.gap_count();
|
||||
return g == 0 ? os::nan() : g;
|
||||
},
|
||||
labels));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
MDConsumerGroup(const MDConsumerGroup &other) = delete;
|
||||
|
||||
// recovery has occured and we need to clear our our collection of handles
|
||||
// and wait for new ones
|
||||
void set_consumer(const MDConsumer &consumer) {
|
||||
// create a new set of handles and swap with the old.
|
||||
// If the new consumer is bad we still have to swap our handles because
|
||||
// the consumer that owns our handles will be scheduled for deletion
|
||||
auto temphandles =
|
||||
std::make_shared<ConcurrentAppendCollection<DatedHandle>>();
|
||||
handles.swap(temphandles);
|
||||
channel = consumer.get_channel(symbol);
|
||||
}
|
||||
|
||||
void add_security(MDConsumerHandle &handle) {
|
||||
bts_assert(handles);
|
||||
bts_assert_d(handle.is_initialized());
|
||||
bts_assert(handle.get_usersymbol() == symbol);
|
||||
DatedHandle h = {TimeStamp::now(), handle};
|
||||
handles->push_back(h);
|
||||
if (this->mic == "")
|
||||
set_mic(h);
|
||||
}
|
||||
|
||||
void set_mic(const DatedHandle &h) {
|
||||
switch (channel.exchange()) {
|
||||
case api::VENUE_ICE:
|
||||
case api::VENUE_SIMICE:
|
||||
this->mic = h.handle.get_normalized_security().ice().mic_code();
|
||||
break;
|
||||
case api::VENUE_GLBX:
|
||||
case api::VENUE_SIM: {
|
||||
const auto &cme_symb_mics =
|
||||
config::get<config::CmeSymbolMics>().cme_mic();
|
||||
for (auto mic = cme_symb_mics.begin(); mic != cme_symb_mics.end();
|
||||
mic++) {
|
||||
const auto &micsym = mic->first;
|
||||
if (micsym == symbol.symbol()) {
|
||||
this->mic = api::CMEMics_Name(mic->second);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case api::VENUE_BTS:
|
||||
case api::VENUE_UNSET:
|
||||
this->mic = "BTS";
|
||||
break;
|
||||
case api::VENUE_DERIBIT:
|
||||
this->mic = "DERIBIT";
|
||||
break;
|
||||
case api::VENUE_FTX:
|
||||
this->mic = "FTX";
|
||||
break;
|
||||
case api::VENUE_BINANCE:
|
||||
this->mic = "BINANCE";
|
||||
break;
|
||||
case api::VENUE_BINANCE_US:
|
||||
this->mic = "BINANCE_US";
|
||||
break;
|
||||
case api::VENUE_COINBASE:
|
||||
this->mic = "COINBASE";
|
||||
break;
|
||||
case api::VENUE_BINANCE_USDS_FUTURES:
|
||||
this->mic = "BINANCE_USDS_FUTURES";
|
||||
break;
|
||||
case api::VENUE_OKX:
|
||||
this->mic = "OKX";
|
||||
break;
|
||||
case api::VENUE_CBOE:
|
||||
this->mic = "CBOE";
|
||||
break;
|
||||
case api::VENUE_TAIFEX:
|
||||
this->mic = "TAIFEX";
|
||||
break;
|
||||
case api::VENUE_CBOECFE:
|
||||
case api::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
|
||||
case api::Venue_INT_MAX_SENTINEL_DO_NOT_USE_:
|
||||
bts_assert(false);
|
||||
this->mic = "UNKNOWN";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
UserSymbol symbol;
|
||||
MDConsumerChannel channel;
|
||||
|
||||
// Can add to handles without invalidating readers (no lock needed)
|
||||
// When we recover we swap a new vector into this unique_ptr and
|
||||
// delayed-delete
|
||||
shared_ptr<ConcurrentAppendCollection<DatedHandle>> handles;
|
||||
std::string mic;
|
||||
};
|
||||
|
||||
void convert(PriceSize ps, PriceSizeMessage *pps) {
|
||||
pps->set_mantissa(ps.mantissa());
|
||||
pps->set_exponent(ps.exponent());
|
||||
pps->set_size(ps.size());
|
||||
}
|
||||
void set_price(PriceSize ps, co2::TradeMessage *ptrade) {
|
||||
ptrade->set_mantissa(ps.mantissa());
|
||||
ptrade->set_exponent(ps.exponent());
|
||||
ptrade->set_size(ps.size());
|
||||
}
|
||||
|
||||
void set_price(const IntPrice &price, co2::PriceMessage *dest) {
|
||||
dest->set_mantissa(price.mantissa());
|
||||
dest->set_exponent(price.exponent());
|
||||
}
|
||||
|
||||
void copy_misc(IntPrice settlement, MiscData misc, co2::MiscMessage *pmisc) {
|
||||
set_price(settlement, pmisc->mutable_settlement());
|
||||
pmisc->set_settlement_date(misc.settlement_date.to_short());
|
||||
set_price(
|
||||
misc.previous_settlement_price,
|
||||
pmisc->mutable_previous_settlement_price());
|
||||
pmisc->set_previous_settlement_date(
|
||||
misc.previous_settlement_date.to_short());
|
||||
pmisc->set_open_price(misc.open_price);
|
||||
pmisc->set_open_date(misc.open_date.to_short());
|
||||
pmisc->set_close_price(misc.close_price);
|
||||
pmisc->set_close_date(misc.close_date.to_short());
|
||||
pmisc->set_fixing_price(misc.fixing_price);
|
||||
pmisc->set_session_high(misc.session_high);
|
||||
pmisc->set_session_low(misc.session_low);
|
||||
// pmisc->set_session_high_bid(misc.session_high_bid);
|
||||
// pmisc->set_session_low_offer(misc.session_low_offer);
|
||||
}
|
||||
|
||||
// Handles market data queries and responds
|
||||
class QueryServerImpl : public IQueryServer {
|
||||
MDClient &_client;
|
||||
MDConsumer _consumer;
|
||||
int _sub;
|
||||
boost::container::flat_map<UserSymbol, shared_ptr<MDConsumerGroup>> _groups;
|
||||
|
||||
public:
|
||||
QueryServerImpl(MDClient &client, metrics::MetricsContainer &stats)
|
||||
: _client(client), _consumer(client.current_consumer()), _sub(0),
|
||||
_groups() {
|
||||
for (const auto &sym : client.symbols()) {
|
||||
_groups.emplace(std::make_pair(
|
||||
sym, std::make_unique<MDConsumerGroup>(sym, _consumer, stats)));
|
||||
}
|
||||
_groups.shrink_to_fit();
|
||||
|
||||
_sub = client.on_consumer().subscribe(
|
||||
[=, this](const MDConsumer &c) { handle_recovery(c); });
|
||||
subscribe_securities();
|
||||
}
|
||||
QueryServerImpl(const QueryServerImpl &) = delete;
|
||||
~QueryServerImpl() { _client.on_consumer().unsubscribe(_sub); }
|
||||
|
||||
void subscribe_securities() {
|
||||
LOG(md, Info, "QueryServer::subscribe_securities");
|
||||
auto id = _consumer.id();
|
||||
_consumer.on_security(
|
||||
[this, id](const SecurityPtr &sec, MDConsumerHandle handle) {
|
||||
if (_consumer.id() == id) {
|
||||
auto iter = _groups.find(handle.get_usersymbol());
|
||||
bts_assert(iter != _groups.end());
|
||||
const auto &pgroup = iter->second;
|
||||
bts_assert(pgroup);
|
||||
LOG(md, Info,
|
||||
"QueryServer::_consumer.on_security symbol:{} "
|
||||
"sec:{}",
|
||||
handle.get_usersymbol().symbol(),
|
||||
bts::securities::descriptor(*sec));
|
||||
pgroup->add_security(handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// not-reentrant
|
||||
void handle_recovery(const MDConsumer &consumer) {
|
||||
MDConsumer temp(consumer);
|
||||
if (temp.all_heartbeats_ok()) {
|
||||
_consumer.swap(temp);
|
||||
LOG(md, Info,
|
||||
"Recovering from bad MD. Old consumer {} new consumer "
|
||||
"{}",
|
||||
_consumer.id(), temp.id());
|
||||
for (auto &pair : _groups) {
|
||||
pair.second->set_consumer(_consumer);
|
||||
}
|
||||
// _handle_index.clear();
|
||||
subscribe_securities();
|
||||
utils::Dispatcher::background().post(
|
||||
[temp]() {
|
||||
LOG(md, Info, "QServer destroying consumer {}", temp.id());
|
||||
},
|
||||
60000);
|
||||
}
|
||||
}
|
||||
|
||||
// the hot part
|
||||
void fill(
|
||||
const SecurityChannel &chan,
|
||||
MDConsumerGroup &group,
|
||||
ChannelReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const {
|
||||
bts_assert(reply);
|
||||
|
||||
reply->mutable_channel()->CopyFrom(chan);
|
||||
reply->mutable_channel()->set_time(TimeStamp::now().to_uint64());
|
||||
|
||||
bool entitled = bypass_entitlement || chan.exchange() == api::VENUE_BTS;
|
||||
if (entitlements && !entitled)
|
||||
entitled = entitlements->count(group.mic);
|
||||
reply->mutable_channel()->set_entitled(entitled);
|
||||
auto flags = (MDRequest::Flags)chan.flags();
|
||||
|
||||
// Get a copy of handles. If recovery happens during this call
|
||||
// we can safely continue using this pointer for 60 seconds
|
||||
auto phandles = group.handles;
|
||||
if (!phandles)
|
||||
return;
|
||||
|
||||
ChannelUpdate temp_update;
|
||||
for (const auto &instrument : *phandles) {
|
||||
bool snapshot = false;
|
||||
MDConsumerHandle handle = instrument.handle;
|
||||
temp_update.Clear();
|
||||
bts_assert_d(handle.is_initialized());
|
||||
if (!handle.is_initialized())
|
||||
continue;
|
||||
ChannelUpdate *pupd = &temp_update;
|
||||
pupd->set_key(instrument.handle.key());
|
||||
// If the security was just discovered try to ensure all
|
||||
// data is sent
|
||||
if (instrument.discovered > TimeStamp(chan.time())) {
|
||||
auto security = handle.get_normalized_security();
|
||||
pupd->mutable_security()->CopyFrom(security);
|
||||
snapshot = true;
|
||||
}
|
||||
// if we are not entitled AND this is the first request
|
||||
// since we lost our entitlement, zero out books
|
||||
if (!entitled && chan.entitled()) {
|
||||
if (HASFLAG(flags, MDRequest::BBO) ||
|
||||
HASFLAG(flags, MDRequest::DIRECT)) {
|
||||
auto *p = pupd->mutable_direct();
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
convert(NO_MARKET, p->add_bids());
|
||||
convert(NO_MARKET, p->add_asks());
|
||||
}
|
||||
}
|
||||
if ((HASFLAG(flags, MDRequest::IMPLIED) ||
|
||||
HASFLAG(flags, MDRequest::BBO)) &&
|
||||
!handle.is_synthetic()) {
|
||||
auto *p = pupd->mutable_implied();
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
convert(NO_MARKET, p->add_bids());
|
||||
convert(NO_MARKET, p->add_asks());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (entitled) {
|
||||
// If we are entitled now but this is the first request
|
||||
// where we are ensure we send all values
|
||||
if (!chan.entitled())
|
||||
snapshot = true;
|
||||
|
||||
if (HASFLAG(flags, MDRequest::BBO) ||
|
||||
HASFLAG(flags, MDRequest::DIRECT)) {
|
||||
std::array<PriceSize, COCONUT_MAX_DEPTH> bids, asks;
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
size_t copy_depth =
|
||||
HASFLAG(flags, MDRequest::DIRECT) ? COCONUT_MAX_DEPTH : 1;
|
||||
auto result = handle.get_direct_book(
|
||||
time, copy_depth, bids.data(), asks.data());
|
||||
if (result == HandleReadResult::SUCCESS) {
|
||||
auto *p = pupd->mutable_direct();
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
PriceSize b = bids[x];
|
||||
if (b != NO_MARKET) {
|
||||
convert(b, p->add_bids());
|
||||
}
|
||||
PriceSize a = asks[x];
|
||||
if (a != NO_MARKET) {
|
||||
convert(a, p->add_asks());
|
||||
}
|
||||
}
|
||||
} else if (result == HandleReadResult::BUSY) {
|
||||
LOG(md, Info,
|
||||
"Busy read on handle {}. Retry on next "
|
||||
"request",
|
||||
instrument.handle.key());
|
||||
// If we get a busy reading BBO (which happens
|
||||
// 1-2x per day for a single relay client) We move
|
||||
// the timestamp back so the next request will try
|
||||
// to read this value again. ALTERNATIVE: We could
|
||||
// spin until the value was not busy but it could
|
||||
// be that the writer was context switched out and
|
||||
// we will have to wait multiple ms to unblock the
|
||||
// request. This fix assumes it is better to send
|
||||
// the update now with 1 stale value than to block
|
||||
// the call and allow all the values to be stale
|
||||
// until this one can be read.
|
||||
reply->mutable_channel()->set_time(chan.time());
|
||||
}
|
||||
}
|
||||
if ((HASFLAG(flags, MDRequest::IMPLIED) ||
|
||||
HASFLAG(flags, MDRequest::BBO)) &&
|
||||
!handle.is_synthetic()) {
|
||||
std::array<PriceSize, COCONUT_MAX_IMPLIED_DEPTH> bids, asks;
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
size_t copy_depth = HASFLAG(flags, MDRequest::IMPLIED)
|
||||
? COCONUT_MAX_IMPLIED_DEPTH
|
||||
: 1;
|
||||
auto result = handle.get_implied_book(
|
||||
time, copy_depth, bids.data(), asks.data());
|
||||
if (result == HandleReadResult::SUCCESS) {
|
||||
auto *p = pupd->mutable_implied();
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
PriceSize b = bids[x];
|
||||
if (b != NO_MARKET) {
|
||||
convert(b, p->add_bids());
|
||||
}
|
||||
PriceSize a = asks[x];
|
||||
if (a != NO_MARKET) {
|
||||
convert(a, p->add_asks());
|
||||
}
|
||||
}
|
||||
} else if (result == HandleReadResult::BUSY) {
|
||||
LOG(md, Info,
|
||||
"Busy read on handle (implied) {}. Retry on "
|
||||
"next request",
|
||||
instrument.handle.key());
|
||||
reply->mutable_channel()->set_time(chan.time());
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::LAST_TRADE)) {
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
PriceSize price;
|
||||
datetime::LLDateTime trade_time;
|
||||
size_t volume;
|
||||
int from_spread;
|
||||
if (handle.get_last_trade(
|
||||
time, price, trade_time, &volume, &from_spread)) {
|
||||
auto *trade = pupd->mutable_last_trade();
|
||||
trade->set_key(handle.key());
|
||||
trade->set_time(trade_time);
|
||||
trade->set_total_volume(volume);
|
||||
trade->set_from_spread(from_spread);
|
||||
set_price(price, trade);
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::MISC)) {
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
if (handle.misc_timestamp() > time) {
|
||||
copy_misc(
|
||||
handle.settlement_price(), handle.misc(),
|
||||
pupd->mutable_misc());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pupd->has_direct() || pupd->has_implied() ||
|
||||
pupd->has_last_trade() || pupd->has_misc() ||
|
||||
pupd->has_security()) {
|
||||
reply->add_updates()->CopyFrom(*pupd);
|
||||
}
|
||||
}
|
||||
|
||||
reply->mutable_channel()->set_segment_id(
|
||||
group.channel.create_time().to_uint64());
|
||||
bool is_same_segment =
|
||||
(chan.segment_id() == group.channel.create_time().to_uint64());
|
||||
|
||||
if (HASFLAG(flags, MDRequest::TRADE_LOG)) {
|
||||
int64_t request_cursor = is_same_segment ? chan.trade_cursor() : 0;
|
||||
auto cursor = group.channel.read_trades(
|
||||
*reply->mutable_trade_log(), request_cursor);
|
||||
if (cursor != chan.trade_cursor()) {
|
||||
reply->mutable_channel()->set_trade_cursor(cursor);
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::RFQ)) {
|
||||
int64_t request_cursor = is_same_segment ? chan.rfq_cursor() : 0;
|
||||
auto cursor =
|
||||
group.channel.read_rfqs(*reply->mutable_rfq_log(), request_cursor);
|
||||
if (cursor != chan.rfq_cursor()) {
|
||||
reply->mutable_channel()->set_rfq_cursor(cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void query(
|
||||
const MDRequest &request,
|
||||
MDReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const {
|
||||
bts_assert(reply != nullptr);
|
||||
for (auto &ch : request.channels()) {
|
||||
auto groupiter =
|
||||
_groups.find(UserSymbol(ch.symbol(), ch.exchange(), ch.type()));
|
||||
if (groupiter != _groups.end()) {
|
||||
auto &group = groupiter->second;
|
||||
fill(
|
||||
ch, *group, reply->add_channels(), entitlements,
|
||||
bypass_entitlement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void get_names(ExpirationNameListReply *reply) const {
|
||||
bts_assert(reply != nullptr);
|
||||
Security security;
|
||||
for (auto &groupiter : _groups) {
|
||||
const auto &group = groupiter.second;
|
||||
ExpirationNameList *psec = reply->add_securities();
|
||||
psec->mutable_product()->CopyFrom(group->symbol.to_product());
|
||||
for (const auto &h : *(group->handles)) {
|
||||
security.CopyFrom(h.handle.get_normalized_security());
|
||||
std::string desc;
|
||||
if (!DomainSecurityUtils::get_security_desc(security, desc)) {
|
||||
LOG(md, Error,
|
||||
"QueryServerImpl::get_names exchange: {} not handled",
|
||||
Venue_Name(security.exchange()));
|
||||
continue;
|
||||
}
|
||||
psec->mutable_names()->insert({h.handle.key(), desc});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void get_securities(
|
||||
google::protobuf::RepeatedField<security_key> keys,
|
||||
api::SecurityList *result) const {
|
||||
bts_assert(result);
|
||||
// Ensure keys are unique
|
||||
std::set<security_key> unique_keys(keys.begin(), keys.end());
|
||||
for (auto k : unique_keys) {
|
||||
auto ptr = _consumer.get_security(SecurityKey(k));
|
||||
if (ptr) {
|
||||
result->add_security()->CopyFrom(*ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct MDRelayServer : bts::co2::AuthenticatedMarketDataRelayBase {
|
||||
const QueryServerImpl &_db;
|
||||
utils::Dispatcher &_threadpool;
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>> _entitlements;
|
||||
#ifndef _WIN32
|
||||
std::shared_ptr<metrics::HistogramMetric<5>> _time, _size;
|
||||
#endif
|
||||
|
||||
MDRelayServer(
|
||||
const QueryServerImpl &db,
|
||||
utils::Dispatcher &threadpool,
|
||||
bts::api::ServiceContext ctx,
|
||||
metrics::MetricsContainer &stats)
|
||||
: bts::co2::AuthenticatedMarketDataRelayBase(ctx), _db(db),
|
||||
_threadpool(threadpool), _entitlements()
|
||||
#ifndef _WIN32
|
||||
,
|
||||
_time(std::make_shared<metrics::HistogramMetric<5>>(
|
||||
"spark_qserver_response_time_ms",
|
||||
std::array<double, 5>({5.0, 10.0, 20.0, 50.0, 100.0}))),
|
||||
_size(std::make_shared<metrics::HistogramMetric<5>>(
|
||||
"spark_qserver_size_bytes",
|
||||
std::array<double, 5>(
|
||||
{10240 /*10k*/, 102400 /*100k*/, 1024 * 1024 /*1mb*/,
|
||||
1024 * 1024 * 10 /*10mb*/, 1024 * 1024 * 100 /*100mb*/}))) {
|
||||
stats.publish(_time);
|
||||
stats.publish(_size);
|
||||
}
|
||||
#else
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
void update_entitlements(
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>>
|
||||
&entitlements) {
|
||||
_entitlements = entitlements;
|
||||
}
|
||||
|
||||
static const Entitlements *get_entitlements(
|
||||
uint32_t user_id,
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>>
|
||||
&entitlements) {
|
||||
if (entitlements) {
|
||||
auto iter = entitlements->find(user_id);
|
||||
if (iter != entitlements->end()) {
|
||||
return &iter->second;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
virtual void requestmd(
|
||||
const api::AuthToken &token,
|
||||
const MDRequest &request,
|
||||
const std::function<void(const MDReply &)> &reply) override {
|
||||
TimeStamp start = TimeStamp::now();
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
MDReply *preply =
|
||||
google::protobuf::Arena::CreateMessage<MDReply>(&arena);
|
||||
// addref to keep shared ptr alive
|
||||
api::user::TokenPayload payload;
|
||||
auto ents = _entitlements;
|
||||
const Entitlements *user_entitlement = nullptr;
|
||||
bool bypass_entitlement = false;
|
||||
if (api::auth::decode_token(token, &payload)) {
|
||||
bypass_entitlement = payload.wheel();
|
||||
if (!bypass_entitlement) {
|
||||
user_entitlement = get_entitlements(payload.id(), ents);
|
||||
}
|
||||
}
|
||||
// disabling md entitlements
|
||||
_db.query(
|
||||
request, preply, user_entitlement, true || bypass_entitlement);
|
||||
reply(*preply);
|
||||
#ifndef _WIN32
|
||||
auto elapsed = (TimeStamp::now() - start);
|
||||
_time->observe(elapsed.milliseconds());
|
||||
_size->observe(preply->ByteSizeLong());
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
virtual void request_products(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const ProductListReply &)> &reply) override {
|
||||
ProductListReply list;
|
||||
const auto syms = SymbolLoader::load();
|
||||
for (const auto &i : syms) {
|
||||
auto prod = list.add_products();
|
||||
prod->set_exchange(i.exchange());
|
||||
prod->set_type(i.type());
|
||||
prod->set_symbol(i.symbol());
|
||||
}
|
||||
reply(list);
|
||||
}
|
||||
|
||||
virtual void request_names(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const ExpirationNameListReply &)> &reply)
|
||||
override {
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
ExpirationNameListReply *preply =
|
||||
google::protobuf::Arena::CreateMessage<ExpirationNameListReply>(
|
||||
&arena);
|
||||
_db.get_names(preply);
|
||||
reply(*preply);
|
||||
});
|
||||
}
|
||||
|
||||
virtual void get_securities(
|
||||
const api::AuthToken &,
|
||||
const SecurityKeyList &keys,
|
||||
const std::function<void(const api::SecurityList &)> &reply) override {
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
api::SecurityList *preply =
|
||||
google::protobuf::Arena::CreateMessage<api::SecurityList>(&arena);
|
||||
_db.get_securities(keys.keys(), preply);
|
||||
reply(*preply);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
struct QueryServer {
|
||||
QueryServer(
|
||||
utils::Dispatcher &threadpool,
|
||||
const bts::api::ServiceContext &ctx,
|
||||
MDClient &client,
|
||||
metrics::MetricsContainer &stats)
|
||||
: db(client, stats), relay(db, threadpool, ctx, stats),
|
||||
admin_client(ctx.locate<api::admin::AdminService>()) {}
|
||||
QueryServerImpl db;
|
||||
MDRelayServer relay;
|
||||
api::admin::AdminService admin_client;
|
||||
rxcpp::composite_subscription entitlement_sub;
|
||||
};
|
||||
|
||||
QueryServerPtr run_query_server(
|
||||
const bts::api::ServiceContext &ctx,
|
||||
MDClient &client,
|
||||
metrics::MetricsContainer &stats) {
|
||||
auto &threadpool = utils::Dispatcher::get_named("MDQuery");
|
||||
|
||||
QueryServerPtr container =
|
||||
std::make_shared<QueryServer>(threadpool, ctx, client, stats);
|
||||
|
||||
// Subscribe to entitlement data
|
||||
container->entitlement_sub =
|
||||
container->admin_client.subscribe_md_entitlement_data().subscribe(
|
||||
[=](const api::admin::Md_entitlement_dataUpdate &update) {
|
||||
const auto &all_updates = update.all();
|
||||
utils::Dispatcher::background().post([all_updates, container]() {
|
||||
auto entitlements = std::make_shared<
|
||||
std::unordered_map<uint32_t, Entitlements>>();
|
||||
for (const auto &row : all_updates) {
|
||||
if (row && row->enabled()) {
|
||||
auto iter = entitlements->find(row->user_id());
|
||||
if (iter == entitlements->end()) {
|
||||
Entitlements ents;
|
||||
ents.insert(row->mic());
|
||||
entitlements->insert(
|
||||
iter,
|
||||
std::make_pair(row->user_id(), std::move(ents)));
|
||||
} else {
|
||||
iter->second.insert(row->mic());
|
||||
}
|
||||
}
|
||||
}
|
||||
container->relay.update_entitlements(entitlements);
|
||||
});
|
||||
});
|
||||
|
||||
// Add a few threads to keep md latency low
|
||||
for (int x = 1; x < std::min(4, os::num_cores()); ++x) {
|
||||
threadpool.add_thread();
|
||||
}
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
std::unique_ptr<IQueryServer> create_query_server(
|
||||
MDClient &mdc, metrics::MetricsContainer &mets) {
|
||||
return std::make_unique<QueryServerImpl>(mdc, mets);
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
#endif
|
||||
@@ -1,479 +0,0 @@
|
||||
#ifndef NO_CPP0X
|
||||
#include "RelayClient.h"
|
||||
#include "RelayRecorder.h"
|
||||
|
||||
#include "../MDProducer.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/utils/AuthToken.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
#include "spark/utils/bts_chrono.h"
|
||||
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/api/services/MarketDataRelay.client.pb.h"
|
||||
#include "spark/config/protos/market_data.pb.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/utils/base64.hpp"
|
||||
#include "system/logging/logging.h"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace bts {
|
||||
namespace md {
|
||||
using namespace co2;
|
||||
|
||||
using bts::system::protobufs::SystemConfig;
|
||||
|
||||
PriceSize convert(const PriceSizeMessage &psm) {
|
||||
return psm.size() > 0
|
||||
? PriceSize({psm.mantissa(), (int8_t)psm.exponent()}, psm.size())
|
||||
: NO_MARKET;
|
||||
}
|
||||
PriceSize trade_pricesize(const co2::TradeMessage &trade) {
|
||||
return trade.size() > 0
|
||||
? PriceSize(
|
||||
{trade.mantissa(), (int8_t)trade.exponent()}, trade.size())
|
||||
: NO_MARKET;
|
||||
}
|
||||
PriceSize book_at(
|
||||
const google::protobuf::RepeatedPtrField<PriceSizeMessage> &side,
|
||||
int index) {
|
||||
if (side.size() > index) {
|
||||
return convert(side.Get(index));
|
||||
}
|
||||
return NO_MARKET;
|
||||
}
|
||||
|
||||
IntPrice convert(const PriceMessage &price) {
|
||||
return {price.mantissa(), (int8_t)price.exponent()};
|
||||
}
|
||||
|
||||
class RelayProducer : public IRelayWriter {
|
||||
bool _shared;
|
||||
std::optional<MDProducer> _producer;
|
||||
unordered_map<security_key, MDProducerHandle> _handles;
|
||||
|
||||
void record_update(MDProducerHandle &handle, const ChannelUpdate &update) {
|
||||
utils::TimeStamp updated = utils::TimeStamp::now();
|
||||
bool snapshot = update.has_security();
|
||||
// If this is a snapshot an empty book() means "no market" rather than "no
|
||||
// change"
|
||||
if (update.has_direct() || update.has_implied() || snapshot) {
|
||||
std::array<PriceSize, COCONUT_MAX_DEPTH> bids, asks;
|
||||
std::array<PriceSize, COCONUT_MAX_IMPLIED_DEPTH> implied_bids,
|
||||
implied_asks;
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
bids[x] = book_at(update.direct().bids(), x);
|
||||
asks[x] = book_at(update.direct().asks(), x);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
implied_bids[x] = book_at(update.implied().bids(), x);
|
||||
implied_asks[x] = book_at(update.implied().asks(), x);
|
||||
}
|
||||
handle.update_books(updated, bids, asks, implied_bids, implied_asks);
|
||||
}
|
||||
if (update.has_misc()) {
|
||||
auto &misc = update.misc();
|
||||
handle.update_settlement(
|
||||
updated, convert(misc.settlement()),
|
||||
datetime::Date(misc.settlement_date()));
|
||||
handle.update_previous_settlement(
|
||||
updated, convert(misc.previous_settlement_price()),
|
||||
datetime::Date(misc.previous_settlement_date()));
|
||||
handle.update_opening(
|
||||
updated, misc.open_price(), datetime::Date(misc.open_date()));
|
||||
handle.update_closing(
|
||||
updated, misc.close_price(), datetime::Date(misc.close_date()));
|
||||
handle.update_session_high(updated, misc.session_high());
|
||||
handle.update_session_low(updated, misc.session_low());
|
||||
handle.update_session_high_bid(updated, misc.session_high_bid());
|
||||
handle.update_session_low_offer(updated, misc.session_low_offer());
|
||||
handle.update_fixing_price(updated, misc.fixing_price());
|
||||
}
|
||||
if (update.has_last_trade()) {
|
||||
handle.set_last_trade(
|
||||
updated, trade_pricesize(update.last_trade()),
|
||||
update.last_trade().time(), update.last_trade().total_volume(),
|
||||
update.last_trade().from_spread());
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
RelayProducer(bool shared) : _shared(shared), _handles() {}
|
||||
|
||||
MDProducer &ensure_producer() {
|
||||
if (!_producer) {
|
||||
// relay never wants to enable SecurityMapper. Securities should always
|
||||
// match the relay source.
|
||||
_producer.emplace(
|
||||
_shared ? MDProducerFlags::Shared : MDProducerFlags::None);
|
||||
}
|
||||
return *_producer;
|
||||
}
|
||||
|
||||
void write(const co2::MDReply &data, bool *phas_new_securities) override {
|
||||
auto &producer = ensure_producer();
|
||||
for (const auto &ch : data.channels()) {
|
||||
// Per-security data
|
||||
int added_security_count = 0;
|
||||
for (const auto &update : ch.updates()) {
|
||||
auto find_result = _handles.find(update.key());
|
||||
if (update.has_security() && find_result == _handles.end()) {
|
||||
if (phas_new_securities)
|
||||
*phas_new_securities = true;
|
||||
added_security_count++;
|
||||
MDProducer &producer = ensure_producer();
|
||||
with_security_like(update.security(), [&](FixedSecurity &fs) {
|
||||
convert_security(update.security(), fs, true);
|
||||
MDProducerHandle handle = producer.add_security(fs);
|
||||
_handles.insert(make_pair(handle.key(), handle));
|
||||
record_update(handle, update);
|
||||
});
|
||||
} else if (find_result != _handles.end()) {
|
||||
MDProducerHandle &handle = find_result->second;
|
||||
record_update(handle, update);
|
||||
}
|
||||
}
|
||||
// Heartbeat
|
||||
auto channel = producer.get_channel(
|
||||
ch.channel().symbol().c_str(), ch.channel().type(),
|
||||
ch.channel().exchange());
|
||||
channel.heartbeat();
|
||||
|
||||
// RFQ and TRADE LOG
|
||||
if (ch.trade_log_size() > 0 || ch.rfq_log_size() > 0) {
|
||||
if (ch.trade_log_size() > 0) {
|
||||
LOG(md, Diag, "Added {} trades", ch.trade_log_size());
|
||||
}
|
||||
for (const auto &trade : ch.trade_log()) {
|
||||
if (trade.key()) {
|
||||
channel.add_trade(trade);
|
||||
}
|
||||
}
|
||||
for (const auto &rfq : ch.rfq_log()) {
|
||||
channel.add_rfq(rfq);
|
||||
}
|
||||
}
|
||||
if (added_security_count > 0) {
|
||||
LOG(md, Diag, "Added {} {} - {}", added_security_count,
|
||||
ch.channel().symbol(), SecurityType_Name(ch.channel().type()));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
shared_ptr<IRelayWriter> mkrelayproducer(bool shared) {
|
||||
return make_shared<RelayProducer>(shared);
|
||||
}
|
||||
|
||||
// Single Threaded
|
||||
class RelayClient {
|
||||
MDRequest _request;
|
||||
MarketDataRelay &_rpc;
|
||||
MDConsumer *_pconsumer;
|
||||
IRelayWriter &_writer;
|
||||
utils::TimeStamp _request_log;
|
||||
|
||||
public:
|
||||
RelayClient(
|
||||
MarketDataRelay &rpc,
|
||||
MDConsumer *pconsumer,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer)
|
||||
: _request(), _rpc(rpc), _pconsumer(pconsumer), _writer(writer),
|
||||
_request_log(utils::TimeStamp::now()) {
|
||||
ostringstream fmt;
|
||||
fmt << config::get<SystemConfig>().host_name() << "(" << os::process_id()
|
||||
<< ")";
|
||||
_request.set_host(fmt.str());
|
||||
for (const auto &s : symbols) {
|
||||
SecurityChannel ch;
|
||||
ch.set_symbol(s.symbol());
|
||||
ch.set_type(s.type());
|
||||
ch.set_exchange(s.exchange());
|
||||
ch.set_flags(0xff);
|
||||
add_symbol(ch);
|
||||
}
|
||||
}
|
||||
|
||||
// Can be called safely with the same symbol
|
||||
void add_symbol(const SecurityChannel &ch) {
|
||||
auto find_result = std::find_if(
|
||||
_request.mutable_channels()->begin(),
|
||||
_request.mutable_channels()->end(), [&](const SecurityChannel &c) {
|
||||
return c.symbol() == ch.symbol() && c.type() == ch.type() &&
|
||||
c.exchange() == ch.exchange();
|
||||
});
|
||||
if (find_result == _request.mutable_channels()->end()) {
|
||||
auto *new_channel = _request.add_channels();
|
||||
new_channel->CopyFrom(ch);
|
||||
new_channel->set_time(0);
|
||||
} else {
|
||||
// update flags
|
||||
auto flags = find_result->flags() | ch.flags();
|
||||
if (flags != find_result->flags()) {
|
||||
find_result->set_flags(flags);
|
||||
// After changing flags request a new snapshot
|
||||
find_result->set_time(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string compact_log_format() const {
|
||||
ostringstream log;
|
||||
log << "{";
|
||||
for (const auto &ch : _request.channels()) {
|
||||
log << std::endl;
|
||||
log << ch.symbol() << " ";
|
||||
switch (ch.type()) {
|
||||
case SecurityType::SECURITYTYPE_FUTURE:
|
||||
log << "Fut ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SPREAD:
|
||||
log << "Spr ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_OPTION:
|
||||
log << "Opt ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SPOT:
|
||||
log << "Spt ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SYNTHETIC:
|
||||
log << "Syn ";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
log << Venue_Name(ch.exchange()).substr(sizeof("venue"));
|
||||
log << " " << (uint32_t)ch.time();
|
||||
log << " " << (uint16_t)ch.segment_id();
|
||||
if (!ch.entitled()) {
|
||||
log << " "
|
||||
<< "Ent=0";
|
||||
}
|
||||
}
|
||||
log << "\n}";
|
||||
auto encoded = websocketpp::base64_encode(log.str());
|
||||
return encoded;
|
||||
}
|
||||
|
||||
void request_md(std::function<void()> cont) {
|
||||
auto now = utils::TimeStamp::now();
|
||||
if ((now - _request_log).seconds() > 60) {
|
||||
_request_log = now;
|
||||
LOG(md, Info, "Requesting MD (b64): {}", compact_log_format());
|
||||
}
|
||||
_rpc.requestmd(
|
||||
_request,
|
||||
[=, this](const api::Result<MDReply> &r) {
|
||||
receive_md(r);
|
||||
cont();
|
||||
},
|
||||
500u);
|
||||
}
|
||||
void receive_md(const api::Result<MDReply> &result) {
|
||||
if (result.success()) {
|
||||
// Write data to shared mem
|
||||
bool has_new_security = false;
|
||||
_writer.write(*result.value(), &has_new_security);
|
||||
// If the reply included and we have a consumer have it scan them
|
||||
if (has_new_security && _pconsumer) {
|
||||
scan_securities_thread().post([=, this]() {
|
||||
auto count = _pconsumer->scan_securities(true);
|
||||
LOG(md, Info, "Discovered {} securities.", count);
|
||||
});
|
||||
}
|
||||
// Update reply timetamps
|
||||
for (auto &req : *_request.mutable_channels()) {
|
||||
for (auto &reply : result.value()->channels()) {
|
||||
if (req.type() == reply.channel().type() &&
|
||||
req.exchange() == reply.channel().exchange() &&
|
||||
req.symbol() == reply.channel().symbol()) {
|
||||
// disabling md entitlements
|
||||
req.set_entitled(true || reply.channel().entitled());
|
||||
req.set_time(reply.channel().time());
|
||||
req.set_trade_cursor(reply.channel().trade_cursor());
|
||||
req.set_rfq_cursor(reply.channel().rfq_cursor());
|
||||
if (req.segment_id() != reply.channel().segment_id()) {
|
||||
LOG(md, Diag, "New segment_id = {}",
|
||||
reply.channel().segment_id());
|
||||
req.set_segment_id(reply.channel().segment_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct RelayScheduler {
|
||||
uint32_t _interval;
|
||||
api::ServiceContext &_ctx;
|
||||
RelayClient &_client;
|
||||
bool running;
|
||||
double speed_factor;
|
||||
|
||||
RelayScheduler(
|
||||
api::ServiceContext &context, uint32_t interval, RelayClient &client)
|
||||
: _interval(interval), _ctx(context), _client(client), running(true),
|
||||
speed_factor(config::get<ReplayOptions>().speed()) {}
|
||||
|
||||
void run() {
|
||||
if (running) {
|
||||
utils::TimeStamp start = utils::TimeStamp::now();
|
||||
_client.request_md([=, this]() {
|
||||
int64_t elapsed_ms =
|
||||
(utils::TimeStamp::now() - start).milliseconds();
|
||||
int64_t delay = (_interval - elapsed_ms) / speed_factor;
|
||||
_ctx.post([=, this]() { run(); }, std::max(delay, (int64_t)0));
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
api::ServiceContext elevated_relay_context() {
|
||||
api::ServiceContext ctx;
|
||||
ctx.login(api::auth::generate_wheel_token());
|
||||
return ctx;
|
||||
}
|
||||
|
||||
void relay_selected(
|
||||
api::ServiceContext &ctx,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer) {
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
RelayClient client(relay, nullptr, symbols, writer);
|
||||
RelayScheduler scheduler(
|
||||
ctx, config::get<RelayOptions>().naggle_ms(), client);
|
||||
ctx.post([&]() { scheduler.run(); });
|
||||
|
||||
// block forever, I guess
|
||||
utils::Dispatcher::current().run();
|
||||
}
|
||||
|
||||
void relay_everything() {
|
||||
api::ServiceContext ctx = elevated_relay_context();
|
||||
const auto system_symbols = SymbolLoader::load();
|
||||
RelayProducer producer(true);
|
||||
relay_selected(ctx, system_symbols, producer);
|
||||
}
|
||||
|
||||
std::set<UserSymbol> get_relay_symbols(bool record_sim) {
|
||||
auto syms = SymbolLoader::load();
|
||||
if (!record_sim) {
|
||||
// Filter out VENUE_SIM
|
||||
for (auto it = syms.begin(); it != syms.end();) {
|
||||
if (it->exchange() != api::VENUE_SIM) {
|
||||
it = syms.erase(it);
|
||||
continue;
|
||||
}
|
||||
it++;
|
||||
}
|
||||
}
|
||||
return syms;
|
||||
}
|
||||
|
||||
void local_relay(IRelayWriter &writer) {
|
||||
api::ServiceContext ctx = elevated_relay_context();
|
||||
ctx.login(api::auth::generate_wheel_token());
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
auto symbols = get_relay_symbols(false);
|
||||
relay_selected(ctx, symbols, writer);
|
||||
}
|
||||
|
||||
void record_everything(std::string path, std::string filename) {
|
||||
auto options = config::get<RecordOptions>();
|
||||
if (filename.empty()) {
|
||||
ostringstream file;
|
||||
file << "marketdata"
|
||||
<< "-";
|
||||
int year, month, day, hour, minute, unused;
|
||||
datetime::ll_to_parts(
|
||||
datetime::ll_local_now(), year, month, day, hour, minute, unused,
|
||||
unused);
|
||||
file << year << setw(2) << setfill('0') << month << setw(2)
|
||||
<< setfill('0') << day << "-" << setw(2) << setfill('0') << hour
|
||||
<< setw(2) << setfill('0') << minute << ".coconut";
|
||||
filename = file.str();
|
||||
}
|
||||
|
||||
if (path.empty()) {
|
||||
path = os::app_data_path("record/").string();
|
||||
}
|
||||
|
||||
auto naggle_ms = config::get<RelayOptions>().naggle_ms();
|
||||
RelayRecorder recorder(path, filename, naggle_ms);
|
||||
|
||||
api::ServiceContext ctx = elevated_relay_context();
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
|
||||
std::set<UserSymbol> system_symbols =
|
||||
get_relay_symbols(options.record_sim());
|
||||
|
||||
RelayClient client(relay, nullptr, system_symbols, recorder);
|
||||
RelayScheduler scheduler(ctx, naggle_ms, client);
|
||||
scheduler.run();
|
||||
|
||||
utils::Dispatcher::current().run();
|
||||
}
|
||||
|
||||
/*
|
||||
* extern api for c#
|
||||
*/
|
||||
|
||||
struct RelayControl {
|
||||
RelayControl(MDConsumer *pconsumer, uint32_t interval)
|
||||
: context(), relay(context.locate<MarketDataRelay>()), producer(false),
|
||||
client(relay, pconsumer, std::set<UserSymbol>(), producer),
|
||||
scheduler(context, interval, client) {
|
||||
scheduler.run();
|
||||
}
|
||||
api::ServiceContext context;
|
||||
MarketDataRelay relay;
|
||||
RelayProducer producer;
|
||||
RelayClient client;
|
||||
RelayScheduler scheduler;
|
||||
};
|
||||
|
||||
RelayControl *start_private_relay(MDConsumer *pconsumer, uint32_t interval) {
|
||||
bts_assert(pconsumer);
|
||||
return new RelayControl(pconsumer, interval);
|
||||
}
|
||||
void stop_relay(RelayControl *relay) {
|
||||
if (relay) {
|
||||
relay->scheduler.running = false;
|
||||
bool terminated = false;
|
||||
relay->context.post([&]() { terminated = true; }, 500);
|
||||
}
|
||||
}
|
||||
void add_relay_symbol(RelayControl *relay, const SecurityChannel &chan) {
|
||||
bts_assert(relay);
|
||||
relay->context.post([=]() { relay->client.add_symbol(chan); });
|
||||
}
|
||||
void set_relay_token(RelayControl *relay, const std::string &token) {
|
||||
bts_assert(relay);
|
||||
relay->context.post([=]() {
|
||||
api::AuthToken auth_token;
|
||||
auth_token.set_token(token);
|
||||
relay->context.login(auth_token);
|
||||
});
|
||||
}
|
||||
|
||||
utils::Dispatcher &scan_securities_thread() {
|
||||
return utils::Dispatcher::background();
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
#endif
|
||||
@@ -1,48 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MDConsumer.h"
|
||||
#include "../UserSymbol.h"
|
||||
#include "spark/utils/Dispatcher.h"
|
||||
#include "spark/utils/bts_export.h"
|
||||
#include "spark/utils/bts_no_copy.h"
|
||||
#include <memory>
|
||||
#include <set>
|
||||
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
|
||||
namespace bts {
|
||||
namespace pubsub {
|
||||
class PubsubHub;
|
||||
}
|
||||
namespace api {
|
||||
class ServiceContext;
|
||||
}
|
||||
namespace md {
|
||||
|
||||
struct RelayControl;
|
||||
void add_relay_symbol(RelayControl *relay, const co2::SecurityChannel &chan);
|
||||
void set_relay_token(RelayControl *relay, const std::string &token);
|
||||
|
||||
struct IRelayWriter {
|
||||
virtual ~IRelayWriter(){};
|
||||
virtual void write(const co2::MDReply &data, bool *has_new_securities) = 0;
|
||||
};
|
||||
|
||||
utils::Dispatcher &scan_securities_thread();
|
||||
|
||||
void relay_selected(
|
||||
api::ServiceContext &ctx,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer);
|
||||
void local_relay(IRelayWriter &writer);
|
||||
|
||||
extern "C" {
|
||||
BTS_EXPORT void relay_everything();
|
||||
|
||||
BTS_EXPORT RelayControl *
|
||||
start_private_relay(MDConsumer *consumer, uint32_t interval);
|
||||
BTS_EXPORT void stop_relay(RelayControl *relay);
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/md/MDConsumerHandle.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct DatedHandle {
|
||||
utils::TimeStamp discovered;
|
||||
MDConsumerHandle handle;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,39 @@
|
||||
#include "i_relay_writer.h"
|
||||
#include "domain/security_criteria.h"
|
||||
#include "spark/api/services/MarketDataRelay.client.pb.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/md/relay/relay_client.h"
|
||||
#include "spark/md/relay/relay_scheduler.h"
|
||||
#include "spark/md/relay/relay_service_context.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using bts::api::ServiceContext;
|
||||
using bts::co2::MarketDataRelay;
|
||||
using bts::domain::SecurityCriteria;
|
||||
|
||||
void relay_selected(
|
||||
ServiceContext &ctx,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer) {
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
RelayClient client(relay, nullptr, symbols, writer);
|
||||
RelayScheduler scheduler(
|
||||
ctx, config::get<RelayOptions>().naggle_ms(), client);
|
||||
ctx.post([&]() { scheduler.run(); });
|
||||
|
||||
// block forever, I guess
|
||||
utils::Dispatcher::current().run();
|
||||
}
|
||||
|
||||
void local_relay(IRelayWriter &writer) {
|
||||
ServiceContext ctx = elevated_relay_context();
|
||||
ctx.login(api::auth::generate_wheel_token());
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
const auto exclude = SecurityCriteria::create(
|
||||
{}, {domain::protobufs::SECURITY_TYPE_SYNTHETIC});
|
||||
const auto symbols = SymbolLoader::load({}, exclude);
|
||||
relay_selected(ctx, symbols, writer);
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/md/UserSymbol.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
|
||||
#include <set>
|
||||
|
||||
namespace bts::api {
|
||||
class ServiceContext;
|
||||
}
|
||||
|
||||
namespace bts ::md {
|
||||
|
||||
struct IRelayWriter {
|
||||
virtual ~IRelayWriter(){};
|
||||
|
||||
virtual void write(const co2::MDReply &data, bool *has_new_securities) = 0;
|
||||
};
|
||||
|
||||
void relay_selected(
|
||||
api::ServiceContext &ctx,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer);
|
||||
|
||||
void local_relay(IRelayWriter &writer);
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,152 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/config/protos/cme_reference_data.pb.h"
|
||||
#include "spark/md/MDConsumer.h"
|
||||
#include "spark/md/UserSymbol.h"
|
||||
#include "spark/md/md_consumer_channel.h"
|
||||
#include "spark/md/relay/dated_handle.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
#include "spark/utils/ConcurrentAppendCollection.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct MDConsumerGroup {
|
||||
// probably just have to send the consumer in from outside
|
||||
MDConsumerGroup(
|
||||
const UserSymbol &symbol,
|
||||
const MDConsumer &consumer,
|
||||
metrics::MetricsContainer &stats)
|
||||
: symbol(symbol), channel(consumer.get_channel(symbol)), handles(),
|
||||
mic() {
|
||||
set_consumer(consumer);
|
||||
|
||||
// create and publish a stat for this group
|
||||
#ifndef _WIN32
|
||||
if (symbol.type() != SecurityType::SECURITYTYPE_SYNTHETIC) {
|
||||
std::vector<metrics::Label> labels;
|
||||
labels.push_back({"symbol", symbol.symbol()});
|
||||
labels.push_back(
|
||||
{"type",
|
||||
SecurityType_Name(symbol.type()).substr(13) /*SECURITYTYPE_*/});
|
||||
labels.push_back(
|
||||
{"exch", Venue_Name(symbol.exchange()).substr(6) /*VENUE_*/});
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_book_updates",
|
||||
[=, this]() {
|
||||
return channel.direct_count() + channel.implied_count();
|
||||
},
|
||||
labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_security_count",
|
||||
[=, this]() { return channel.security_count(); }, labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricL>(
|
||||
"spark_md_trade_count",
|
||||
[=, this]() { return channel.trade_count(); }, labels));
|
||||
stats.publish(std::make_shared<metrics::LazyCounterMetricD>(
|
||||
"spark_md_gap_count",
|
||||
[=, this]() {
|
||||
auto g = channel.gap_count();
|
||||
return g == 0 ? os::nan() : g;
|
||||
},
|
||||
labels));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
MDConsumerGroup(const MDConsumerGroup &other) = delete;
|
||||
|
||||
// recovery has occured and we need to clear our our collection of handles
|
||||
// and wait for new ones
|
||||
void set_consumer(const MDConsumer &consumer) {
|
||||
// create a new set of handles and swap with the old.
|
||||
// If the new consumer is bad we still have to swap our handles because
|
||||
// the consumer that owns our handles will be scheduled for deletion
|
||||
auto temphandles =
|
||||
std::make_shared<ConcurrentAppendCollection<DatedHandle>>();
|
||||
handles.swap(temphandles);
|
||||
channel = consumer.get_channel(symbol);
|
||||
}
|
||||
|
||||
void add_security(MDConsumerHandle &handle) {
|
||||
bts_assert(handles);
|
||||
bts_assert_d(handle.is_initialized());
|
||||
bts_assert(handle.get_usersymbol() == symbol);
|
||||
DatedHandle h = {utils::TimeStamp::now(), handle};
|
||||
handles->push_back(h);
|
||||
if (this->mic == "")
|
||||
set_mic(h);
|
||||
}
|
||||
|
||||
void set_mic(const DatedHandle &h) {
|
||||
switch (channel.exchange()) {
|
||||
case api::VENUE_ICE:
|
||||
case api::VENUE_SIMICE:
|
||||
this->mic = h.handle.get_normalized_security().ice().mic_code();
|
||||
break;
|
||||
case api::VENUE_GLBX:
|
||||
case api::VENUE_SIM: {
|
||||
const auto &cme_symb_mics =
|
||||
config::get<config::CmeSymbolMics>().cme_mic();
|
||||
for (auto mic = cme_symb_mics.begin(); mic != cme_symb_mics.end();
|
||||
mic++) {
|
||||
const auto &micsym = mic->first;
|
||||
if (micsym == symbol.symbol()) {
|
||||
this->mic = api::CMEMics_Name(mic->second);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case api::VENUE_BTS:
|
||||
case api::VENUE_UNSET:
|
||||
this->mic = "BTS";
|
||||
break;
|
||||
case api::VENUE_DERIBIT:
|
||||
this->mic = "DERIBIT";
|
||||
break;
|
||||
case api::VENUE_FTX:
|
||||
this->mic = "FTX";
|
||||
break;
|
||||
case api::VENUE_BINANCE:
|
||||
this->mic = "BINANCE";
|
||||
break;
|
||||
case api::VENUE_BINANCE_US:
|
||||
this->mic = "BINANCE_US";
|
||||
break;
|
||||
case api::VENUE_COINBASE:
|
||||
this->mic = "COINBASE";
|
||||
break;
|
||||
case api::VENUE_BINANCE_USDS_FUTURES:
|
||||
this->mic = "BINANCE_USDS_FUTURES";
|
||||
break;
|
||||
case api::VENUE_OKX:
|
||||
this->mic = "OKX";
|
||||
break;
|
||||
case api::VENUE_CBOE:
|
||||
this->mic = "CBOE";
|
||||
break;
|
||||
case api::VENUE_TAIFEX:
|
||||
this->mic = "TAIFEX";
|
||||
break;
|
||||
case api::VENUE_CBOECFE:
|
||||
case api::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
|
||||
case api::Venue_INT_MAX_SENTINEL_DO_NOT_USE_:
|
||||
bts_assert(false);
|
||||
this->mic = "UNKNOWN";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
UserSymbol symbol;
|
||||
MDConsumerChannel channel;
|
||||
|
||||
// Can add to handles without invalidating readers (no lock needed)
|
||||
// When we recover we swap a new vector into this unique_ptr and
|
||||
// delayed-delete
|
||||
std::shared_ptr<ConcurrentAppendCollection<DatedHandle>> handles;
|
||||
std::string mic;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,245 @@
|
||||
#ifndef _WIN32
|
||||
#include "md_relay_server.h"
|
||||
#include "spark/api/apicore.pb.h"
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/api/services/AdminService.client.pb.h"
|
||||
#include "spark/api/services/MarketDataRelay.server.pb.h"
|
||||
#include "spark/config/protos/cme_reference_data.pb.h"
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/md/MDClient.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/relay/query_server_impl.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
#include "spark/utils/AuthToken.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <google/protobuf/arena.h>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using bts::co2::ExpirationNameListReply;
|
||||
using bts::co2::MDReply;
|
||||
using bts::co2::ProductListReply;
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using bts::api::ServiceContext;
|
||||
using bts::api::admin::AdminService;
|
||||
using bts::co2::AuthenticatedMarketDataRelayBase;
|
||||
using bts::co2::MDRequest;
|
||||
using bts::co2::SecurityKeyList;
|
||||
using bts::metrics::MetricsContainer;
|
||||
using bts::utils::Dispatcher;
|
||||
using std::shared_ptr;
|
||||
using std::string;
|
||||
using std::unique_ptr;
|
||||
|
||||
/*
|
||||
* NORMAL OPERATION:
|
||||
* Client sends time=0 to server
|
||||
* Server sends complete snapshot back (time=502)
|
||||
* client sends time=502 to server
|
||||
* Server sends any changes that have happened after time=502 and any securities
|
||||
* discovered since time=502
|
||||
*
|
||||
* ERROR RECOVERY:
|
||||
* Client sends time=0 to server
|
||||
* Server sends complete snapshot back (time=502)
|
||||
* Server detects heartbeat failure and recovers. All timestamps > 502
|
||||
* Client sends time=502 to server
|
||||
* Server sends complete snapshot back (time=605)
|
||||
* - Since the server shared memory has been recreated the client will
|
||||
* automatically overwrite all stale data.
|
||||
* - If a security has been deleted the client will leave it frozen (OK)
|
||||
*
|
||||
* We scan for bad heartbeats on a different time
|
||||
* If a bad heartbeat is detected we try to construct a new Consumer
|
||||
* When a good consumer is created we std::move the old consumer and handles to
|
||||
* delayed queue for deletion This way we don't have to lock anything during the
|
||||
* recovery process because all pointers will remain valid for the duration of
|
||||
* existing calls.
|
||||
*
|
||||
*/
|
||||
|
||||
// Handles market data queries and responds
|
||||
|
||||
MDRelayServer::MDRelayServer(
|
||||
const QueryServerImpl &db,
|
||||
Dispatcher &threadpool,
|
||||
ServiceContext ctx,
|
||||
MetricsContainer &stats)
|
||||
: AuthenticatedMarketDataRelayBase(ctx), _db(db), _threadpool(threadpool),
|
||||
_entitlements()
|
||||
#ifndef _WIN32
|
||||
,
|
||||
_time(std::make_shared<metrics::HistogramMetric<5>>(
|
||||
"spark_qserver_response_time_ms",
|
||||
std::array<double, 5>({5.0, 10.0, 20.0, 50.0, 100.0}))),
|
||||
_size(std::make_shared<metrics::HistogramMetric<5>>(
|
||||
"spark_qserver_size_bytes",
|
||||
std::array<double, 5>(
|
||||
{10240 /*10k*/, 102400 /*100k*/, 1024 * 1024 /*1mb*/,
|
||||
1024 * 1024 * 10 /*10mb*/, 1024 * 1024 * 100 /*100mb*/}))) {
|
||||
stats.publish(_time);
|
||||
stats.publish(_size);
|
||||
}
|
||||
#else
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
void MDRelayServer::update_entitlements(
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>> &entitlements) {
|
||||
_entitlements = entitlements;
|
||||
}
|
||||
|
||||
const Entitlements *MDRelayServer::get_entitlements(
|
||||
uint32_t user_id,
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>> &entitlements) {
|
||||
if (entitlements) {
|
||||
auto iter = entitlements->find(user_id);
|
||||
if (iter != entitlements->end()) {
|
||||
return &iter->second;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void MDRelayServer::requestmd(
|
||||
const api::AuthToken &token,
|
||||
const MDRequest &request,
|
||||
const std::function<void(const MDReply &)> &reply) {
|
||||
const auto start = utils::TimeStamp::now();
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
MDReply *preply = google::protobuf::Arena::CreateMessage<MDReply>(&arena);
|
||||
// addref to keep shared ptr alive
|
||||
api::user::TokenPayload payload;
|
||||
auto ents = _entitlements;
|
||||
const Entitlements *user_entitlement = nullptr;
|
||||
bool bypass_entitlement = false;
|
||||
if (api::auth::decode_token(token, &payload)) {
|
||||
bypass_entitlement = payload.wheel();
|
||||
if (!bypass_entitlement) {
|
||||
user_entitlement = get_entitlements(payload.id(), ents);
|
||||
}
|
||||
}
|
||||
// disabling md entitlements
|
||||
_db.query(request, preply, user_entitlement, true || bypass_entitlement);
|
||||
reply(*preply);
|
||||
#ifndef _WIN32
|
||||
auto elapsed = (utils::TimeStamp::now() - start);
|
||||
_time->observe(elapsed.milliseconds());
|
||||
_size->observe(preply->ByteSizeLong());
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
void MDRelayServer::request_products(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const ProductListReply &)> &reply) {
|
||||
ProductListReply list;
|
||||
const auto syms = SymbolLoader::load();
|
||||
for (const auto &i : syms) {
|
||||
auto prod = list.add_products();
|
||||
prod->set_exchange(i.exchange());
|
||||
prod->set_type(i.type());
|
||||
prod->set_symbol(i.symbol());
|
||||
}
|
||||
reply(list);
|
||||
}
|
||||
|
||||
void MDRelayServer::request_names(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const ExpirationNameListReply &)> &reply) {
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
ExpirationNameListReply *preply =
|
||||
google::protobuf::Arena::CreateMessage<ExpirationNameListReply>(
|
||||
&arena);
|
||||
_db.get_names(preply);
|
||||
reply(*preply);
|
||||
});
|
||||
}
|
||||
|
||||
void MDRelayServer::get_securities(
|
||||
const api::AuthToken &,
|
||||
const SecurityKeyList &keys,
|
||||
const std::function<void(const api::SecurityList &)> &reply) {
|
||||
_threadpool.post([=, this]() {
|
||||
google::protobuf::Arena arena;
|
||||
api::SecurityList *preply =
|
||||
google::protobuf::Arena::CreateMessage<api::SecurityList>(&arena);
|
||||
_db.get_securities(keys.keys(), preply);
|
||||
reply(*preply);
|
||||
});
|
||||
}
|
||||
|
||||
struct QueryServer {
|
||||
QueryServer(
|
||||
Dispatcher &threadpool,
|
||||
const ServiceContext &ctx,
|
||||
MDClient &client,
|
||||
MetricsContainer &stats)
|
||||
: db(client, stats), relay(db, threadpool, ctx, stats),
|
||||
admin_client(ctx.locate<AdminService>()) {}
|
||||
QueryServerImpl db;
|
||||
MDRelayServer relay;
|
||||
AdminService admin_client;
|
||||
rxcpp::composite_subscription entitlement_sub;
|
||||
};
|
||||
|
||||
QueryServerPtr run_query_server(
|
||||
const ServiceContext &ctx, MDClient &client, MetricsContainer &stats) {
|
||||
auto &threadpool = Dispatcher::get_named("MDQuery");
|
||||
|
||||
QueryServerPtr container =
|
||||
std::make_shared<QueryServer>(threadpool, ctx, client, stats);
|
||||
|
||||
// Subscribe to entitlement data
|
||||
container->entitlement_sub =
|
||||
container->admin_client.subscribe_md_entitlement_data().subscribe(
|
||||
[=](const api::admin::Md_entitlement_dataUpdate &update) {
|
||||
const auto &all_updates = update.all();
|
||||
utils::Dispatcher::background().post([all_updates, container]() {
|
||||
auto entitlements = std::make_shared<
|
||||
std::unordered_map<uint32_t, Entitlements>>();
|
||||
for (const auto &row : all_updates) {
|
||||
if (row && row->enabled()) {
|
||||
auto iter = entitlements->find(row->user_id());
|
||||
if (iter == entitlements->end()) {
|
||||
Entitlements ents;
|
||||
ents.insert(row->mic());
|
||||
entitlements->insert(
|
||||
iter,
|
||||
std::make_pair(row->user_id(), std::move(ents)));
|
||||
} else {
|
||||
iter->second.insert(row->mic());
|
||||
}
|
||||
}
|
||||
}
|
||||
container->relay.update_entitlements(entitlements);
|
||||
});
|
||||
});
|
||||
|
||||
// Add a few threads to keep md latency low
|
||||
for (int x = 1; x < std::min(4, os::num_cores()); ++x) {
|
||||
threadpool.add_thread();
|
||||
}
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
std::unique_ptr<IQueryServer> create_query_server(
|
||||
MDClient &mdc, metrics::MetricsContainer &mets) {
|
||||
return std::make_unique<QueryServerImpl>(mdc, mets);
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
#endif
|
||||
@@ -0,0 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include "query_server.h"
|
||||
#include "spark/api/apicore.pb.h"
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/api/services/MarketDataRelay.server.pb.h"
|
||||
#include "spark/domain_model/Security.pb.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/relay/query_server_impl.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <google/protobuf/arena.h>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
/**
|
||||
* Handles market data queries and responds
|
||||
*/
|
||||
struct MDRelayServer : bts::co2::AuthenticatedMarketDataRelayBase {
|
||||
const QueryServerImpl &_db;
|
||||
utils::Dispatcher &_threadpool;
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>> _entitlements;
|
||||
#ifndef _WIN32
|
||||
std::shared_ptr<metrics::HistogramMetric<5>> _time, _size;
|
||||
#endif
|
||||
|
||||
MDRelayServer(
|
||||
const QueryServerImpl &db,
|
||||
utils::Dispatcher &threadpool,
|
||||
api::ServiceContext ctx,
|
||||
metrics::MetricsContainer &stats);
|
||||
|
||||
void update_entitlements(
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>>
|
||||
&entitlements);
|
||||
|
||||
static const Entitlements *get_entitlements(
|
||||
uint32_t user_id,
|
||||
std::shared_ptr<std::unordered_map<uint32_t, Entitlements>>
|
||||
&entitlements);
|
||||
|
||||
virtual void requestmd(
|
||||
const api::AuthToken &token,
|
||||
const co2::MDRequest &request,
|
||||
const std::function<void(const co2::MDReply &)> &reply) override;
|
||||
|
||||
virtual void request_products(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const co2::ProductListReply &)> &reply)
|
||||
override;
|
||||
|
||||
virtual void request_names(
|
||||
const api::AuthToken &,
|
||||
const api::VoidMessage &,
|
||||
const std::function<void(const co2::ExpirationNameListReply &)> &reply)
|
||||
override;
|
||||
|
||||
virtual void get_securities(
|
||||
const api::AuthToken &,
|
||||
const co2::SecurityKeyList &keys,
|
||||
const std::function<void(const api::SecurityList &)> &reply) override;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
+15
-17
@@ -1,43 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/md/ISyntheticSecurityService.h"
|
||||
#include "spark/md/UserSymbol.h"
|
||||
#include "spark/utils/bts_export.h"
|
||||
#include "spark/utils/bts_no_copy.h"
|
||||
#include <boost/container/flat_set.hpp>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
|
||||
namespace bts {
|
||||
namespace api {
|
||||
#include <boost/container/flat_set.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace bts::api {
|
||||
class ServiceContext;
|
||||
}
|
||||
namespace metrics {
|
||||
|
||||
namespace bts::metrics {
|
||||
class MetricsContainer;
|
||||
}
|
||||
namespace md {
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct QueryServer;
|
||||
typedef std::shared_ptr<QueryServer> QueryServerPtr;
|
||||
|
||||
class MDClient;
|
||||
typedef boost::container::flat_set<std::string> Entitlements;
|
||||
|
||||
// provides a polling interface on top of market data
|
||||
|
||||
struct IQueryServer {
|
||||
virtual ~IQueryServer() {}
|
||||
|
||||
virtual void query(
|
||||
const co2::MDRequest &request,
|
||||
co2::MDReply *reply,
|
||||
const Entitlements *,
|
||||
bool) const = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<IQueryServer> create_query_server(
|
||||
MDClient &, metrics::MetricsContainer &);
|
||||
|
||||
struct QueryServer;
|
||||
typedef std::shared_ptr<QueryServer> QueryServerPtr;
|
||||
QueryServerPtr run_query_server(
|
||||
const bts::api::ServiceContext &, MDClient &, metrics::MetricsContainer &);
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,364 @@
|
||||
#include "query_server_impl.h"
|
||||
#include "spark/domain/DomainSecurityUtils.h"
|
||||
#include "spark/domain_model/Security.h"
|
||||
#include "spark/utils/helper_macros.h"
|
||||
|
||||
#include <set>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using bts::co2::ChannelReply;
|
||||
using bts::co2::ChannelUpdate;
|
||||
using bts::co2::ExpirationNameList;
|
||||
using bts::co2::ExpirationNameListReply;
|
||||
using bts::co2::MDReply;
|
||||
using bts::co2::MDRequest;
|
||||
using bts::co2::MiscMessage;
|
||||
using bts::co2::PriceMessage;
|
||||
using bts::co2::PriceSizeMessage;
|
||||
using bts::co2::SecurityChannel;
|
||||
using bts::co2::TradeMessage;
|
||||
using bts::domain::DomainSecurityUtils;
|
||||
using bts::utils::TimeStamp;
|
||||
using std::uint32_t;
|
||||
|
||||
static void convert(PriceSize ps, PriceSizeMessage *pps) {
|
||||
pps->set_mantissa(ps.mantissa());
|
||||
pps->set_exponent(ps.exponent());
|
||||
pps->set_size(ps.size());
|
||||
}
|
||||
|
||||
static void set_price(PriceSize ps, TradeMessage *ptrade) {
|
||||
ptrade->set_mantissa(ps.mantissa());
|
||||
ptrade->set_exponent(ps.exponent());
|
||||
ptrade->set_size(ps.size());
|
||||
}
|
||||
|
||||
static void set_price(const IntPrice &price, PriceMessage *dest) {
|
||||
dest->set_mantissa(price.mantissa());
|
||||
dest->set_exponent(price.exponent());
|
||||
}
|
||||
|
||||
static void copy_misc(IntPrice settlement, MiscData misc, MiscMessage *pmisc) {
|
||||
set_price(settlement, pmisc->mutable_settlement());
|
||||
pmisc->set_settlement_date(misc.settlement_date.to_short());
|
||||
set_price(
|
||||
misc.previous_settlement_price,
|
||||
pmisc->mutable_previous_settlement_price());
|
||||
pmisc->set_previous_settlement_date(
|
||||
misc.previous_settlement_date.to_short());
|
||||
pmisc->set_open_price(misc.open_price);
|
||||
pmisc->set_open_date(misc.open_date.to_short());
|
||||
pmisc->set_close_price(misc.close_price);
|
||||
pmisc->set_close_date(misc.close_date.to_short());
|
||||
pmisc->set_fixing_price(misc.fixing_price);
|
||||
pmisc->set_session_high(misc.session_high);
|
||||
pmisc->set_session_low(misc.session_low);
|
||||
// pmisc->set_session_high_bid(misc.session_high_bid);
|
||||
// pmisc->set_session_low_offer(misc.session_low_offer);
|
||||
}
|
||||
|
||||
QueryServerImpl::QueryServerImpl(
|
||||
MDClient &client, metrics::MetricsContainer &stats)
|
||||
: _client(client), _consumer(client.current_consumer()), _sub(0),
|
||||
_groups() {
|
||||
for (const auto &sym : client.symbols()) {
|
||||
_groups.emplace(std::make_pair(
|
||||
sym, std::make_unique<MDConsumerGroup>(sym, _consumer, stats)));
|
||||
}
|
||||
_groups.shrink_to_fit();
|
||||
|
||||
_sub = client.on_consumer().subscribe(
|
||||
[=, this](const MDConsumer &c) { handle_recovery(c); });
|
||||
subscribe_securities();
|
||||
}
|
||||
|
||||
QueryServerImpl::~QueryServerImpl() { _client.on_consumer().unsubscribe(_sub); }
|
||||
|
||||
void QueryServerImpl::subscribe_securities() {
|
||||
LOG(md, Info, "QueryServer::subscribe_securities");
|
||||
auto id = _consumer.id();
|
||||
_consumer.on_security(
|
||||
[this, id](const SecurityPtr &sec, MDConsumerHandle handle) {
|
||||
if (_consumer.id() == id) {
|
||||
auto iter = _groups.find(handle.get_usersymbol());
|
||||
bts_assert(iter != _groups.end());
|
||||
const auto &pgroup = iter->second;
|
||||
bts_assert(pgroup);
|
||||
LOG(md, Info,
|
||||
"QueryServer::_consumer.on_security symbol:{} "
|
||||
"sec:{}",
|
||||
handle.get_usersymbol().symbol(),
|
||||
bts::securities::descriptor(*sec));
|
||||
pgroup->add_security(handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// not-reentrant
|
||||
void QueryServerImpl::handle_recovery(const MDConsumer &consumer) {
|
||||
MDConsumer temp(consumer);
|
||||
if (temp.all_heartbeats_ok()) {
|
||||
_consumer.swap(temp);
|
||||
LOG(md, Info,
|
||||
"Recovering from bad MD. Old consumer {} new consumer "
|
||||
"{}",
|
||||
_consumer.id(), temp.id());
|
||||
for (auto &pair : _groups) {
|
||||
pair.second->set_consumer(_consumer);
|
||||
}
|
||||
// _handle_index.clear();
|
||||
subscribe_securities();
|
||||
utils::Dispatcher::background().post(
|
||||
[temp]() {
|
||||
LOG(md, Info, "QServer destroying consumer {}", temp.id());
|
||||
},
|
||||
60000);
|
||||
}
|
||||
}
|
||||
|
||||
// the hot part
|
||||
void QueryServerImpl::fill(
|
||||
const SecurityChannel &chan,
|
||||
MDConsumerGroup &group,
|
||||
ChannelReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const {
|
||||
bts_assert(reply);
|
||||
|
||||
reply->mutable_channel()->CopyFrom(chan);
|
||||
reply->mutable_channel()->set_time(TimeStamp::now().to_uint64());
|
||||
|
||||
bool entitled = bypass_entitlement || chan.exchange() == api::VENUE_BTS;
|
||||
if (entitlements && !entitled)
|
||||
entitled = entitlements->count(group.mic);
|
||||
reply->mutable_channel()->set_entitled(entitled);
|
||||
auto flags = (co2::MDRequest::Flags)chan.flags();
|
||||
|
||||
// Get a copy of handles. If recovery happens during this call
|
||||
// we can safely continue using this pointer for 60 seconds
|
||||
auto phandles = group.handles;
|
||||
if (!phandles)
|
||||
return;
|
||||
|
||||
ChannelUpdate temp_update;
|
||||
for (const auto &instrument : *phandles) {
|
||||
bool snapshot = false;
|
||||
MDConsumerHandle handle = instrument.handle;
|
||||
temp_update.Clear();
|
||||
bts_assert_d(handle.is_initialized());
|
||||
if (!handle.is_initialized())
|
||||
continue;
|
||||
ChannelUpdate *pupd = &temp_update;
|
||||
pupd->set_key(instrument.handle.key());
|
||||
// If the security was just discovered try to ensure all
|
||||
// data is sent
|
||||
if (instrument.discovered > TimeStamp(chan.time())) {
|
||||
auto security = handle.get_normalized_security();
|
||||
pupd->mutable_security()->CopyFrom(security);
|
||||
snapshot = true;
|
||||
}
|
||||
// if we are not entitled AND this is the first request
|
||||
// since we lost our entitlement, zero out books
|
||||
if (!entitled && chan.entitled()) {
|
||||
if (HASFLAG(flags, MDRequest::BBO) ||
|
||||
HASFLAG(flags, MDRequest::DIRECT)) {
|
||||
auto *p = pupd->mutable_direct();
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
convert(NO_MARKET, p->add_bids());
|
||||
convert(NO_MARKET, p->add_asks());
|
||||
}
|
||||
}
|
||||
if ((HASFLAG(flags, MDRequest::IMPLIED) ||
|
||||
HASFLAG(flags, MDRequest::BBO)) &&
|
||||
!handle.is_synthetic()) {
|
||||
auto *p = pupd->mutable_implied();
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
convert(NO_MARKET, p->add_bids());
|
||||
convert(NO_MARKET, p->add_asks());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (entitled) {
|
||||
// If we are entitled now but this is the first request
|
||||
// where we are ensure we send all values
|
||||
if (!chan.entitled())
|
||||
snapshot = true;
|
||||
|
||||
if (HASFLAG(flags, MDRequest::BBO) ||
|
||||
HASFLAG(flags, MDRequest::DIRECT)) {
|
||||
std::array<PriceSize, COCONUT_MAX_DEPTH> bids, asks;
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
size_t copy_depth =
|
||||
HASFLAG(flags, MDRequest::DIRECT) ? COCONUT_MAX_DEPTH : 1;
|
||||
auto result = handle.get_direct_book(
|
||||
time, copy_depth, bids.data(), asks.data());
|
||||
if (result == HandleReadResult::SUCCESS) {
|
||||
auto *p = pupd->mutable_direct();
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
PriceSize b = bids[x];
|
||||
if (b != NO_MARKET) {
|
||||
convert(b, p->add_bids());
|
||||
}
|
||||
PriceSize a = asks[x];
|
||||
if (a != NO_MARKET) {
|
||||
convert(a, p->add_asks());
|
||||
}
|
||||
}
|
||||
} else if (result == HandleReadResult::BUSY) {
|
||||
LOG(md, Info,
|
||||
"Busy read on handle {}. Retry on next "
|
||||
"request",
|
||||
instrument.handle.key());
|
||||
// If we get a busy reading BBO (which happens
|
||||
// 1-2x per day for a single relay client) We move
|
||||
// the timestamp back so the next request will try
|
||||
// to read this value again. ALTERNATIVE: We could
|
||||
// spin until the value was not busy but it could
|
||||
// be that the writer was context switched out and
|
||||
// we will have to wait multiple ms to unblock the
|
||||
// request. This fix assumes it is better to send
|
||||
// the update now with 1 stale value than to block
|
||||
// the call and allow all the values to be stale
|
||||
// until this one can be read.
|
||||
reply->mutable_channel()->set_time(chan.time());
|
||||
}
|
||||
}
|
||||
if ((HASFLAG(flags, MDRequest::IMPLIED) ||
|
||||
HASFLAG(flags, MDRequest::BBO)) &&
|
||||
!handle.is_synthetic()) {
|
||||
std::array<PriceSize, COCONUT_MAX_IMPLIED_DEPTH> bids, asks;
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
size_t copy_depth = HASFLAG(flags, MDRequest::IMPLIED)
|
||||
? COCONUT_MAX_IMPLIED_DEPTH
|
||||
: 1;
|
||||
auto result = handle.get_implied_book(
|
||||
time, copy_depth, bids.data(), asks.data());
|
||||
if (result == HandleReadResult::SUCCESS) {
|
||||
auto *p = pupd->mutable_implied();
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
PriceSize b = bids[x];
|
||||
if (b != NO_MARKET) {
|
||||
convert(b, p->add_bids());
|
||||
}
|
||||
PriceSize a = asks[x];
|
||||
if (a != NO_MARKET) {
|
||||
convert(a, p->add_asks());
|
||||
}
|
||||
}
|
||||
} else if (result == HandleReadResult::BUSY) {
|
||||
LOG(md, Info,
|
||||
"Busy read on handle (implied) {}. Retry on "
|
||||
"next request",
|
||||
instrument.handle.key());
|
||||
reply->mutable_channel()->set_time(chan.time());
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::LAST_TRADE)) {
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
PriceSize price;
|
||||
datetime::LLDateTime trade_time;
|
||||
size_t volume;
|
||||
int from_spread;
|
||||
if (handle.get_last_trade(
|
||||
time, price, trade_time, &volume, &from_spread)) {
|
||||
auto *trade = pupd->mutable_last_trade();
|
||||
trade->set_key(handle.key());
|
||||
trade->set_time(trade_time);
|
||||
trade->set_total_volume(volume);
|
||||
trade->set_from_spread(from_spread);
|
||||
set_price(price, trade);
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::MISC)) {
|
||||
TimeStamp time(snapshot ? 0 : chan.time());
|
||||
if (handle.misc_timestamp() > time) {
|
||||
copy_misc(
|
||||
handle.settlement_price(), handle.misc(),
|
||||
pupd->mutable_misc());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pupd->has_direct() || pupd->has_implied() || pupd->has_last_trade() ||
|
||||
pupd->has_misc() || pupd->has_security()) {
|
||||
reply->add_updates()->CopyFrom(*pupd);
|
||||
}
|
||||
}
|
||||
|
||||
reply->mutable_channel()->set_segment_id(
|
||||
group.channel.create_time().to_uint64());
|
||||
bool is_same_segment =
|
||||
(chan.segment_id() == group.channel.create_time().to_uint64());
|
||||
|
||||
if (HASFLAG(flags, MDRequest::TRADE_LOG)) {
|
||||
int64_t request_cursor = is_same_segment ? chan.trade_cursor() : 0;
|
||||
auto cursor = group.channel.read_trades(
|
||||
*reply->mutable_trade_log(), request_cursor);
|
||||
if (cursor != chan.trade_cursor()) {
|
||||
reply->mutable_channel()->set_trade_cursor(cursor);
|
||||
}
|
||||
}
|
||||
if (HASFLAG(flags, MDRequest::RFQ)) {
|
||||
int64_t request_cursor = is_same_segment ? chan.rfq_cursor() : 0;
|
||||
auto cursor =
|
||||
group.channel.read_rfqs(*reply->mutable_rfq_log(), request_cursor);
|
||||
if (cursor != chan.rfq_cursor()) {
|
||||
reply->mutable_channel()->set_rfq_cursor(cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void QueryServerImpl::query(
|
||||
const MDRequest &request,
|
||||
MDReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const {
|
||||
bts_assert(reply != nullptr);
|
||||
for (auto &ch : request.channels()) {
|
||||
auto groupiter =
|
||||
_groups.find(UserSymbol(ch.symbol(), ch.exchange(), ch.type()));
|
||||
if (groupiter != _groups.end()) {
|
||||
auto &group = groupiter->second;
|
||||
fill(
|
||||
ch, *group, reply->add_channels(), entitlements,
|
||||
bypass_entitlement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void QueryServerImpl::get_names(ExpirationNameListReply *reply) const {
|
||||
bts_assert(reply != nullptr);
|
||||
Security security;
|
||||
for (auto &groupiter : _groups) {
|
||||
const auto &group = groupiter.second;
|
||||
ExpirationNameList *psec = reply->add_securities();
|
||||
psec->mutable_product()->CopyFrom(group->symbol.to_product());
|
||||
for (const auto &h : *(group->handles)) {
|
||||
security.CopyFrom(h.handle.get_normalized_security());
|
||||
std::string desc;
|
||||
if (!DomainSecurityUtils::get_security_desc(security, desc)) {
|
||||
LOG(md, Error,
|
||||
"QueryServerImpl::get_names exchange: {} not handled",
|
||||
Venue_Name(security.exchange()));
|
||||
continue;
|
||||
}
|
||||
psec->mutable_names()->insert({h.handle.key(), desc});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void QueryServerImpl::get_securities(
|
||||
google::protobuf::RepeatedField<uint32_t> keys,
|
||||
api::SecurityList *result) const {
|
||||
bts_assert(result);
|
||||
// Ensure keys are unique
|
||||
std::set<uint32_t> unique_keys{keys.begin(), keys.end()};
|
||||
for (auto k : unique_keys) {
|
||||
auto ptr = _consumer.get_security(SecurityKey(k));
|
||||
if (ptr) {
|
||||
result->add_security()->CopyFrom(*ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/api/services/MarketDataRelay.pb.h"
|
||||
#include "spark/md/MDClient.h"
|
||||
#include "spark/md/MDConsumer.h"
|
||||
#include "spark/md/relay/md_consumer_group.h"
|
||||
#include "spark/md/relay/query_server.h"
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
class QueryServerImpl : public IQueryServer {
|
||||
MDClient &_client;
|
||||
MDConsumer _consumer;
|
||||
int _sub;
|
||||
boost::container::flat_map<UserSymbol, std::shared_ptr<MDConsumerGroup>>
|
||||
_groups;
|
||||
|
||||
public:
|
||||
QueryServerImpl(MDClient &client, metrics::MetricsContainer &stats);
|
||||
QueryServerImpl(const QueryServerImpl &) = delete;
|
||||
~QueryServerImpl();
|
||||
|
||||
QueryServerImpl &operator=(const QueryServerImpl &) = delete;
|
||||
|
||||
void subscribe_securities();
|
||||
|
||||
// not-reentrant
|
||||
void handle_recovery(const MDConsumer &consumer);
|
||||
|
||||
// the hot part
|
||||
void fill(
|
||||
const co2::SecurityChannel &channel,
|
||||
MDConsumerGroup &group,
|
||||
co2::ChannelReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const;
|
||||
|
||||
void query(
|
||||
const co2::MDRequest &request,
|
||||
co2::MDReply *reply,
|
||||
const Entitlements *entitlements,
|
||||
bool bypass_entitlement) const;
|
||||
|
||||
void get_names(co2::ExpirationNameListReply *reply) const;
|
||||
|
||||
void get_securities(
|
||||
google::protobuf::RepeatedField<std::uint32_t> keys,
|
||||
api::SecurityList *result) const;
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "relay_client.h"
|
||||
#include "spark/api/services/MarketDataRelay.client.pb.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/relay/relay_scanner_thread.h"
|
||||
#include "spark/utils/base64.hpp"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using co2::MarketDataRelay;
|
||||
using co2::MDReply;
|
||||
using co2::SecurityChannel;
|
||||
using std::ostringstream;
|
||||
using system::protobufs::SystemConfig;
|
||||
|
||||
RelayClient::RelayClient(
|
||||
MarketDataRelay &rpc,
|
||||
MDConsumer *pconsumer,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer)
|
||||
: _request(), _rpc(rpc), _pconsumer(pconsumer), _writer(writer),
|
||||
_request_log(utils::TimeStamp::now()) {
|
||||
ostringstream fmt;
|
||||
fmt << config::get<SystemConfig>().host_name() << "(" << os::process_id()
|
||||
<< ")";
|
||||
_request.set_host(fmt.str());
|
||||
for (const auto &s : symbols) {
|
||||
SecurityChannel ch;
|
||||
ch.set_symbol(s.symbol());
|
||||
ch.set_type(s.type());
|
||||
ch.set_exchange(s.exchange());
|
||||
ch.set_flags(0xff);
|
||||
add_symbol(ch);
|
||||
}
|
||||
}
|
||||
|
||||
// Can be called safely with the same symbol
|
||||
void RelayClient::add_symbol(const SecurityChannel &ch) {
|
||||
auto find_result = std::find_if(
|
||||
_request.mutable_channels()->begin(), _request.mutable_channels()->end(),
|
||||
[&](const SecurityChannel &c) {
|
||||
return c.symbol() == ch.symbol() && c.type() == ch.type() &&
|
||||
c.exchange() == ch.exchange();
|
||||
});
|
||||
if (find_result == _request.mutable_channels()->end()) {
|
||||
auto *new_channel = _request.add_channels();
|
||||
new_channel->CopyFrom(ch);
|
||||
new_channel->set_time(0);
|
||||
} else {
|
||||
// update flags
|
||||
auto flags = find_result->flags() | ch.flags();
|
||||
if (flags != find_result->flags()) {
|
||||
find_result->set_flags(flags);
|
||||
// After changing flags request a new snapshot
|
||||
find_result->set_time(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string RelayClient::compact_log_format() const {
|
||||
ostringstream log;
|
||||
log << "{";
|
||||
for (const auto &ch : _request.channels()) {
|
||||
log << std::endl;
|
||||
log << ch.symbol() << " ";
|
||||
switch (ch.type()) {
|
||||
case SecurityType::SECURITYTYPE_FUTURE:
|
||||
log << "Fut ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SPREAD:
|
||||
log << "Spr ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_OPTION:
|
||||
log << "Opt ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SPOT:
|
||||
log << "Spt ";
|
||||
break;
|
||||
case SecurityType::SECURITYTYPE_SYNTHETIC:
|
||||
log << "Syn ";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
log << Venue_Name(ch.exchange()).substr(sizeof("venue"));
|
||||
log << " " << (uint32_t)ch.time();
|
||||
log << " " << (uint16_t)ch.segment_id();
|
||||
if (!ch.entitled()) {
|
||||
log << " "
|
||||
<< "Ent=0";
|
||||
}
|
||||
}
|
||||
log << "\n}";
|
||||
auto encoded = websocketpp::base64_encode(log.str());
|
||||
return encoded;
|
||||
}
|
||||
|
||||
void RelayClient::request_md(std::function<void()> cont) {
|
||||
auto now = utils::TimeStamp::now();
|
||||
if ((now - _request_log).seconds() > 60) {
|
||||
_request_log = now;
|
||||
LOG(md, Info, "Requesting MD (b64): {}", compact_log_format());
|
||||
}
|
||||
_rpc.requestmd(
|
||||
_request,
|
||||
[=, this](const api::Result<MDReply> &r) {
|
||||
receive_md(r);
|
||||
cont();
|
||||
},
|
||||
500u);
|
||||
}
|
||||
|
||||
void RelayClient::receive_md(const api::Result<MDReply> &result) {
|
||||
if (result.success()) {
|
||||
// Write data to shared mem
|
||||
bool has_new_security = false;
|
||||
_writer.write(*result.value(), &has_new_security);
|
||||
// If the reply included and we have a consumer have it scan them
|
||||
if (has_new_security && _pconsumer) {
|
||||
scan_securities_thread().post([=, this]() {
|
||||
auto count = _pconsumer->scan_securities(true);
|
||||
LOG(md, Info, "Discovered {} securities.", count);
|
||||
});
|
||||
}
|
||||
// Update reply timetamps
|
||||
for (auto &req : *_request.mutable_channels()) {
|
||||
for (auto &reply : result.value()->channels()) {
|
||||
if (req.type() == reply.channel().type() &&
|
||||
req.exchange() == reply.channel().exchange() &&
|
||||
req.symbol() == reply.channel().symbol()) {
|
||||
// disabling md entitlements
|
||||
req.set_entitled(true || reply.channel().entitled());
|
||||
req.set_time(reply.channel().time());
|
||||
req.set_trade_cursor(reply.channel().trade_cursor());
|
||||
req.set_rfq_cursor(reply.channel().rfq_cursor());
|
||||
if (req.segment_id() != reply.channel().segment_id()) {
|
||||
LOG(md, Diag, "New segment_id = {}",
|
||||
reply.channel().segment_id());
|
||||
req.set_segment_id(reply.channel().segment_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/api/services/MarketDataRelay.client.pb.h"
|
||||
#include "spark/md/MDConsumer.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/relay/i_relay_writer.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
|
||||
#include <functional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
// Single Threaded
|
||||
class RelayClient {
|
||||
co2::MDRequest _request;
|
||||
co2::MarketDataRelay &_rpc;
|
||||
MDConsumer *_pconsumer;
|
||||
IRelayWriter &_writer;
|
||||
utils::TimeStamp _request_log;
|
||||
|
||||
public:
|
||||
RelayClient(
|
||||
co2::MarketDataRelay &rpc,
|
||||
MDConsumer *pconsumer,
|
||||
const std::set<UserSymbol> &symbols,
|
||||
IRelayWriter &writer);
|
||||
|
||||
// Can be called safely with the same symbol
|
||||
void add_symbol(const co2::SecurityChannel &ch);
|
||||
|
||||
std::string compact_log_format() const;
|
||||
|
||||
void request_md(std::function<void()> cont);
|
||||
void receive_md(const api::Result<co2::MDReply> &result);
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "relay_control.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/md/relay/relay_service_context.h"
|
||||
#include "spark/utils/AuthToken.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using std::uint32_t;
|
||||
|
||||
void add_relay_symbol(RelayControl *relay, const co2::SecurityChannel &chan) {
|
||||
bts_assert(relay);
|
||||
relay->context.post([=]() { relay->client.add_symbol(chan); });
|
||||
}
|
||||
|
||||
void set_relay_token(RelayControl *relay, const std::string &token) {
|
||||
bts_assert(relay);
|
||||
relay->context.post([=]() {
|
||||
api::AuthToken auth_token;
|
||||
auth_token.set_token(token);
|
||||
relay->context.login(auth_token);
|
||||
});
|
||||
}
|
||||
|
||||
void relay_everything() {
|
||||
api::ServiceContext ctx = elevated_relay_context();
|
||||
const auto system_symbols = SymbolLoader::load();
|
||||
RelayProducer producer(true);
|
||||
relay_selected(ctx, system_symbols, producer);
|
||||
}
|
||||
|
||||
RelayControl *start_private_relay(MDConsumer *pconsumer, uint32_t interval) {
|
||||
bts_assert(pconsumer);
|
||||
return new RelayControl(pconsumer, interval);
|
||||
}
|
||||
|
||||
void stop_relay(RelayControl *relay) {
|
||||
if (relay) {
|
||||
relay->scheduler.running = false;
|
||||
bool terminated = false;
|
||||
relay->context.post([&]() { terminated = true; }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/api/services/MarketDataRelay.client.pb.h"
|
||||
#include "spark/md/MDConsumer.h"
|
||||
#include "spark/md/relay/relay_producer.h"
|
||||
#include "spark/md/relay/relay_scheduler.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct RelayControl {
|
||||
RelayControl(MDConsumer *pconsumer, std::uint32_t interval)
|
||||
: context(), relay(context.locate<co2::MarketDataRelay>()),
|
||||
producer(false),
|
||||
client(relay, pconsumer, std::set<UserSymbol>(), producer),
|
||||
scheduler(context, interval, client) {
|
||||
scheduler.run();
|
||||
}
|
||||
|
||||
api::ServiceContext context;
|
||||
co2::MarketDataRelay relay;
|
||||
RelayProducer producer;
|
||||
RelayClient client;
|
||||
RelayScheduler scheduler;
|
||||
};
|
||||
|
||||
void add_relay_symbol(RelayControl *relay, const co2::SecurityChannel &chan);
|
||||
void set_relay_token(RelayControl *relay, const std::string &token);
|
||||
|
||||
/*
|
||||
* Extern api for c#
|
||||
*/
|
||||
extern "C" {
|
||||
BTS_EXPORT void relay_everything();
|
||||
BTS_EXPORT RelayControl *start_private_relay(
|
||||
MDConsumer *consumer, std::uint32_t interval);
|
||||
BTS_EXPORT void stop_relay(RelayControl *relay);
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,148 @@
|
||||
#include "spark/md/PriceSize.h"
|
||||
#ifndef NO_CPP0X
|
||||
|
||||
#include "spark/md/MDProducer.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/md/relay/i_relay_writer.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
#include "system/logging/logging.h"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
|
||||
#include <array>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
using bts::system::protobufs::SystemConfig;
|
||||
|
||||
class RelayProducer : public IRelayWriter {
|
||||
bool _shared;
|
||||
std::optional<MDProducer> _producer;
|
||||
std::unordered_map<security_key, MDProducerHandle> _handles;
|
||||
|
||||
PriceSize trade_pricesize(const co2::TradeMessage &trade) {
|
||||
return trade.size() > 0
|
||||
? PriceSize(
|
||||
{trade.mantissa(), (int8_t)trade.exponent()},
|
||||
trade.size())
|
||||
: NO_MARKET;
|
||||
}
|
||||
|
||||
IntPrice convert(const co2::PriceMessage &price) {
|
||||
return {price.mantissa(), (int8_t)price.exponent()};
|
||||
}
|
||||
|
||||
void record_update(
|
||||
MDProducerHandle &handle, const co2::ChannelUpdate &update) {
|
||||
utils::TimeStamp updated = utils::TimeStamp::now();
|
||||
bool snapshot = update.has_security();
|
||||
// If this is a snapshot an empty book() means "no market" rather than "no
|
||||
// change"
|
||||
if (update.has_direct() || update.has_implied() || snapshot) {
|
||||
std::array<PriceSize, COCONUT_MAX_DEPTH> bids, asks;
|
||||
std::array<PriceSize, COCONUT_MAX_IMPLIED_DEPTH> implied_bids,
|
||||
implied_asks;
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
bids[x] = PriceSize_from_proto_book(update.direct().bids(), x);
|
||||
asks[x] = PriceSize_from_proto_book(update.direct().asks(), x);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
implied_bids[x] =
|
||||
PriceSize_from_proto_book(update.implied().bids(), x);
|
||||
implied_asks[x] =
|
||||
PriceSize_from_proto_book(update.implied().asks(), x);
|
||||
}
|
||||
handle.update_books(updated, bids, asks, implied_bids, implied_asks);
|
||||
}
|
||||
if (update.has_misc()) {
|
||||
auto &misc = update.misc();
|
||||
handle.update_settlement(
|
||||
updated, convert(misc.settlement()),
|
||||
datetime::Date(misc.settlement_date()));
|
||||
handle.update_previous_settlement(
|
||||
updated, convert(misc.previous_settlement_price()),
|
||||
datetime::Date(misc.previous_settlement_date()));
|
||||
handle.update_opening(
|
||||
updated, misc.open_price(), datetime::Date(misc.open_date()));
|
||||
handle.update_closing(
|
||||
updated, misc.close_price(), datetime::Date(misc.close_date()));
|
||||
handle.update_session_high(updated, misc.session_high());
|
||||
handle.update_session_low(updated, misc.session_low());
|
||||
handle.update_session_high_bid(updated, misc.session_high_bid());
|
||||
handle.update_session_low_offer(updated, misc.session_low_offer());
|
||||
handle.update_fixing_price(updated, misc.fixing_price());
|
||||
}
|
||||
if (update.has_last_trade()) {
|
||||
handle.set_last_trade(
|
||||
updated, trade_pricesize(update.last_trade()),
|
||||
update.last_trade().time(), update.last_trade().total_volume(),
|
||||
update.last_trade().from_spread());
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
RelayProducer(bool shared) : _shared(shared), _handles() {}
|
||||
|
||||
MDProducer &ensure_producer() {
|
||||
if (!_producer) {
|
||||
// relay never wants to enable SecurityMapper. Securities should always
|
||||
// match the relay source.
|
||||
_producer.emplace(
|
||||
_shared ? MDProducerFlags::Shared : MDProducerFlags::None);
|
||||
}
|
||||
return *_producer;
|
||||
}
|
||||
|
||||
void write(const co2::MDReply &data, bool *phas_new_securities) override {
|
||||
auto &producer = ensure_producer();
|
||||
for (const auto &ch : data.channels()) {
|
||||
// Per-security data
|
||||
int added_security_count = 0;
|
||||
for (const auto &update : ch.updates()) {
|
||||
auto find_result = _handles.find(update.key());
|
||||
if (update.has_security() && find_result == _handles.end()) {
|
||||
if (phas_new_securities)
|
||||
*phas_new_securities = true;
|
||||
added_security_count++;
|
||||
MDProducer &producer = ensure_producer();
|
||||
with_security_like(update.security(), [&](FixedSecurity &fs) {
|
||||
convert_security(update.security(), fs, true);
|
||||
MDProducerHandle handle = producer.add_security(fs);
|
||||
_handles.insert(std::make_pair(handle.key(), handle));
|
||||
record_update(handle, update);
|
||||
});
|
||||
} else if (find_result != _handles.end()) {
|
||||
MDProducerHandle &handle = find_result->second;
|
||||
record_update(handle, update);
|
||||
}
|
||||
}
|
||||
// Heartbeat
|
||||
auto channel = producer.get_channel(
|
||||
ch.channel().symbol().c_str(), ch.channel().type(),
|
||||
ch.channel().exchange());
|
||||
channel.heartbeat();
|
||||
|
||||
// RFQ and TRADE LOG
|
||||
if (ch.trade_log_size() > 0 || ch.rfq_log_size() > 0) {
|
||||
if (ch.trade_log_size() > 0) {
|
||||
LOG(md, Diag, "Added {} trades", ch.trade_log_size());
|
||||
}
|
||||
for (const auto &trade : ch.trade_log()) {
|
||||
if (trade.key()) {
|
||||
channel.add_trade(trade);
|
||||
}
|
||||
}
|
||||
for (const auto &rfq : ch.rfq_log()) {
|
||||
channel.add_rfq(rfq);
|
||||
}
|
||||
}
|
||||
if (added_security_count > 0) {
|
||||
LOG(md, Diag, "Added {} {} - {}", added_security_count,
|
||||
ch.channel().symbol(), SecurityType_Name(ch.channel().type()));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
#endif
|
||||
+58
-15
@@ -1,43 +1,45 @@
|
||||
#ifndef NO_CPP0X
|
||||
|
||||
#include "RelayRecorder.h"
|
||||
#include "relay_recorder.h"
|
||||
#include "domain/security_criteria.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/utils/HTTPStream.h"
|
||||
#include "spark/utils/bts_chrono.h"
|
||||
#include "spark/utils/datetime.h"
|
||||
|
||||
#include "spark/config/protos/market_data.pb.h"
|
||||
#include "spark/md/SecurityIDRecorder.h"
|
||||
#include "spark/md/SymbolLoader.h"
|
||||
#include "spark/md/common.h"
|
||||
#include "spark/md/protos/co2.pb.h"
|
||||
#include "spark/utils/bts_chrono.h"
|
||||
#include "spark/md/relay/relay_producer.h"
|
||||
#include "spark/md/relay/relay_scheduler.h"
|
||||
#include "spark/md/relay/relay_service_context.h"
|
||||
#include "spark/utils/HTTPStream.h"
|
||||
#include "spark/utils/datetime.h"
|
||||
#include "system/logging/logging.h"
|
||||
#include "system/protobufs/config/system_config.pb.h"
|
||||
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <google/protobuf/text_format.h>
|
||||
#include <memory>
|
||||
#include <string.h>
|
||||
#include <thread>
|
||||
|
||||
using namespace std;
|
||||
using namespace bts::co2;
|
||||
|
||||
namespace bts {
|
||||
namespace md {
|
||||
namespace bts::md {
|
||||
|
||||
using bts::system::protobufs::SystemConfig;
|
||||
|
||||
const char *magic = "Co2";
|
||||
const uint32_t recorder_version = 3;
|
||||
|
||||
template <class T> void writebuf(ofstream &out, const T &pb) {
|
||||
template <class T>
|
||||
void writebuf(ofstream &out, const T &pb) {
|
||||
auto size = static_cast<std::uint32_t>(pb.ByteSizeLong());
|
||||
out.write(reinterpret_cast<char *>(&size), sizeof(size));
|
||||
bts_assert(pb.SerializeToOstream(&out));
|
||||
}
|
||||
|
||||
template <class T> bool readbuf(istream &in, T *result) {
|
||||
template <class T>
|
||||
bool readbuf(istream &in, T *result) {
|
||||
if (result) {
|
||||
uint32_t size;
|
||||
in.read(reinterpret_cast<char *>(&size), sizeof(size));
|
||||
@@ -242,7 +244,9 @@ void get_securities_from_replay(std::function<void(const api::Security &)> cb) {
|
||||
}
|
||||
}
|
||||
|
||||
shared_ptr<IRelayWriter> mkrelayproducer(bool shared);
|
||||
shared_ptr<IRelayWriter> mkrelayproducer(bool shared) {
|
||||
return make_shared<RelayProducer>(shared);
|
||||
}
|
||||
|
||||
/*this is the public one*/
|
||||
void replay_recording(
|
||||
@@ -336,6 +340,45 @@ void unprint_recording(const std::string &src, const std::string &dest) {
|
||||
out.flush();
|
||||
}
|
||||
|
||||
} // namespace md
|
||||
} // namespace bts
|
||||
void record_everything(std::string path, std::string filename) {
|
||||
auto options = config::get<RecordOptions>();
|
||||
if (filename.empty()) {
|
||||
ostringstream file;
|
||||
file << "marketdata"
|
||||
<< "-";
|
||||
int year, month, day, hour, minute, unused;
|
||||
datetime::ll_to_parts(
|
||||
datetime::ll_local_now(), year, month, day, hour, minute, unused,
|
||||
unused);
|
||||
file << year << setw(2) << setfill('0') << month << setw(2)
|
||||
<< setfill('0') << day << "-" << setw(2) << setfill('0') << hour
|
||||
<< setw(2) << setfill('0') << minute << ".coconut";
|
||||
filename = file.str();
|
||||
}
|
||||
|
||||
if (path.empty()) {
|
||||
path = os::app_data_path("record/").string();
|
||||
}
|
||||
|
||||
auto naggle_ms = config::get<RelayOptions>().naggle_ms();
|
||||
RelayRecorder recorder(path, filename, naggle_ms);
|
||||
|
||||
api::ServiceContext ctx = elevated_relay_context();
|
||||
auto relay = ctx.locate<MarketDataRelay>();
|
||||
|
||||
const auto exclude =
|
||||
options.record_sim()
|
||||
? domain::SecurityCriteria::empty()
|
||||
: domain::SecurityCriteria::create(
|
||||
{}, {domain::protobufs::SECURITY_TYPE_SYNTHETIC});
|
||||
std::set<UserSymbol> system_symbols = SymbolLoader::load({}, exclude);
|
||||
|
||||
RelayClient client(relay, nullptr, system_symbols, recorder);
|
||||
RelayScheduler scheduler(ctx, naggle_ms, client);
|
||||
scheduler.run();
|
||||
|
||||
utils::Dispatcher::current().run();
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
#endif
|
||||
+4
-4
@@ -1,9 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "RelayClient.h"
|
||||
#include "spark/utils/bts_no_copy.h"
|
||||
#include "spark/md/relay/i_relay_writer.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace bts {
|
||||
@@ -14,7 +14,7 @@ class RelayRecorder : public IRelayWriter {
|
||||
RelayRecorder(
|
||||
const std::string &base_path,
|
||||
const std::string &filename,
|
||||
uint32_t naggle);
|
||||
std::uint32_t naggle);
|
||||
~RelayRecorder();
|
||||
virtual void write(const co2::MDReply &, bool *) override;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "system/threading/dispatcher.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
inline utils::Dispatcher &scan_securities_thread() {
|
||||
return utils::Dispatcher::background();
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/md/relay/relay_client.h"
|
||||
#include "spark/utils/TimeStamp.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
struct RelayScheduler {
|
||||
std::uint32_t _interval;
|
||||
api::ServiceContext &_ctx;
|
||||
RelayClient &_client;
|
||||
bool running;
|
||||
double speed_factor;
|
||||
|
||||
RelayScheduler(
|
||||
api::ServiceContext &context, uint32_t interval, RelayClient &client)
|
||||
: _interval(interval), _ctx(context), _client(client), running(true),
|
||||
speed_factor(config::get<ReplayOptions>().speed()) {}
|
||||
|
||||
void run() {
|
||||
if (running) {
|
||||
utils::TimeStamp start = utils::TimeStamp::now();
|
||||
_client.request_md([=, this]() {
|
||||
std::int64_t elapsed_ms =
|
||||
(utils::TimeStamp::now() - start).milliseconds();
|
||||
int64_t delay = (_interval - elapsed_ms) / speed_factor;
|
||||
_ctx.post([=, this]() { run(); }, std::max(delay, (int64_t)0));
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/api/public/ServiceContext.h"
|
||||
#include "spark/utils/AuthToken.h"
|
||||
|
||||
namespace bts::md {
|
||||
|
||||
inline api::ServiceContext elevated_relay_context() {
|
||||
api::ServiceContext ctx;
|
||||
ctx.login(api::auth::generate_wheel_token());
|
||||
return ctx;
|
||||
}
|
||||
|
||||
} // namespace bts::md
|
||||
@@ -3,9 +3,10 @@
|
||||
#include "../SecurityCache.h"
|
||||
#include "../SettlementRecorder.h"
|
||||
#include "../coconut2.h"
|
||||
#include "../relay/QueryServer.h"
|
||||
#include "Co2TestInstrument.h"
|
||||
#include "spark/config/config.h"
|
||||
#include "spark/md/PriceSize.h"
|
||||
#include "spark/md/relay/query_server.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
#include "spark/utils/Dispatcher.h"
|
||||
#include "spark/utils/Shuffle.h"
|
||||
@@ -14,9 +15,9 @@
|
||||
#include "spark/utils/warn_ctrl.h"
|
||||
#include "system/os.h"
|
||||
|
||||
#include "md_test_utils.h"
|
||||
#include "spark/config/protos/market_data.pb.h"
|
||||
#include "spark/utils/Sqlite_utils.h"
|
||||
#include "md_test_utils.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <catch2/catch_all.hpp>
|
||||
@@ -46,10 +47,6 @@ MetricsContainer::~MetricsContainer() {}
|
||||
|
||||
int md_tests = 0;
|
||||
namespace md {
|
||||
// import this from RelayClient.cpp
|
||||
PriceSize book_at(
|
||||
const google::protobuf::RepeatedPtrField<co2::PriceSizeMessage> &side,
|
||||
int index);
|
||||
namespace test {
|
||||
|
||||
using namespace api;
|
||||
@@ -1402,8 +1399,12 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.has_direct());
|
||||
REQUIRE(update.direct().asks_size() > 0);
|
||||
REQUIRE(update.direct().bids_size() > 0);
|
||||
REQUIRE(book_at(update.direct().bids(), 0) == price35);
|
||||
REQUIRE(book_at(update.direct().asks(), 0) == price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), 0) ==
|
||||
price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), 0) ==
|
||||
price35);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1428,9 +1429,11 @@ struct Co2RelayTests {
|
||||
REQUIRE(reply.channels(1).updates().size() == 0);
|
||||
REQUIRE(reply.channels(0).updates(0).has_direct());
|
||||
REQUIRE(
|
||||
book_at(reply.channels(0).updates(0).direct().bids(), 0) == price5);
|
||||
PriceSize_from_proto_book(
|
||||
reply.channels(0).updates(0).direct().bids(), 0) == price5);
|
||||
REQUIRE(
|
||||
book_at(reply.channels(0).updates(0).direct().asks(), 0) == price5);
|
||||
PriceSize_from_proto_book(
|
||||
reply.channels(0).updates(0).direct().asks(), 0) == price5);
|
||||
|
||||
// NaN out all the prices - expect to get a full set of updates
|
||||
for (auto p : producers) {
|
||||
@@ -1451,8 +1454,12 @@ struct Co2RelayTests {
|
||||
// We need to have a book to signal that it was updated but it can
|
||||
// have no rows. This signifies an empty book and will be written
|
||||
// as such by the relay client.
|
||||
REQUIRE(book_at(update.direct().bids(), 0) == NO_MARKET);
|
||||
REQUIRE(book_at(update.direct().asks(), 0) == NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), 0) ==
|
||||
NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), 0) ==
|
||||
NO_MARKET);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1475,8 +1482,12 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.has_direct());
|
||||
REQUIRE(update.direct().bids_size() > 0);
|
||||
REQUIRE(update.direct().asks_size() > 0);
|
||||
REQUIRE(book_at(update.direct().bids(), 0) == price35);
|
||||
REQUIRE(book_at(update.direct().asks(), 0) == price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), 0) ==
|
||||
price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), 0) ==
|
||||
price35);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1497,8 +1508,12 @@ struct Co2RelayTests {
|
||||
for (auto &channel : reply.channels()) {
|
||||
for (auto &update : channel.updates()) {
|
||||
REQUIRE(update.has_direct());
|
||||
REQUIRE(book_at(update.direct().bids(), 0) == NO_MARKET);
|
||||
REQUIRE(book_at(update.direct().asks(), 0) == price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), 0) ==
|
||||
NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), 0) ==
|
||||
price35);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1565,12 +1580,20 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.implied().bids_size() == COCONUT_MAX_IMPLIED_DEPTH);
|
||||
REQUIRE(update.implied().asks_size() == COCONUT_MAX_IMPLIED_DEPTH);
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.direct().bids(), x) == price35);
|
||||
REQUIRE(book_at(update.direct().asks(), x) == price5);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), x) ==
|
||||
price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), x) ==
|
||||
price5);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.implied().bids(), x) == price35);
|
||||
REQUIRE(book_at(update.implied().asks(), x) == price5);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().bids(), x) ==
|
||||
price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().asks(), x) ==
|
||||
price5);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1592,12 +1615,20 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.implied().bids_size() == 0);
|
||||
REQUIRE(update.implied().asks_size() == 0);
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.direct().bids(), x) == price35);
|
||||
REQUIRE(book_at(update.direct().asks(), x) == price5);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), x) ==
|
||||
price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), x) ==
|
||||
price5);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.implied().bids(), x) == NO_MARKET);
|
||||
REQUIRE(book_at(update.implied().asks(), x) == NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().bids(), x) ==
|
||||
NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().asks(), x) ==
|
||||
NO_MARKET);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1619,12 +1650,20 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.implied().bids_size() == 0);
|
||||
REQUIRE(update.implied().asks_size() == 0);
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.direct().bids(), x) == NO_MARKET);
|
||||
REQUIRE(book_at(update.direct().asks(), x) == NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), x) ==
|
||||
NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), x) ==
|
||||
NO_MARKET);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.implied().bids(), x) == NO_MARKET);
|
||||
REQUIRE(book_at(update.implied().asks(), x) == NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().bids(), x) ==
|
||||
NO_MARKET);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().asks(), x) ==
|
||||
NO_MARKET);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1647,12 +1686,20 @@ struct Co2RelayTests {
|
||||
REQUIRE(update.implied().bids_size() == COCONUT_MAX_IMPLIED_DEPTH);
|
||||
REQUIRE(update.implied().asks_size() == COCONUT_MAX_IMPLIED_DEPTH);
|
||||
for (size_t x = 0; x < COCONUT_MAX_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.direct().bids(), x) == price5);
|
||||
REQUIRE(book_at(update.direct().asks(), x) == price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().bids(), x) ==
|
||||
price5);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.direct().asks(), x) ==
|
||||
price35);
|
||||
}
|
||||
for (size_t x = 0; x < COCONUT_MAX_IMPLIED_DEPTH; ++x) {
|
||||
REQUIRE(book_at(update.implied().bids(), x) == price5);
|
||||
REQUIRE(book_at(update.implied().asks(), x) == price35);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().bids(), x) ==
|
||||
price5);
|
||||
REQUIRE(
|
||||
PriceSize_from_proto_book(update.implied().asks(), x) ==
|
||||
price35);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "spark/md/MDConsumer.h"
|
||||
#include "spark/md/MDConsumerHandle.h"
|
||||
#include "spark/md/cme/MDP3Utils.h"
|
||||
#include "spark/md/md_consumer_channel.h"
|
||||
#include "spark/mercury/actors/Actor.h"
|
||||
#include "spark/mercury/actors/IPollableActor.h"
|
||||
#include "spark/metrics/metrics.h"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "AlgoTestDriver.h"
|
||||
#include "domain/protobufs/trading_status.pb.h"
|
||||
#include "spark/api/services/OrderService.pb.h"
|
||||
#include "spark/md/relay/RelayRecorder.h"
|
||||
#include "spark/md/relay/relay_recorder.h"
|
||||
#include "spark/orderman/calculations/ITheoCalculator.h"
|
||||
#include "spark/orderman/orderman_utils/Book.h"
|
||||
#include "system/logging/logging.h"
|
||||
|
||||
Reference in new issue
Block a user