diff --git a/src/lib/config/protos/MarketData.proto b/src/lib/config/protos/MarketData.proto index c52377235..3efb46c77 100755 --- a/src/lib/config/protos/MarketData.proto +++ b/src/lib/config/protos/MarketData.proto @@ -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}"]; diff --git a/src/lib/md/MBOProcessor.cpp b/src/lib/md/MBOProcessor.cpp new file mode 100644 index 000000000..4366fb528 --- /dev/null +++ b/src/lib/md/MBOProcessor.cpp @@ -0,0 +1,81 @@ +#include "MBOProcessor.h" +#include "lib/utils/Dispatcher.h" +#include "lib/utils/ConcurrentPool.h" + +#include +#include + +#include + + +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 MapType; +struct MBOProcessorImpl { + utils::ConcurrentPool pool; + MapType snapshots; + MBOProcessorImpl() : pool(2048,512), snapshots() {} +}; + +// +// Processor + +MBOProcessor::MBOProcessor() : + _me(std::make_shared()), + _producer(_me), + _consumer(_me) +{} + +MBOWriter& MBOProcessor::writer() { return _producer;} +MBOReader& MBOProcessor::reader() { return _consumer; } + +// +// Writer +MBOWriter::MBOWriter(std::shared_ptr& 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& 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); +} + +}} diff --git a/src/lib/md/MBOProcessor.h b/src/lib/md/MBOProcessor.h new file mode 100644 index 000000000..854c47a6d --- /dev/null +++ b/src/lib/md/MBOProcessor.h @@ -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 +#include + +namespace bts { +namespace md { + +using OrderKey = utils::ValueWrapper; + +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 bids; + std::vector 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 _me; + friend class MBOProcessor; + MBOWriter(std::shared_ptr&); + ~MBOWriter(); + public: + + snapshot::MBOSnapshot* allocate_snapshot(); + + void publish_snapshot(SecurityKey key, snapshot::MBOSnapshot* snapshot); +}; + +class MBOReader { + std::shared_ptr _me; + friend class MBOProcessor; + MBOReader(std::shared_ptr&); + ~MBOReader(); + public: + snapshot::MBOSnapshot* acquire_snapshot(SecurityKey key); + void release_snapshot(snapshot::MBOSnapshot**); +}; + +class MBOProcessor { + std::shared_ptr _me; + MBOWriter _producer; + MBOReader _consumer; + +public: + MBOProcessor(); + MBOWriter& writer(); + MBOReader& reader(); +}; + + +}} diff --git a/src/lib/utils/ConcurrentPool.h b/src/lib/utils/ConcurrentPool.h new file mode 100644 index 000000000..91ad99095 --- /dev/null +++ b/src/lib/utils/ConcurrentPool.h @@ -0,0 +1,55 @@ +#pragma once +#include +#include +#include + +namespace bts { +namespace utils { + +template +class ConcurrentPool { + tbb::concurrent_vector> _all; + tbb::concurrent_queue _free; + size_t _grow_size; + std::atomic _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 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 diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 2dc515483..3b788c4a2 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -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 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( diff --git a/src/server/sparkd/cmds/Web.cpp b/src/server/sparkd/cmds/Web.cpp index 029ae34bc..abbe80ed6 100644 --- a/src/server/sparkd/cmds/Web.cpp +++ b/src/server/sparkd/cmds/Web.cpp @@ -37,7 +37,7 @@ int Web::execute(const std::vector& 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); diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp index 6049e982b..f25450a6d 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp @@ -15,7 +15,7 @@ namespace md { MDP3Listener::MDP3Listener( CMESecurityIndex& index, MDProducer& producer, - // co2::SettlementRecorder& , + MBOWriter* mbo, const std::vector 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(sec, book, book_type_direct); @@ -119,6 +120,24 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con onBookUpdate(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 diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h index fc20add4c..c18a823d7 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.h @@ -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 #include #include +#include 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); 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 @@ -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 @@ -199,6 +219,7 @@ private: std::pair, std::array> asks; }; std::vector _book_updates; + MBOWriter* _mbo; }; ////////////////////////////////////////// diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp index 7c0db2832..c711993ac 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.cpp @@ -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& symbols) { +void MDP3Main::run(std::vector& 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 phandler = prepare_handler(channel.id); - _listeners.push_back(prepare_listener(*phandler, channel)); + unique_ptr 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 MDP3Main::prepare_handler(const string& channel_id) { +unique_ptr MDP3Main::prepare_handler(const string& channel_id, MBOWriter* mbo) { const auto& pub_options = config::get(); 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 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 MDP3Main::prepare_handler(const string& channel_id) { // // Create a listener for this channel and register callbacks -unique_ptr MDP3Main::prepare_listener(onixs::Handler& handler, const CMEChannel& channel) { +unique_ptr 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 producer_channels; for (auto& symbol : channel.symbols) { producer_channels.push_back(_producer.get_channel(symbol.symbol().c_str(), symbol.type(), symbol.exchange())); } - unique_ptr listener(new MDP3Listener(_index, _producer, /*_settlement_recorder,*/ producer_channels)); + unique_ptr listener(new MDP3Listener(_index, _producer, mbo, producer_channels)); for (auto& symbol : channel.symbols) { listener->add_filter_symbol(symbol.symbol()); } diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h index 4eb1fbf62..eb321087f 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h @@ -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&); + void run(std::vector&, MBOWriter*); void initialize(); std::unique_ptr prepare_handler(const std::string& channel); - std::unique_ptr prepare_listener(onixs::Handler& handler, const CMEChannel& channel); + std::unique_ptr prepare_listener(onixs::Handler& handler, const CMEChannel& channel, MBOWriter*); private: BTS_NO_COPY(MDP3Main); diff --git a/src/server/sparkd/md/run_md.cpp b/src/server/sparkd/md/run_md.cpp index 56e2c2762..bf216d7ec 100644 --- a/src/server/sparkd/md/run_md.cpp +++ b/src/server/sparkd/md/run_md.cpp @@ -20,6 +20,7 @@ #include #include #include +#include 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 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 _md_thread; +void run_market_data_publishers_forever(MBOWriter* mbo) { const auto& conf = config::get(); 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().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().use_sim()) { threading::make_thread("ExchangeSim", []() { sim::start_exchange_sim(); }) @@ -327,7 +328,7 @@ void md_tool(std::vector const &args) { else if (cmd == "cleanup") run_cleanup(); else if (cmd == "dump") run_dump(vector(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(args.begin()+1, args.end())); diff --git a/src/server/sparkd/md/run_md.h b/src/server/sparkd/md/run_md.h index 587a6e0c1..dc771b0bf 100644 --- a/src/server/sparkd/md/run_md.h +++ b/src/server/sparkd/md/run_md.h @@ -5,7 +5,9 @@ namespace bts { namespace md { -void run_market_datapublishers(); +class MBOWriter; + +void run_market_datapublishers(MBOWriter*); void md_tool(std::vector const& args); }}