SPARK-2202 MBOProcessor producer side

This commit is contained in:
Eric Harding committed 2019-03-29 11:08:37 -04:00
1 parent e9da338402
commit bad5bc3097
12 files changed
+302 -31

No files matched your search

+2 -1
View File
@@ -113,7 +113,8 @@ message CMEOptions
optional bool load_security_db = 33 [default = true];
reserved 34;
// optional BookType book_type = 34 [default = BOOKTYPE_CONSOLIDATED];
// optional BookType book_type = 34 [default = BOOKTYPE_CONSOLIDATED];
optional bool maintain_mbo = 35 [default = true];
}
optional string onixs_license = 1 [default = "{default}"];
+81
View File
@@ -0,0 +1,81 @@
#include "MBOProcessor.h"
#include "lib/utils/Dispatcher.h"
#include "lib/utils/ConcurrentPool.h"
#include <map>
#include <functional>
#include <tbb/concurrent_hash_map.h>
namespace bts {
namespace md {
struct SecurityKeyHashCompare {
static size_t hash(const SecurityKey& k) {
return k.value();
}
static bool equal(const SecurityKey& a, const SecurityKey& b) {
return a.value() == b.value();
}
};
typedef tbb::concurrent_hash_map<SecurityKey, snapshot::MBOSnapshot*, SecurityKeyHashCompare> MapType;
struct MBOProcessorImpl {
utils::ConcurrentPool<snapshot::MBOSnapshot> pool;
MapType snapshots;
MBOProcessorImpl() : pool(2048,512), snapshots() {}
};
//
// Processor
MBOProcessor::MBOProcessor() :
_me(std::make_shared<MBOProcessorImpl>()),
_producer(_me),
_consumer(_me)
{}
MBOWriter& MBOProcessor::writer() { return _producer;}
MBOReader& MBOProcessor::reader() { return _consumer; }
//
// Writer
MBOWriter::MBOWriter(std::shared_ptr<MBOProcessorImpl>& me): _me(me) { }
MBOWriter::~MBOWriter() { }
snapshot::MBOSnapshot* MBOWriter::allocate_snapshot() {
return _me->pool.allocate();
}
void MBOWriter::publish_snapshot(SecurityKey key, snapshot::MBOSnapshot* snapshot) {
bts_assert(snapshot != nullptr);
MapType::accessor accessor;
_me->snapshots.insert(accessor, key);
std::swap(accessor->second, snapshot);
if (snapshot != nullptr) {
// Note: relase() should happen inside accessor lifetime
_me->pool.release(&snapshot);
}
}
//
// Reader
MBOReader::MBOReader(std::shared_ptr<MBOProcessorImpl>& me): _me(me) { }
MBOReader::~MBOReader() { }
snapshot::MBOSnapshot* MBOReader::acquire_snapshot(SecurityKey key) {
// get a result eagerly so we don't have to do it while accessor has the entry locked
auto result = _me->pool.allocate();
MapType::const_accessor accessor;
if (_me->snapshots.find(accessor, key) && accessor->second != nullptr) {
result->copy_from(*accessor->second);
}
else {
release_snapshot(&result);
}
return result;
}
void MBOReader::release_snapshot(snapshot::MBOSnapshot** s) {
_me->pool.release(s);
}
}}
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include "lib/domain_model/SecurityKey.h"
#include "lib/domain_model/Security.h"
#include "lib/utils/TimeStamp.h"
#include "lib/utils/ValueWrapper.h"
#include "IntPrice.h"
#include <vector>
#include <memory>
namespace bts {
namespace md {
using OrderKey = utils::ValueWrapper<struct OrderKeyTag,uint64_t>;
namespace snapshot {
struct SnapshotOrder {
OrderKey id;
int32_t size;
};
struct MBOSnapshot {
MBOSnapshot() = default;
MBOSnapshot(const MBOSnapshot&) = delete;
MBOSnapshot(MBOSnapshot&& other) = delete;
utils::TimeStamp updated;
std::vector<SnapshotOrder> bids;
std::vector<SnapshotOrder> asks;
void copy_from(const MBOSnapshot& src) {
bids = src.bids;
asks = src.asks;
updated = src.updated;
}
void reset() {
updated = utils::TimeStamp();
bids.clear();
asks.clear();
}
};
}
struct MBOProcessorImpl;
class MBOProcessor;
class MBOWriter {
std::shared_ptr<MBOProcessorImpl> _me;
friend class MBOProcessor;
MBOWriter(std::shared_ptr<MBOProcessorImpl>&);
~MBOWriter();
public:
snapshot::MBOSnapshot* allocate_snapshot();
void publish_snapshot(SecurityKey key, snapshot::MBOSnapshot* snapshot);
};
class MBOReader {
std::shared_ptr<MBOProcessorImpl> _me;
friend class MBOProcessor;
MBOReader(std::shared_ptr<MBOProcessorImpl>&);
~MBOReader();
public:
snapshot::MBOSnapshot* acquire_snapshot(SecurityKey key);
void release_snapshot(snapshot::MBOSnapshot**);
};
class MBOProcessor {
std::shared_ptr<MBOProcessorImpl> _me;
MBOWriter _producer;
MBOReader _consumer;
public:
MBOProcessor();
MBOWriter& writer();
MBOReader& reader();
};
}}
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include <tbb/concurrent_queue.h>
#include <tbb/concurrent_vector.h>
#include <atomic>
namespace bts {
namespace utils {
template <class T>
class ConcurrentPool {
tbb::concurrent_vector<std::unique_ptr<T[]>> _all;
tbb::concurrent_queue<T*> _free;
size_t _grow_size;
std::atomic<size_t> _outstanding;
public:
ConcurrentPool(size_t initial_size=256, size_t grow_size=32):
_all(), _free(), _grow_size(grow_size), _outstanding(0) {
reserve(initial_size);
}
~ConcurrentPool() { }
T* allocate() {
T* result = nullptr;
++_outstanding;
if (_free.try_pop(result)) {
return result;
}
else {
reserve(_grow_size);
return allocate();
}
}
void reserve(size_t count) {
std::unique_ptr<T[]> buffer {new T[count]};
for (size_t x = 0; x < count; ++x) {
T* temp = &buffer[x];
release(&temp);
}
_all.push_back(std::move(buffer));
}
void release(T** item) {
if (*item) {
(*item)->reset();
_free.push(*item);
*item = nullptr;
--_outstanding;
}
}
};
}} //namespace
+5 -2
View File
@@ -14,6 +14,7 @@
#include "lib/md/MDClient.h"
#include "lib/md/SyntheticSecurityService.h"
#include "lib/md/relay/QueryServer.h"
#include "lib/md/MBOProcessor.h"
#include "lib/metrics/metrics.h"
#include "lib/metrics/system_metrics.h"
#include "lib/orderman/order_factory/DynamicOrderRegistry.h"
@@ -57,10 +58,12 @@ int Run::execute(std::vector<std::string> const &) {
persistence::PersistenceServiceServer settings_saver(sc, "settings");
user::AuthServiceServer login_server(sc);
md::run_market_datapublishers();
md::MBOProcessor mbo;
md::run_market_datapublishers(&mbo.writer());
api::synthetic::SyntheticSecurityService synthetic_service(sc);
md::MDClient mdclient(&utils::Dispatcher::background(), &synthetic_service);
md::MDClient mdclient(&utils::Dispatcher::background(), &synthetic_service /*, mbo*/);
md::QueryServerPtr md_query_server(
+1 -1
View File
@@ -37,7 +37,7 @@ int Web::execute(const std::vector<std::string>& args) {
user::AuthServiceServer login_server(sc);
if (std::find(args.begin(), args.end(), "-md") != args.end()) {
md::run_market_datapublishers();
md::run_market_datapublishers(nullptr);
}
api::synthetic::SyntheticSecurityService synthetic_service(sc);
@@ -15,7 +15,7 @@ namespace md {
MDP3Listener::MDP3Listener(
CMESecurityIndex& index,
MDProducer& producer,
// co2::SettlementRecorder& ,
MBOWriter* mbo,
const std::vector<MDProducerChannel> channels) :
_index(index),
_producer(producer),
@@ -27,7 +27,8 @@ MDP3Listener::MDP3Listener(
_symbol_filter(),
_channels(channels),
_concurrency_monitor(0),
_book_updates()
_book_updates(),
_mbo(mbo)
{
_book_updates.reserve(32);
}
@@ -109,7 +110,7 @@ void MDP3Listener::onEndOfPacket(onixs::Handler&, const onixs::PacketArgs&) {
}
//
// Security discovery
// Book updates
void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, const onixs::DirectBook& book) {
onBookUpdate<COCONUT_MAX_DEPTH>(sec, book, book_type_direct);
@@ -119,6 +120,24 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con
onBookUpdate<COCONUT_MAX_IMPLIED_DEPTH>(sec, book, book_type_implied);
}
void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, const onixs::MboBook& book) {
if (_mbo) {
auto data = _index.get_security(sec.id());
if (data == nullptr) return;
auto key = data->handle.key();
if (key == invalid_security_key) return;
auto* snapshot = _mbo->allocate_snapshot();
// copy from onixs book
for (const auto& bid : book.bids()) {
snapshot->bids.push_back({ OrderKey(bid.id()), bid.quantity() });
}
for (const auto& ask : book.offers()) {
snapshot->asks.push_back({ OrderKey(ask.id()), ask.quantity() });
}
_mbo->publish_snapshot(SecurityKey(key), snapshot);
}
}
//
// Trades
@@ -2,6 +2,7 @@
#include "lib/utils/bts_no_copy.h"
#include "lib/md/coconut2.h"
#include "lib/md/MBOProcessor.h"
#include "CMESecurityIndex.h"
#include "lib/tracing/bts_trace.h"
@@ -13,11 +14,11 @@
#include <atomic>
#include <array>
#include <utility>
#include <optional>
namespace bts {
namespace md {
class MDP3Listener :
public onixs::HandlerListener,
public onixs::MarketDataListener,
@@ -31,7 +32,7 @@ class MDP3Listener :
public:
MDP3Listener(CMESecurityIndex& index,
MDProducer&,
// co2::SettlementRecorder&,
MBOWriter* mbo,
const std::vector<MDProducerChannel>);
virtual ~MDP3Listener();
@@ -54,6 +55,25 @@ public:
void onPacket(onixs::Handler&, const onixs::PacketArgs&) override;
void onEndOfPacket(onixs::Handler&, const onixs::PacketArgs&) override;
//
// Handle MBO incremental updates directly
// void onMessage(onixs::Handler&, const onixs::IncrementalRefreshBook32Args& args) override {
// for(const auto& a : args.message().orderIdEntries()) {
// int qty;
// a.displayQty(qty);
// uint8_t ref;
// a.referenceId(ref);
// const auto& ref_entry = args.message().entries()[(size_t)ref];
// std::cout
// << a.orderId()
// << qty
// << ref_entry.securityId()
// ;
// }
// };
// void onMessage(onixs::Handler&, const onixs::IncrementalRefreshBook46Args&) override {};
//
// Security discovery
template <typename InstrumentDefinitionFuture>
@@ -74,9 +94,9 @@ public:
//
// Book
// void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::MboBook&) override;
void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::DirectBook&) override;
void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::ImpliedBook&) override;
void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::MboBook&) override;
// void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::ConsolidatedBook&) override;
template <size_t MAX_DEPTH,class TBook>
@@ -199,6 +219,7 @@ private:
std::pair<std::array<PriceSize, COCONUT_MAX_DEPTH>, std::array<PriceSize,COCONUT_MAX_IMPLIED_DEPTH>> asks;
};
std::vector<BookData> _book_updates;
MBOWriter* _mbo;
};
//////////////////////////////////////////
@@ -1,6 +1,7 @@
#include "MDP3Main.h"
#include "lib/md/cme/MDP3Utils.h"
#include "lib/md/MBOProcessor.h"
#include "lib/config/config.h"
#include "lib/md/coconut2.h"
#include "lib/os/os.h"
@@ -130,14 +131,14 @@ onixs::SessionSettings session_settings_for_channel(const string& channel_id) {
return settings;
}
void MDP3Main::run(std::vector<UserSymbol>& symbols) {
void MDP3Main::run(std::vector<UserSymbol>& symbols, MBOWriter* mbo) {
await_cme_config();
initialize();
const auto& channels = parse_channels(symbols);
_engines = create_feed_engines(channels);
for (const auto& channel : channels) {
unique_ptr<onixs::Handler> phandler = prepare_handler(channel.id);
_listeners.push_back(prepare_listener(*phandler, channel));
unique_ptr<onixs::Handler> phandler = prepare_handler(channel.id, mbo);
_listeners.push_back(prepare_listener(*phandler, channel, mbo));
_handlers.insert(std::make_pair(channel.id, move(phandler)));
std::stringstream symstr;
for (const auto& sym : channel.symbols) { symstr << sym.symbol() << "-" << SecurityType_Name(sym.type()) << " "; }
@@ -196,7 +197,7 @@ void MDP3Main::initialize() {
// //
// Initialize HandlerSettings and allocate the channel Handler
unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id, MBOWriter* mbo) {
const auto& pub_options = config::get<PublisherOptions>();
const auto& options = channel_settings_for(channel_id);
LOG(md,Info,"Loaded channel options for channel {}:\n{}",channel_id ,options.DebugString());
@@ -209,6 +210,9 @@ unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
settings.bookManagement().directBooks().maintain(true);
settings.bookManagement().impliedBooks().maintain(true);
settings.bookManagement().consolidatedBooks().maintain(false);
if (options.maintain_mbo() && mbo != nullptr) {
settings.bookManagement().mboBooks().maintain(true);
}
// 10k default is *far* too low
settings.recoveryQueueMaxSize(options.recovery_queue_size());
@@ -331,14 +335,14 @@ unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
//
// Create a listener for this channel and register callbacks
unique_ptr<MDP3Listener> MDP3Main::prepare_listener(onixs::Handler& handler, const CMEChannel& channel) {
unique_ptr<MDP3Listener> MDP3Main::prepare_listener(onixs::Handler& handler, const CMEChannel& channel, MBOWriter* mbo) {
// We need to get a handler to the producer channels so we can produce heartbeats
vector<MDProducerChannel> producer_channels;
for (auto& symbol : channel.symbols) {
producer_channels.push_back(_producer.get_channel(symbol.symbol().c_str(), symbol.type(), symbol.exchange()));
}
unique_ptr<MDP3Listener> listener(new MDP3Listener(_index, _producer, /*_settlement_recorder,*/ producer_channels));
unique_ptr<MDP3Listener> listener(new MDP3Listener(_index, _producer, mbo, producer_channels));
for (auto& symbol : channel.symbols) {
listener->add_filter_symbol(symbol.symbol());
}
@@ -15,6 +15,8 @@ namespace md {
// void run_onixs_mdp3_server(UserSymbol* sym, size_t symcount);
class MBOWriter;
struct CMEChannel;
/*
@@ -29,10 +31,10 @@ public:
MDP3Main();
~MDP3Main();
void run(std::vector<UserSymbol>&);
void run(std::vector<UserSymbol>&, MBOWriter*);
void initialize();
std::unique_ptr<onixs::Handler> prepare_handler(const std::string& channel);
std::unique_ptr<MDP3Listener> prepare_listener(onixs::Handler& handler, const CMEChannel& channel);
std::unique_ptr<MDP3Listener> prepare_listener(onixs::Handler& handler, const CMEChannel& channel, MBOWriter*);
private:
BTS_NO_COPY(MDP3Main);
+13 -12
View File
@@ -20,6 +20,7 @@
#include <iostream>
#include <thread>
#include <set>
#include <optional>
using namespace bts;
using namespace std;
@@ -65,12 +66,12 @@ void run_replay() {
replay_recording(file, naggle_ms, fallback_path);
}
void run_onixs() {
void run_onixs(MBOWriter* mbo) {
// get all glbx symbols
std::vector<UserSymbol> symbols;
get_system_md_symbols(api::VENUE_GLBX, api::SECURITYTYPE_UNSET, &symbols);
MDP3Main main;
main.run(symbols);
main.run(symbols, mbo);
}
void run_cleanup() {
@@ -78,15 +79,14 @@ void run_cleanup() {
}
std::thread* _md_thread;
void run_market_data_publishers_forever() {
os::set_thread_name("md publisher");
std::optional<std::thread> _md_thread;
void run_market_data_publishers_forever(MBOWriter* mbo) {
const auto& conf = config::get<MarketDataConfig>();
if (conf.use_replay()) {
run_replay();
}
else if (conf.use_onixs()) {
run_onixs();
run_onixs(mbo);
}
}
@@ -110,14 +110,15 @@ void boot_sleep() {
}
}
void run_market_datapublishers() {
bts_assert(_md_thread == nullptr);
void run_market_datapublishers(MBOWriter* mbo) {
bts_assert(_md_thread == std::nullopt);
run_cleanup();
if (!config::get<MarketDataConfig>().use_md()) return;
// start a thread for the md
_md_thread = new std::thread([]() {
run_market_data_publishers_forever();
});
_md_thread = std::optional(
threading::make_thread("md publisher", [mbo]() {
run_market_data_publishers_forever(mbo);
}));
if (config::get<MarketDataConfig>().use_sim()) {
threading::make_thread("ExchangeSim", []() { sim::start_exchange_sim(); })
@@ -327,7 +328,7 @@ void md_tool(std::vector<std::string> const &args) {
else if (cmd == "cleanup") run_cleanup();
else if (cmd == "dump") run_dump(vector<string>(args.begin()+1, args.end()));
else if (cmd == "replay") run_replay();
else if (cmd == "run") run_market_data_publishers_forever();
else if (cmd == "run") run_market_data_publishers_forever(nullptr);
else if (cmd == "relay") relay_everything();
else if (cmd == "test_relay") relay_everything();
else if (cmd == "dumpsecurity" || cmd == "dumpsecurities") dump_db(vector<string>(args.begin()+1, args.end()));
+3 -1
View File
@@ -5,7 +5,9 @@
namespace bts {
namespace md {
void run_market_datapublishers();
class MBOWriter;
void run_market_datapublishers(MBOWriter*);
void md_tool(std::vector<std::string> const& args);
}}