diff --git a/CMakeLists.txt b/CMakeLists.txt index 14e71551b..0e276bc2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,6 +116,7 @@ else() if (BUILD_SPARKD) add_subdirectory(src/lib_binance_execution) add_subdirectory(src/lib_okx_execution) + add_subdirectory(src/lib_python_md) add_subdirectory(src/app_sparkd) add_subdirectory(src/data_files) endif() diff --git a/CMakePresets.json b/CMakePresets.json index 008626d8a..bbb15e819 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -62,6 +62,7 @@ "CMAKE_CXX_STANDARD": "20", "CMAKE_INSTALL_RPATH": ".", "CMAKE_INSTALL_PREFIX": "${sourceDir}/install/${presetName}", + "CMAKE_PREFIX_PATH": "${sourceDir}/cmake/;${sourceDir}/.venv/lib/python3.10/site-packages/pybind11/share/cmake/pybind11", "CMAKE_EXE_LINKER_FLAGS": "-Wno-undef", "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/vcpkg/scripts/buildsystems/vcpkg.cmake", "DATABENTO_USE_EXTERNAL_JSON": { diff --git a/src/app_sparkd/CMakeLists.txt b/src/app_sparkd/CMakeLists.txt index 4f386e678..5363af3b0 100644 --- a/src/app_sparkd/CMakeLists.txt +++ b/src/app_sparkd/CMakeLists.txt @@ -111,11 +111,35 @@ set_target_properties( INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" ) +# Python interop (for python md providers) +add_dependencies(${PROJECT_NAME} + python_md + python_md_module + python_md_providers + copy_python_md_providers +) +include(${CMAKE_SOURCE_DIR}/cmake/SymLink.cmake) + +sym_link_local_lib(python_md) +sym_link_file( + SOURCE ${CMAKE_BINARY_DIR}/src/lib_python_md/python_md_module.cpython-310-x86_64-linux-gnu.so + DEST ${CMAKE_CURRENT_BINARY_DIR}/python_md_module.cpython-310-x86_64-linux-gnu.so + INSTALL_DEST ${CMAKE_INSTALL_BINDIR}/ +) +get_target_property(providers python_md_providers INTERFACE_PYTHON_SCRIPTS_DIR) +sym_link_dir( + TARGET_NAME link_python_md_providers + SOURCE ${providers} + DEST ${CMAKE_CURRENT_BINARY_DIR}/python_md_providers +) + target_link_libraries( sparkd spark binance_execution okx_execution + python_md + python_md_module databento::databento ${emumba-deribit-connector-library_LIBRARIES} tbb diff --git a/src/app_sparkd/sparkd/md/MarketDataGateway.cpp b/src/app_sparkd/sparkd/md/MarketDataGateway.cpp index 5342b49e4..4dff382af 100644 --- a/src/app_sparkd/sparkd/md/MarketDataGateway.cpp +++ b/src/app_sparkd/sparkd/md/MarketDataGateway.cpp @@ -19,6 +19,7 @@ #include "spark/utils/bts_fatal.h" #include "spark/utils/stopwatch.h" #include "sparkd/md/OnixsMarketDataProvider.h" +#include "sparkd/md/PyMarketDataProvider.h" #include "sparkd/md/ReplayMarketDataProvider.h" #include "sparkd/md/ccapi/CCApiMarketDataProvider.h" #include "sparkd/md/databento/DatabentoMarketDataProvider.h" @@ -78,6 +79,8 @@ struct MarketDataGateway::PImpl { this->config, this->sec_id_store)); providers.push_back(std::make_unique( this->config, this->sec_id_store)); + providers.push_back(std::make_unique( + this->config, this->sec_id_store)); providers.push_back(std::make_unique( this->config, this->sec_id_store)); } diff --git a/src/app_sparkd/sparkd/md/PyMarketDataProvider.cpp b/src/app_sparkd/sparkd/md/PyMarketDataProvider.cpp new file mode 100644 index 000000000..7169137e8 --- /dev/null +++ b/src/app_sparkd/sparkd/md/PyMarketDataProvider.cpp @@ -0,0 +1,53 @@ +#include "PyMarketDataProvider.h" +#include "spark/api/md/MarketDataConfig.pb.h" +#include "spark/md/IMarketDataSource.h" +#include "spark/persistence/IDGenerator.h" +#include "spark/utils/bts_assert.h" +#include "sparkd/md/PyMarketDataSubscription.h" + +namespace bts::md { + +using bts::api::domain::Venue; +using bts::api::md::MarketDataConfig; +using bts::persistence::IDGenerator; +using std::pair; +using std::shared_ptr; +using std::string; +using std::vector; +using Path = boost::filesystem::path; + +struct PyMarketDataProvider::PImpl { + MarketDataConfig config; + shared_ptr sec_id_store; + vector> py_md_subs; + + PImpl(MarketDataConfig config, shared_ptr sec_id_store) + : config(std::move(config)), sec_id_store(std::move(sec_id_store)) {} +}; + +PyMarketDataProvider::PyMarketDataProvider( + MarketDataConfig config, shared_ptr sec_id_store) + : me_(std::make_unique(std::move(config), std::move(sec_id_store))) { +} + +PyMarketDataProvider::~PyMarketDataProvider() = default; + +vector>> +PyMarketDataProvider::get_sources() { + vector>> rv; + for (const auto &py_plugin : me_->config.python_md_providers()) { + try { + auto source = std::make_shared( + py_plugin, me_->sec_id_store.get()); + me_->py_md_subs.push_back(source); + rv.emplace_back(py_plugin.venue(), std::move(source)); + } catch (const std::exception &ex) { + bts_assert_msgf( + false, "PyMarketDataSubscription threw: {}", + std::string{ex.what()}); + } + } + return rv; +} + +} // namespace bts::md diff --git a/src/app_sparkd/sparkd/md/PyMarketDataProvider.h b/src/app_sparkd/sparkd/md/PyMarketDataProvider.h new file mode 100644 index 000000000..245abc126 --- /dev/null +++ b/src/app_sparkd/sparkd/md/PyMarketDataProvider.h @@ -0,0 +1,28 @@ +#pragma once + +#include "spark/api/domain/Venue.pb.h" +#include "spark/api/md/MarketDataConfig.pb.h" +#include "spark/md/IMarketDataProvider.h" +#include "spark/persistence/IDGenerator.h" + +#include + +namespace bts::md { + +class PyMarketDataProvider : public IMarketDataProvider { + public: + explicit PyMarketDataProvider( + api::md::MarketDataConfig config, + std::shared_ptr sec_id_store); + ~PyMarketDataProvider(); + + std::vector< + std::pair>> + get_sources() override; + + private: + struct PImpl; + std::unique_ptr me_; +}; + +} // namespace bts::md diff --git a/src/app_sparkd/sparkd/md/PyMarketDataSubscription.cpp b/src/app_sparkd/sparkd/md/PyMarketDataSubscription.cpp new file mode 100644 index 000000000..f881ce3a2 --- /dev/null +++ b/src/app_sparkd/sparkd/md/PyMarketDataSubscription.cpp @@ -0,0 +1,299 @@ +#include "PyMarketDataSubscription.h" +#include "python_md/md_sink.h" +#include "python_md/py_book.h" +#include "python_md/py_contract_specification.h" +#include "python_md/py_md_executor.h" +#include "python_md/py_security.h" +#include "python_md/py_security_list.h" +#include "python_md/py_trade.h" +#include "spark/api/domain/CallPut.pb.h" +#include "spark/api/domain/SecurityType.h" +#include "spark/api/domain/Venue.h" +#include "spark/api/md/PyMarketDataProviderConfig.pb.h" +#include "spark/core/TimeStamp.h" +#include "spark/domain/AggressorSide.h" +#include "spark/domain/FutureSecurity.h" +#include "spark/domain/Security.h" +#include "spark/domain/SecurityID.h" +#include "spark/domain/SpotSecurity.h" +#include "spark/domain/TradeRecord.h" +#include "spark/io/json_formatter.h" +#include "spark/logging/logging.h" +#include "spark/md/IMarketDataListener.h" +#include "spark/os/os.h" +#include "spark/persistence/IDGenerator.h" +#include "spark/utils/bts_assert.h" + +#include +#include +#include +#include +#include +#include + +namespace bts::md { + +#define AGGRESSOR_SIDE(x) bts::domain::AGGRESSOR_SIDE_##x + +using bts::api::domain::CallPut; +using bts::api::domain::SecurityType; +using bts::api::domain::Venue; +using bts::api::md::PyMarketDataProviderConfig; +using bts::core::TimeStamp; +using bts::domain::AggressorSide; +using bts::domain::Book; +using bts::domain::FutureSecurity; +using bts::domain::OptionSecurity; +using bts::domain::Price; +using bts::domain::Security; +using bts::domain::SecurityID; +using bts::domain::SpotSecurity; +using bts::domain::TradeRecord; +using bts::io::json_formatter; +using bts::md::py_interop::PyBook; +using bts::md::py_interop::PyBookList; +using bts::md::py_interop::PyBookSide; +using bts::md::py_interop::PyMdExecutor; +using bts::md::py_interop::PySecurity; +using bts::md::py_interop::PySecurityList; +using bts::md::py_interop::PyTrade; +using bts::md::py_interop::PyTradeList; +using bts::persistence::IDGenerator; +using std::optional; +using std::shared_ptr; +using std::string; +using std::vector; + +using Path = boost::filesystem::path; + +struct TradeTuple { + PyTrade py_trade; + TradeRecord trade; + Venue venue; +}; + +struct PyMarketDataSubscription::PImpl : private py_interop::MdSink { + PImpl(PyMarketDataProviderConfig config, IDGenerator *sec_id_store) + : config(std::move(config)), py_md_exec_( + this->config.provider_type(), + {this->config.module_path().begin(), + this->config.module_path().end()}, + this), + sec_id_store_(sec_id_store) {} + + void start(shared_ptr listener) { + bts_assert(listener != nullptr); + this->listener_ = std::move(listener); + LOG(md, Info, "PyMarketDataSubscription::start t_id:{} t_name:{}", + os::get_thread_id(), os::get_thread_name()); + py_md_exec_.start(); + } + + void stop() { py_md_exec_.stop(); } + + private: + PyMarketDataProviderConfig config; + PyMdExecutor py_md_exec_; + shared_ptr listener_; + + shared_ptr sec_id_store_; + // The main store for securities. + vector securities_; + vector security_ptrs_; + Book book_; + // Since the python md provider isn't tethered to a single venue, we + // must know the venue for each individual trade. + vector trades_; + vector trade_ptrs_; + + void on_securities(const PySecurityList &py_securities) override { + LOG(md, Info, R"([py_md_secs.json]{{ "secs": {}, "ts": {}}})", + json_formatter(py_securities.items()), TimeStamp::now_ns()); + // `securities_` and `security_ptrs_` should already be empty, but no harm in clearing them + // again. We keep them as member variables to avoid (re)allocating memory in each callback. + securities_.clear(); + security_ptrs_.clear(); + for (const auto &py_sec : py_securities.items()) { + auto sec = to_bts_security_(py_sec); + if (!sec) { + LOG(md, Error, + "Failed to convert security {} to bts::domain::Security", + py_sec.name()); + LOG(md, Error, R"([py_md_sec_parse_error.json]{{ "sec": {}, "ts": {}}})", py_sec); + continue; + } + securities_.push_back(std::move(*sec)); + } + // Populate vectors of security ptrs per each venue. + for (auto &sec : securities_) { + security_ptrs_.push_back(&sec); + } + // Pass securities to the sinks (per venue). + listener_->on_securities(security_ptrs_); + securities_.clear(); + security_ptrs_.clear(); + } + + void on_books(const PyBookList &py_books) override { + LOG(md, Info, R"([py_md_books.json]{{ "bks": {}, "ts": {}}})", + json_formatter(py_books.items()), TimeStamp::now_ns()); + for (auto &py_book : py_books.items()) { + bts_assert(book_.count_populated() == 0); + to_book_(py_book, book_); + listener_->on_book(book_); + book_.clear(); + } + } + + void on_trades(const PyTradeList &py_trades) override { + LOG(md, Info, R"([py_md_trades.json]{{ "trds": {}, "ts": {}}})", + json_formatter(py_trades.items()), TimeStamp::now_ns()); + // `trades_` and `trade_ptrs_` should already be empty, but no harm in clearing them again. + // We keep them as member variables to avoid (re)allocating memory in each callback. + trades_.clear(); + trade_ptrs_.clear(); + for (const auto &py_trade : py_trades.items()) { + LOG(md, Info, "PyMarketDataSubscription received trade {}", + py_trade.to_string()); + to_bts_trade_(py_trade, trades_.emplace_back()); + } + for (const auto &t : trades_) { + trade_ptrs_.push_back(&t); + } + listener_->on_trades(trade_ptrs_); + trades_.clear(); + trade_ptrs_.clear(); + } + + SecurityID get_sec_id_( + Venue venue, SecurityType sec_type, const string &sec_name) { + auto sec_id = sec_id_store_->get_id(venue, sec_type, sec_name, true); + bts_assert_msgf( + sec_id, + "Failed to get security id for py_book. venue: {}, type: {}, name: " + "{}", + venue, sec_type, sec_name); + return SecurityID{*sec_id}; + } + + optional to_bts_security_(const PySecurity &py_sec) { + // We can't let python provider assign the id, because it is unaware of other + // md providers, so can't possibly guarentee a unique id. + bts_assert(py_sec.id() == 0); + Security sec; + auto &sec_comm = sec.security_common; + if (!venue_parse_smart(py_sec.venue(), &sec_comm.venue)) { + LOG(md, Error, "Failed to parse venue from '{}'", py_sec.venue()); + return std::nullopt; + } + sec_comm.exchange_sec_id = py_sec.exchange_id(); + sec_comm.currency = py_sec.currency(); + sec_comm.asset = py_sec.asset(); + sec_comm.group = py_sec.group(); + sec_comm.symbol = py_sec.asset(); + if (sec_comm.symbol.empty()) { + sec_comm.symbol = py_sec.group(); + } + const py_interop::PyContractSpecification &spec = py_sec.contract_spec(); + if (spec.price_infos().size() > 0) { + bts_assert(spec.price_infos().size() == 1); + const py_interop::PyContractPriceInfo &price_info = + spec.price_infos().items()[0]; + bts_assert(price_info.tick_unit() > 0 && price_info.tick_base() > 0); + sec_comm.min_price_increment = + price_info.tick_unit() / price_info.tick_base(); + if (price_info.cash_per_point() > 0) { + sec_comm.cash_per_point = price_info.cash_per_point(); + } + } + if (spec.quantity_infos().size() > 0) { + bts_assert(spec.quantity_infos().size() == 1); + const py_interop::PyContractQuantityInfo &qty_info = + spec.quantity_infos().items()[0]; + bts_assert(qty_info.tick_unit() > 0 && qty_info.tick_base() > 0); + sec_comm.min_quantity_increment = + qty_info.tick_unit() / qty_info.tick_base(); + sec_comm.min_quantity = std::max( + qty_info.min_value(), + static_cast(sec_comm.min_quantity_increment)); + } + sec_comm.desc = py_sec.name(); + if (py_sec.is_spot()) { + sec.security = SpotSecurity{}; + } else if (py_sec.is_future()) { + FutureSecurity fut; + fut.expiration = + TimeStamp::from_iso_string(py_sec.future().expiration()); + sec.security = std::move(fut); + } else if (py_sec.is_option()) { + OptionSecurity opt; + const auto &py_opt = py_sec.option(); + opt.expiration = TimeStamp::from_iso_string(py_opt.expiration()); + opt.call_put = py_opt.is_call() ? CallPut::CALL : CallPut::PUT; + opt.strike = Price::from_double(py_opt.strike()); + sec.security = std::move(opt); + } else { + LOG(md, Error, + "PySecurity has incomplete definition (not spot, future, or " + "option)"); + return std::nullopt; + } + sec_comm.id = + get_sec_id_(sec_comm.venue, sec.type(), sec_comm.exchange_sec_id); + return sec; + } + + void to_bts_trade_(const PyTrade &source, domain::TradeRecord &dest) { + Venue venue; + bts_assert(venue_parse_smart(source.venue(), &venue)); + SecurityType sec_type; + bts_assert(security_type_parse_smart(source.security_type(), &sec_type)); + dest.sec_id = get_sec_id_(venue, sec_type, source.exchange_security_id()); + dest.time_stamp = core::TimeStamp::from_nanos(source.timestamp()); + const string &agg_str = source.aggressor_side(); + dest.agg_side = agg_str.starts_with('B') || agg_str.starts_with('b') + ? AggressorSide::Buy + : AggressorSide::Sell; + dest.trade_price = Price::from_double(source.price()); + *dest.trade_quantity = source.quantity(); + } + + void to_book_side_(const PyBookSide &source, domain::BookSide &dest) { + for (int i = 0; i < source.size(); i++) { + auto py_level = source.get_level(i); + const auto price = py_level.price(); + const auto quantity = py_level.quantity(); + bts_assert(!std::isnan(price)); + bts_assert(quantity > 0); + *dest[i].total_quantity = quantity; + *dest[i].direct_quantity = quantity; + dest[i].price = domain::Price::from_double(price); + } + } + + void to_book_(const PyBook &source, domain::Book &dest) { + to_book_side_(source.bids(), dest.bids()); + to_book_side_(source.asks(), dest.asks()); + Venue venue; + bts_assert(venue_parse_smart(source.venue(), &venue)); + SecurityType type; + bts_assert(security_type_parse_smart(source.security_type(), &type)); + dest.set_security_id( + get_sec_id_(venue, type, source.exchange_security_id())); + } +}; + +PyMarketDataSubscription::PyMarketDataSubscription( + PyMarketDataProviderConfig config, IDGenerator *sec_id_store) + : me(std::make_unique( + std::move(config), sec_id_store)) {} + +PyMarketDataSubscription::~PyMarketDataSubscription() { me->stop(); } + +void PyMarketDataSubscription::start(shared_ptr listener) { + me->start(std::move(listener)); +} + +void PyMarketDataSubscription::stop() { me->stop(); } + +} // namespace bts::md diff --git a/src/app_sparkd/sparkd/md/PyMarketDataSubscription.h b/src/app_sparkd/sparkd/md/PyMarketDataSubscription.h new file mode 100644 index 000000000..1288270a3 --- /dev/null +++ b/src/app_sparkd/sparkd/md/PyMarketDataSubscription.h @@ -0,0 +1,32 @@ +#pragma once + +#include "spark/md/IMarketDataSource.h" + +#include + +namespace bts::api::md { +class PyMarketDataProviderConfig; +} + +namespace bts::persistence { +class IDGenerator; +} + +namespace bts::md { + +class PyMarketDataSubscription : public IMarketDataSource { + public: + explicit PyMarketDataSubscription( + api::md::PyMarketDataProviderConfig config, + persistence::IDGenerator *sec_id_store); + ~PyMarketDataSubscription(); + + void start(std::shared_ptr listener) override; + void stop() override; + + private: + struct PImpl; + std::unique_ptr me; +}; + +} // namespace bts::md diff --git a/src/lib_python_md/CMakeLists.txt b/src/lib_python_md/CMakeLists.txt new file mode 100644 index 000000000..6181e15a9 --- /dev/null +++ b/src/lib_python_md/CMakeLists.txt @@ -0,0 +1,140 @@ +cmake_minimum_required(VERSION 3.23) +# This lists file configures 3 primary targets: +# 1) python_md -> libpython_md.so +# * Normal c++ libs/exes (e.g., libspark, sparkd) can link this +# 2) python_md_module -> python_md_module.cpython-310-x86_64-linux-gnu.so +# * Exports a py module with the MdProvider base class +# * Py md providers must import this and define a class that derives from 'python_md_module.MdProvider' +# * Normal c++ libs/exes shouldn't link this +# * For more info on the cpython api: +# - https://docs.python.org/3/extending/building.html +# - https://docs.python.org/3/c-api/module.html#c.PyModuleDef +# 3) python_md_providers +# * Copies py md provider plugins to a runtime dir where sparkd can find them +# * Doesn't output a c++ lib or exe + +project(python_md) +include(GNUInstallDirs) +include(${CMAKE_SOURCE_DIR}/cmake/InitLibrary.cmake) + +if (NOT DEFINED PROJECT_VERSION) + set(PROJECT_VERSION 1.0.0) +endif() + +# Find Python from the virtual environment +find_package(Python3 REQUIRED COMPONENTS Interpreter Development) +find_package(pybind11 REQUIRED) + +# 1) python_md +init_library(SHARED) +target_link_libraries(${PROJECT_NAME} PUBLIC spark) + +target_include_directories( + ${PROJECT_NAME} + PUBLIC + ${Python3_INCLUDE_DIRS} +) +target_link_directories( + ${PROJECT_NAME} + PUBLIC + ${Python3_LIBRARY_DIRS} +) +target_link_libraries( + ${PROJECT_NAME} + PUBLIC + pybind11::embed + ${Python3_LIBRARIES} +) + +# 2) python_md_module +set(module_proj ${PROJECT_NAME}_module) +set(module_proj_SOURCES ${${PROJECT_NAME}_SOURCES}) +pybind11_add_module(${module_proj} SHARED ${module_proj_SOURCES}) +target_link_libraries( + ${module_proj} + PUBLIC + pybind11::embed + spark +) +target_include_directories( + ${module_proj} + PRIVATE + $ +) +target_include_directories( + ${module_proj} + PUBLIC + ${Python3_INCLUDE_DIRS} + $ + $ +) +install( + TARGETS ${module_proj} + EXPORT ${module_proj}Targets + RUNTIME + DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY + DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE + DESTINATION ${CMAKE_INSTALL_LIBDIR} +) +foreach(dir ${pybind11_INCLUDE_DIRS}) + install(DIRECTORY ${dir} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) +endforeach() +install( + EXPORT ${module_proj}Targets + FILE ${module_proj}Targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +# 3) python_md_providers +set(providers_proj ${PROJECT_NAME}_providers) +file( + GLOB_RECURSE providers + RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} + ${providers_proj}/*.py) +set(provider_outs) +foreach(_provider ${providers}) + set(_provider_in ${CMAKE_CURRENT_SOURCE_DIR}/${_provider}) + set(_provider_out ${CMAKE_CURRENT_BINARY_DIR}/${_provider}) + add_custom_command( + OUTPUT ${_provider_out} + COMMAND ${CMAKE_COMMAND} -E copy ${_provider_in} ${_provider_out} + DEPENDS ${_provider_in} + COMMENT "Copying md provider plugin ${_provider} to ${_provider_out}" + ) + list(APPEND provider_outs ${_provider_out}) +endforeach() + +add_custom_target(copy_${providers_proj} ALL DEPENDS ${provider_outs}) + +add_library(${providers_proj} INTERFACE) +add_library(${PROJECT_NAME}::${providers_proj} ALIAS ${providers_proj}) + +set_target_properties( + ${providers_proj} + PROPERTIES + INTERFACE_PYTHON_SCRIPTS_DIR + $$ +) + +set_target_properties( + ${providers_proj} + PROPERTIES + INTERFACE_PYTHON_SCRIPTS $$ +) + +install( + TARGETS ${providers_proj} + EXPORT ${providers_proj}Targets + DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +install( + EXPORT ${providers_proj}Targets + FILE ${providers_proj}Targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) +install(DIRECTORY ${providers_proj} DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/src/lib_python_md/Config.cmake.in b/src/lib_python_md/Config.cmake.in new file mode 100644 index 000000000..ea8dbc30c --- /dev/null +++ b/src/lib_python_md/Config.cmake.in @@ -0,0 +1,12 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@_moduleTargets.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@_providersTargets.cmake") + +find_dependency(Python3 REQUIRED COMPONENTS Interpreter Development) +find_dependency(pybind11) + +check_required_components(@PROJECT_NAME@) +check_required_components(@PROJECT_NAME@_module) +check_required_components(@PROJECT_NAME@_providers) diff --git a/src/lib_python_md/README.md b/src/lib_python_md/README.md new file mode 100644 index 000000000..bca33d5cb --- /dev/null +++ b/src/lib_python_md/README.md @@ -0,0 +1,89 @@ + + +[pybind11]: https://github.com/pybind/pybind11 +[lib_spark]: ../lib_spark/README.md + +# lib_python_md + +This library binds c++ market data providers to python modules +which can be loaded at runtime. + +## **Dependencies** + +* **[Pybind11][pybind11]** +* **[lib_spark][lib_spark]** + +## Notes + +* Because this is *python*, market data enums (SecurityType, Venue, Side, etc.) are represented as strings + * Parsing is **NOT** case sensitive (though it is conventional to use `UPPER_CASE` strings) + * Type name prefixes (SECURITY_TYPE_, VENUE_, SIDE_ etc.) are **NOT** required + * ***Having said that,*** we recommend UPPER_CASE strings without the type prefix. Here are a few examples: + * SECURITY_TYPE + * "SPOT" + * "FUTURE" + * "OPTION" + * etc. + * VENUE: + * "BYBIT" + * "GATEIO" + * "DERIBIT" + * "COINBASE" + * etc. + * SIDE, AGGRESSOR_SIDE: + * "BUY" + * "SELL" + +## Example +```python +import time +import python_md_module as pymd + + +class MdProviderExample(pymd.MdProvider): + def __init__(self): + super(MdProviderExample, self).__init__() + pass + + def start(self, sink: pymd.MdSink): + print("Starting MdProviderExample") + # An actual implementation would subscribe to market data here. + # This is just an example to show you how to pass market data + # back to the c++ Spark api. + + def add_dummy_security(): + # This example populates a dummy security for demonstrative purposes. + # Of course, an actual implementation would populate the security list + # with data received from the exchange (or some other provider). + sec = pymd.PySecurity() + sec.set_venue("GLBX") + sec.set_name("ESH8") + sec.set_asset("ES") + fut = pymd.PyFuture() + fut.set_expiration("2025-03-28") + sec.set_future(fut) + # Note: the example only adds 1 sec, but batch adds are supported. + sec_list = pymd.PySecurityList() + sec_list.append(sec) + sink.on_securities(sec_list) + + def add_dummy_trade(): + trade = pymd.PyTrade() + trade.set_venue("GLBX") + trade.set_security_type("FUTURE") + trade.set_exchange_security_id("ESH8") + trade.set_price(5684.25) + trade.set_quantity(1) + trade.set_aggressor_side("BUY") + trade.set_timestamp(time.time_ns()) + + add_dummy_security() + add_dummy_trade() + + def stop(self): + print("Stopping MdProviderExample") +``` + +## Devs +Python files in `python_md_providers/` (child dir of this dir) are copied to
+the plugins directory at build time, and should automatically be loaded at runtime. diff --git a/src/lib_python_md/python_md/md_provider.cpp b/src/lib_python_md/python_md/md_provider.cpp new file mode 100644 index 000000000..4e9de1a48 --- /dev/null +++ b/src/lib_python_md/python_md/md_provider.cpp @@ -0,0 +1,7 @@ +#include "python_md/md_provider.h" + +namespace bts::md::py_interop { + +MdProvider::~MdProvider() = default; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/md_provider.h b/src/lib_python_md/python_md/md_provider.h new file mode 100644 index 000000000..74ad68109 --- /dev/null +++ b/src/lib_python_md/python_md/md_provider.h @@ -0,0 +1,14 @@ +#pragma once + +#include "python_md/md_sink.h" + +namespace bts::md::py_interop { + +class MdProvider { + public: + virtual ~MdProvider(); + virtual void start(MdSink *sink) = 0; + virtual void stop() = 0; +}; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/md_sink.cpp b/src/lib_python_md/python_md/md_sink.cpp new file mode 100644 index 000000000..c09561296 --- /dev/null +++ b/src/lib_python_md/python_md/md_sink.cpp @@ -0,0 +1,7 @@ +#include "md_sink.h" + +namespace bts::md::py_interop { + +MdSink::~MdSink() = default; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/md_sink.h b/src/lib_python_md/python_md/md_sink.h new file mode 100644 index 000000000..19c4e35e2 --- /dev/null +++ b/src/lib_python_md/python_md/md_sink.h @@ -0,0 +1,18 @@ +#pragma once + +#include "python_md/py_book_list.h" +#include "python_md/py_security_list.h" +#include "python_md/py_trade_list.h" + +namespace bts::md::py_interop { + +class MdSink { + public: + virtual ~MdSink(); + + virtual void on_securities(const py_interop::PySecurityList &securities) = 0; + virtual void on_books(const py_interop::PyBookList &books) = 0; + virtual void on_trades(const py_interop::PyTradeList &trades) = 0; +}; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/md_sink_impl.cpp b/src/lib_python_md/python_md/md_sink_impl.cpp new file mode 100644 index 000000000..980fa98a4 --- /dev/null +++ b/src/lib_python_md/python_md/md_sink_impl.cpp @@ -0,0 +1,96 @@ +#include "python_md/md_sink_impl.h" +#include "python_md/py_security_list.h" +#include "python_md/py_trade_list.h" +#include "spark/logging/logging.h" +#include "spark/utils/formatters/exception_formatter.h" + +#include + +namespace bts::md::py_interop { + +#define ASSERT_FN(test, fn, ...) \ + bts_assert_msgf(test, "md_sink_impl::" fn ". " __VA_ARGS__) +#define LOG_FN(level, fn, ...) \ + LOG(md, level, "md_sink_impl::" fn ". " __VA_ARGS__) +#define DIAG_FN(fn, ...) LOG_FN(bts::Diag, fn, __VA_ARGS__) +#define INFO_FN(fn, ...) LOG_FN(bts::Info, fn, __VA_ARGS__) +#define WARN_FN(fn, ...) LOG_FN(bts::Warn, fn, __VA_ARGS__) +#define ERROR_FN(fn, ...) LOG_FN(bts::Error, fn, __VA_ARGS__) + +#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__) +#define INFO(...) _LOG(bts::Info, __VA_ARGS__) +#define ERROR(...) _LOG(bts::Error, __VA_ARGS__) + +struct MdSinkImpl::PImpl { + std::function securities_callback; + std::function books_callback; + std::function trades_callback; +}; + +MdSinkImpl::MdSinkImpl() : me(std::make_unique()) {} + +MdSinkImpl::MdSinkImpl(MdSinkImpl &&) = default; +MdSinkImpl &MdSinkImpl::operator=(MdSinkImpl &&) = default; +MdSinkImpl::~MdSinkImpl() = default; + +void MdSinkImpl::on_books(const PyBookList &books) { + DIAG_FN("on_books", "{}", books); + try { + if (books.items().empty()) { + WARN_FN("on_books", "books empty"); + return; + } + if (me->books_callback) { + me->books_callback(books); + } + } catch (const std::exception &ex) { + ERROR_FN("on_books", "ex: {}", ex); + } +} + +void MdSinkImpl::on_securities(const PySecurityList &securities) { + DIAG_FN("on_securities", "{}", securities); + try { + if (securities.items().empty()) { + WARN_FN("on_securities", "securities empty"); + return; + } + if (me->securities_callback) { + me->securities_callback(securities); + } + } catch (const std::exception &ex) { + ERROR_FN("on_securities", "ex: {}", ex); + } +} + +void MdSinkImpl::on_trades(const PyTradeList &trades) { + DIAG_FN("on_trades", "{}", trades); + try { + if (trades.items().empty()) { + WARN_FN("on_trades", "trades empty"); + return; + } + if (me->trades_callback) { + me->trades_callback(trades); + } + } catch (const std::exception &ex) { + ERROR_FN("on_trades", "ex: {}", ex); + } +} + +void MdSinkImpl::set_books_callback( + std::function callback) { + me->books_callback = callback; +} + +void MdSinkImpl::set_trades_callback( + std::function callback) { + me->trades_callback = callback; +} + +void MdSinkImpl::set_securities_callback( + std::function callback) { + me->securities_callback = callback; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/md_sink_impl.h b/src/lib_python_md/python_md/md_sink_impl.h new file mode 100644 index 000000000..d50f63519 --- /dev/null +++ b/src/lib_python_md/python_md/md_sink_impl.h @@ -0,0 +1,35 @@ +#pragma once + +#include "python_md/md_sink.h" +#include "python_md/py_book_list.h" +#include "python_md/py_security_list.h" +#include "python_md/py_trade_list.h" + +#include +#include + +namespace bts::md::py_interop { + +class MdSinkImpl : public MdSink { + public: + MdSinkImpl(); + MdSinkImpl(MdSinkImpl &&); + ~MdSinkImpl() override; + + MdSinkImpl &operator=(MdSinkImpl &&); + + void on_books(const PyBookList &books) override; + void on_trades(const PyTradeList &trades) override; + void on_securities(const PySecurityList &securities) override; + + void set_books_callback(std::function callback); + void set_trades_callback(std::function callback); + void set_securities_callback( + std::function callback); + + private: + struct PImpl; + std::unique_ptr me; +}; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_book.h b/src/lib_python_md/python_md/py_book.h new file mode 100644 index 000000000..8c1f1a0cf --- /dev/null +++ b/src/lib_python_md/python_md/py_book.h @@ -0,0 +1,138 @@ +#pragma once + +#include "python_md/py_book_side.h" +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include + +namespace bts::md::py_interop { + +/** + * @brief An L2 Order Book (both sides of the market). + */ +class PyBook { + public: + /** + * Gets the exchange security id. This is typically the security's name + * (e.g., "BTS-PERPETUAL", or "ESH5"). + * + * @note Should be unique for each security at a particular venue (i.e., a single + * venue cannot have 2 securities with the same name). MUST be unique for each security + * of the same type (e.g., SPOT, FUTURE, OPTION) at a particular venue. + * + * @note There is no "security_id" member because that is an internal id that + * we generate elsewhere in c++ code. The python plugins just need to set the + * venue and exchange_security_id. + */ + const std::string &exchange_security_id() const; + /** + * @brief Sets the exchange security id. + * + * @param value The new exchange security id. + */ + void set_exchange_security_id(std::string value); + + /** + * @brief Gets the name of the venue (i.e., exchange). + * + * @return const std::string& The name of the venue. + */ + const std::string &venue() const; + void set_venue(std::string value); + + /** + * @brief Gets the name of the security type (e.g., "SPOT", "FUTURE", "OPTION"). + * + * @return const std::string& The name of the security type. + */ + const std::string &security_type() const; + /** + * @brief Sets the security type. + * + * @param value The new security type (should be "SPOT", "FUTURE", or "OPTION"). + */ + void set_security_type(std::string value); + + PyBookSide &bids(); + const PyBookSide &bids() const; + void set_bids(PyBookSide bids); + + PyBookSide &asks(); + const PyBookSide &asks() const; + void set_asks(PyBookSide asks); + + /** + * @brief Gets the number of levels in the book (i.e., the number of prices + * with resting orders). + */ + constexpr int size() const; + std::string to_string() const; + + private: + std::string venue_; + std::string security_type_; + std::string exchange_security_id_; + PyBookSide bids_; + PyBookSide asks_; +}; + +void to_json(nlohmann::json &j, const PyBook &bk); +void from_json(const nlohmann::json &j, PyBook &bk); + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL(bts::md::py_interop::PyBook, bs, "{}", bts::io::json_formatter(bs)); + +namespace bts::md::py_interop { + +inline const std::string &PyBook::venue() const { return venue_; } +inline void PyBook::set_venue(std::string value) { venue_ = std::move(value); } + +inline const std::string &PyBook::security_type() const { + return security_type_; +} +inline void PyBook::set_security_type(std::string value) { + security_type_ = std::move(value); +} + +inline const std::string &PyBook::exchange_security_id() const { + return exchange_security_id_; +} +inline void PyBook::set_exchange_security_id(std::string value) { + exchange_security_id_ = std::move(value); +} + +inline PyBookSide &PyBook::bids() { return bids_; } +inline const PyBookSide &PyBook::bids() const { return bids_; } +inline void PyBook::set_bids(PyBookSide bids) { bids_ = std::move(bids); } + +inline PyBookSide &PyBook::asks() { return asks_; } +inline const PyBookSide &PyBook::asks() const { return asks_; } +inline void PyBook::set_asks(PyBookSide asks) { asks_ = std::move(asks); } + +constexpr int PyBook::size() const { return bids_.size() + asks_.size(); } + +inline std::string PyBook::to_string() const { + return fmt::format("{}", *this); +} + +inline void to_json(nlohmann::json &j, const PyBook &bk) { + j["bids"] = bk.bids(); + j["asks"] = bk.asks(); +} + +inline void from_json(const nlohmann::json &j, PyBook &bk) { + bk.set_exchange_security_id(j.at("sec").get()); + bk.set_venue(j.at("venue").get()); + bk.set_security_type(j.at("typ").get()); + bk.set_bids(j.at("bids").get()); + bk.set_asks(j.at("asks").get()); +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_book_level.h b/src/lib_python_md/python_md/py_book_level.h new file mode 100644 index 000000000..3e73d1cc1 --- /dev/null +++ b/src/lib_python_md/python_md/py_book_level.h @@ -0,0 +1,70 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include + +namespace bts::md::py_interop { + +class PyBookLevel { + public: + constexpr PyBookLevel() = default; + + constexpr double price() const; + void set_price(double value); + + constexpr double quantity() const; + void set_quantity(double value); + + std::string to_string() const; + + private: + double price_{std::numeric_limits::quiet_NaN()}; + double quantity_{0}; +}; + +std::ostream &operator<<(std::ostream &out, const PyBookLevel &l) noexcept; + +void to_json(nlohmann::json &j, const PyBookLevel &l); +void from_json(const nlohmann::json &j, PyBookLevel &l); + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL(bts::md::py_interop::PyBookLevel, l, "{}", bts::io::json_formatter(l)); + +namespace bts::md::py_interop { + +constexpr double PyBookLevel::price() const { return price_; } +inline void PyBookLevel::set_price(double value) { price_ = value; } + +constexpr double PyBookLevel::quantity() const { return quantity_; } +inline void PyBookLevel::set_quantity(double value) { quantity_ = value; } + +inline std::string PyBookLevel::to_string() const { + return fmt::format("{}", *this); +} + +inline void to_json(nlohmann::json &j, const PyBookLevel &l) { + j["p"] = l.price(); + j["q"] = l.quantity(); +} + +inline void from_json(const nlohmann::json &j, PyBookLevel &l) { + l.set_price(j.at("p").get()); + l.set_quantity(j.at("q").get()); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyBookLevel &l) noexcept { + out << fmt::format("{}", l); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_book_list.h b/src/lib_python_md/python_md/py_book_list.h new file mode 100644 index 000000000..154d913ae --- /dev/null +++ b/src/lib_python_md/python_md/py_book_list.h @@ -0,0 +1,63 @@ +#pragma once + +#include "python_md/py_book.h" +#include "spark/core/FMT_IMPL.h" + +#include +#include + +namespace bts::md::py_interop { + +class PyBookList { + public: + void append(const py_interop::PyBook &book); + void clear(); + std::vector &items(); + const std::vector &items() const; + constexpr std::size_t size() const; + std::string to_string() const; + + private: + std::vector items_; +}; + +std::ostream &operator<<(std::ostream &out, const PyBookList &l) noexcept; + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + bts::md::py_interop::PyBookList, + bks, + "[{}]", + fmt::format("{}", fmt::join(bks.items(), ", "))); + +namespace bts::md::py_interop { + +inline void PyBookList::append(const py_interop::PyBook &book) { + items_.push_back(book); +} + +inline void PyBookList::clear() { items_.clear(); } + +constexpr std::size_t PyBookList::size() const { return items_.size(); } + +inline std::vector &PyBookList::items() { return items_; } +inline const std::vector &PyBookList::items() const { + return items_; +} + +inline std::string PyBookList::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyBookList &l) noexcept { + out << fmt::format("{}", l); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_book_side.cpp b/src/lib_python_md/python_md/py_book_side.cpp new file mode 100644 index 000000000..d5dd9a224 --- /dev/null +++ b/src/lib_python_md/python_md/py_book_side.cpp @@ -0,0 +1,67 @@ +#include "py_book_side.h" + +#include +#include + +namespace bts::md::py_interop { + +void PyBookSide::set_level(PyBookLevel level) { + if (std::isnan(level.price())) { + std::cerr << "PyBookLevel invalid price (nan)" << std::endl; + return; + } + if (level.quantity() < 0) { + std::cerr << "PyBookLevel invalid quantity (less than 0)" << std::endl; + return; + } + auto it = std::lower_bound( + levels_.begin(), levels_.end(), level, + [](const auto &lhs, const auto &rhs) { + return lhs.price() < rhs.price(); + }); + if (it == levels_.end()) { + if (level.quantity() == 0) { + std::cerr << "PyBookLevel " << to_string() + << " indicates remove op, but the price level does not exist" + << std::endl; + return; + } + levels_.push_back(std::move(level)); + } else if (it->price() == level.price()) { + if (level.quantity() == 0) { + levels_.erase(it); + } else { + *it = std::move(level); + } + } else { + levels_.insert(it, std::move(level)); + } +} + +std::string PyBookSide::to_string_pretty() const { + std::string rv; + if (is_ascending_) { + bool is_first = true; + for (const auto &level : levels_) { + if (is_first) { + is_first = false; + } else { + rv.append(", "); + } + rv.append(level.to_string()); + } + } else { + bool is_first = true; + for (auto it = levels_.rbegin(); it != levels_.rend(); it++) { + if (is_first) { + is_first = false; + } else { + rv.append(", "); + } + rv.append(it->to_string()); + } + } + return rv; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_book_side.h b/src/lib_python_md/python_md/py_book_side.h new file mode 100644 index 000000000..0bd970ba6 --- /dev/null +++ b/src/lib_python_md/python_md/py_book_side.h @@ -0,0 +1,93 @@ +#pragma once + +#include "python_md/py_book_level.h" +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include + +namespace bts::md::py_interop { + +/** + * @brief L2 Order Book for one side of the market (i.e., bids or offers). + * + * @details Bid market levels should be in DESCENDING order by price, while Ask + * levels (offers) should be in ASCENDING order. Another way to think about it + * is the price levels are sorted by their distance from the opposite market. + */ +class PyBookSide { + public: + constexpr bool is_ascending(); + void set_is_ascending(bool is_ascending); + + constexpr PyBookLevel get_level(int index); + constexpr PyBookLevel get_level(int index) const; + void set_level(PyBookLevel level); + + constexpr int size() const; + + std::string to_string() const; + std::string to_string_pretty() const; + + private: + std::vector levels_; + bool is_ascending_; + + friend void to_json(nlohmann::json &j, const PyBookSide &bs); + friend void from_json(const nlohmann::json &j, PyBookSide &bs); +}; + +void to_json(nlohmann::json &j, const PyBookSide &bs); +void from_json(const nlohmann::json &j, PyBookSide &bs); + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + bts::md::py_interop::PyBookSide, bs, "{}", bts::io::json_formatter(bs)); + +namespace bts::md::py_interop { + +constexpr bool PyBookSide::is_ascending() { return is_ascending_; } + +inline void PyBookSide::set_is_ascending(bool is_ascending) { + is_ascending_ = is_ascending; +} + +constexpr PyBookLevel PyBookSide::get_level(int index) { + if (!is_ascending_) { + index = levels_.size() - 1 - index; + } + return levels_.at(index); +} + +constexpr PyBookLevel PyBookSide::get_level(int index) const { + if (!is_ascending_) { + index = levels_.size() - 1 - index; + } + return levels_.at(index); +} + +constexpr int PyBookSide::size() const { return levels_.size(); } + +inline std::string PyBookSide::to_string() const { + return fmt::format("{}", *this); +} + +inline void to_json(nlohmann::json &j, const PyBookSide &bs) { j = bs.levels_; } + +inline void from_json(const nlohmann::json &j, PyBookSide &bs) { + j.get_to(bs.levels_); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyBookSide &bs) noexcept { + out << fmt::format("{}", bs); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_contract_price_info.h b/src/lib_python_md/python_md/py_contract_price_info.h new file mode 100644 index 000000000..fb5b41e30 --- /dev/null +++ b/src/lib_python_md/python_md/py_contract_price_info.h @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include +#include + +namespace bts::md::py_interop { + +/** + * Price metadata for a particular contract within a continuous price range. + * + * @note If there are multiple PyContractPriceInfo items, they should be added + * to a list in ascending order by "max_price". Then the "min_price" for each + * item simply the "max_price" of the previous item. Hence the omission of a + * "min_price" function. + */ +class PyContractPriceInfo { + public: + constexpr PyContractPriceInfo() = default; + + float tick_unit() const; + void set_tick_unit(float value); + + float tick_base() const; + void set_tick_base(float value); + + float multiplier() const; + void set_multiplier(float value); + + float cash_per_point() const; + void set_cash_per_point(float value); + + float max_price() const; + void set_max_price(float value); + + std::string to_string() const; + + private: + float tick_unit_ = std::numeric_limits::quiet_NaN(); + float tick_base_ = std::numeric_limits::quiet_NaN(); + float multiplier_ = 1; + float cash_per_point_ = 1; + float max_price_ = std::numeric_limits::max(); +}; + +std::ostream &operator<<( + std::ostream &out, const PyContractPriceInfo &qty_info) noexcept; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +inline float PyContractPriceInfo::tick_unit() const { return tick_unit_; } +inline void PyContractPriceInfo::set_tick_unit(float value) { + tick_unit_ = value; +} + +inline float PyContractPriceInfo::tick_base() const { return tick_base_; } +inline void PyContractPriceInfo::set_tick_base(float value) { + tick_base_ = value; +} + +inline float PyContractPriceInfo::multiplier() const { return multiplier_; } +inline void PyContractPriceInfo::set_multiplier(float value) { + multiplier_ = value; +} + +inline float PyContractPriceInfo::cash_per_point() const { + return cash_per_point_; +} +inline void PyContractPriceInfo::set_cash_per_point(float value) { + cash_per_point_ = value; +} + +inline float PyContractPriceInfo::max_price() const { return max_price_; } +inline void PyContractPriceInfo::set_max_price(float value) { + max_price_ = value; +} + +inline std::string PyContractPriceInfo::to_string() const { + std::stringstream str; + str << *this; + return str.str(); +} + +} // namespace bts::md::py_interop + +template <> +struct fmt::formatter { + constexpr auto parse(fmt ::format_parse_context &ctx) + -> decltype(ctx.end()) { + return ctx.end(); + } + template + auto format( + const bts::md::py_interop::PyContractPriceInfo &cpi, + FormatContext &ctx) const -> decltype(ctx.out()) { + return fmt::format_to( + ctx.out(), + R"( "tick_unit": {}, "tick_base": {}, "multiplier": {}, "cash_per_point": {}, "max_price": {} )", + cpi.tick_unit(), cpi.tick_base(), cpi.multiplier(), + cpi.cash_per_point(), cpi.max_price()); + } +}; + +namespace bts::md::py_interop { + +inline std::ostream &operator<<( + std::ostream &out, const PyContractPriceInfo &qty_info) noexcept { + out << fmt::format("{}", qty_info); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_contract_price_info_list.h b/src/lib_python_md/python_md/py_contract_price_info_list.h new file mode 100644 index 000000000..a936065b2 --- /dev/null +++ b/src/lib_python_md/python_md/py_contract_price_info_list.h @@ -0,0 +1,59 @@ +#pragma once + +#include "python_md/py_contract_price_info.h" +#include "spark/core/FMT_IMPL.h" + +#include +#include + +namespace bts::md::py_interop { + +class PyContractPriceInfoList { + public: + void append(const PyContractPriceInfo &item); + void clear(); + const std::vector &items() const; + constexpr std::size_t size() const; + std::string to_string() const; + + private: + std::vector items_; +}; + +std::ostream &operator<<( + std::ostream &out, const PyContractPriceInfoList &l) noexcept; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +} // namespace bts::md::py_interop + +FMT_IMPL( + bts::md::py_interop::PyContractPriceInfoList, + l, + "[{}]", + fmt::format("{}", fmt::join(l.items(), ", "))); + +namespace bts::md::py_interop { + +inline void PyContractPriceInfoList::append(const PyContractPriceInfo &value) { + items_.push_back(value); +} + +inline void PyContractPriceInfoList::clear() { items_.clear(); } + +constexpr std::size_t PyContractPriceInfoList::size() const { + return items_.size(); +} + +inline const std::vector & +PyContractPriceInfoList::items() const { + return items_; +} + +inline std::string PyContractPriceInfoList::to_string() const { + return fmt::format("{}", *this); +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_contract_quantity_info.h b/src/lib_python_md/python_md/py_contract_quantity_info.h new file mode 100644 index 000000000..d64fd6ceb --- /dev/null +++ b/src/lib_python_md/python_md/py_contract_quantity_info.h @@ -0,0 +1,120 @@ +#pragma once + +#include +#include +#include +#include + +namespace bts::md::py_interop { + +/** + * Quantity metadata for a particular contract within a continuous price range. + * Most contracts use the same quantity metadata for all prices. For those that + * don't, the "min price" is interpretted as the "max_price" of the previous + * item in the list of quantity metadatas (presumably sorted by "max_price"). + */ +class PyContractQuantityInfo { + public: + constexpr PyContractQuantityInfo() = default; + + float min_value() const; + void set_min_value(float value); + + float max_value() const; + void set_max_value(float value); + + float tick_unit() const; + void set_tick_unit(float value); + + float tick_base() const; + void set_tick_base(float value); + + float multiplier() const; + void set_multiplier(float value); + + float max_price() const; + void set_max_price(float value); + + std::string to_string() const; + + private: + float min_value_ = std::numeric_limits::min(); + float max_value_ = std::numeric_limits::max(); + float tick_unit_ = std::numeric_limits::quiet_NaN(); + float tick_base_ = std::numeric_limits::quiet_NaN(); + float multiplier_ = 1; + float max_price_ = std::numeric_limits::max(); +}; + +std::ostream &operator<<( + std::ostream &out, const PyContractQuantityInfo &qty_info) noexcept; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +inline float PyContractQuantityInfo::min_value() const { return min_value_; } +inline void PyContractQuantityInfo::set_min_value(float value) { + min_value_ = value; +} + +inline float PyContractQuantityInfo::max_value() const { return max_value_; } +inline void PyContractQuantityInfo::set_max_value(float value) { + max_value_ = value; +} + +inline float PyContractQuantityInfo::tick_unit() const { return tick_unit_; } +inline void PyContractQuantityInfo::set_tick_unit(float value) { + tick_unit_ = value; +} + +inline float PyContractQuantityInfo::tick_base() const { return tick_base_; } +inline void PyContractQuantityInfo::set_tick_base(float value) { + tick_base_ = value; +} + +inline float PyContractQuantityInfo::multiplier() const { return multiplier_; } +inline void PyContractQuantityInfo::set_multiplier(float value) { + multiplier_ = value; +} + +inline float PyContractQuantityInfo::max_price() const { return max_price_; } +inline void PyContractQuantityInfo::set_max_price(float value) { + max_price_ = value; +} + +inline std::string PyContractQuantityInfo::to_string() const { + std::stringstream str; + str << *this; + return str.str(); +} + +} // namespace bts::md::py_interop + +template <> +struct fmt::formatter { + constexpr auto parse(fmt ::format_parse_context &ctx) + -> decltype(ctx.end()) { + return ctx.end(); + } + template + auto format( + const bts::md::py_interop::PyContractQuantityInfo &cqi, + FormatContext &ctx) const -> decltype(ctx.out()) { + return fmt::format_to( + ctx.out(), + R"( "min_value": {}, "max_value": {}, "tick_unit": {}, "tick_base": {}, "multiplier": {}, "max_price": {} )", + cqi.min_value(), cqi.max_value(), cqi.tick_unit(), cqi.tick_base(), + cqi.multiplier(), cqi.max_price()); + } +}; + +namespace bts::md::py_interop { + +inline std::ostream &operator<<( + std::ostream &out, const PyContractQuantityInfo &qty_info) noexcept { + out << fmt::format("{}", qty_info); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_contract_quantity_info_list.h b/src/lib_python_md/python_md/py_contract_quantity_info_list.h new file mode 100644 index 000000000..1377697db --- /dev/null +++ b/src/lib_python_md/python_md/py_contract_quantity_info_list.h @@ -0,0 +1,70 @@ +#pragma once + +#include "python_md/py_contract_quantity_info.h" +#include "spark/core/FMT_IMPL.h" + +#include +#include + +namespace bts::md::py_interop { + +class PyContractQuantityInfoList { + public: + void append(const PyContractQuantityInfo &item); + void remove_at(int index); + void clear(); + const std::vector &items() const; + constexpr std::size_t size() const; + std::string to_string() const; + + private: + std::vector items_; +}; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +} // namespace bts::md::py_interop + +FMT_IMPL( + bts::md::py_interop::PyContractQuantityInfoList, + l, + "[{}]", + fmt::format("{}", fmt::join(l.items(), ", "))); + +namespace bts::md::py_interop { + +inline void PyContractQuantityInfoList::append( + const PyContractQuantityInfo &value) { + items_.push_back(value); +} + +inline void PyContractQuantityInfoList::remove_at(int index) { + if (index >= 0 && static_cast(index) < items_.size()) { + items_.erase(items_.begin() + index); + } +} + +inline void PyContractQuantityInfoList::clear() { items_.clear(); } + +constexpr std::size_t PyContractQuantityInfoList::size() const { + return items_.size(); +} + +inline const std::vector & +PyContractQuantityInfoList::items() const { + return items_; +} + +inline std::string PyContractQuantityInfoList::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyContractQuantityInfoList &l) noexcept { + out << fmt::format("{}", l); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_contract_specification.h b/src/lib_python_md/python_md/py_contract_specification.h new file mode 100644 index 000000000..9b44f83cf --- /dev/null +++ b/src/lib_python_md/python_md/py_contract_specification.h @@ -0,0 +1,126 @@ +#pragma once + +#include "python_md/py_contract_price_info_list.h" +#include "python_md/py_contract_quantity_info_list.h" +#include "spark/core/FMT_IMPL.h" + +#include +#include + +namespace bts::md::py_interop { + +/** + * Quantity and price metadata for a particular contract. + */ +class PyContractSpecification { + public: + constexpr PyContractSpecification() = default; + + const PyContractPriceInfoList &price_infos() const; + PyContractPriceInfoList &mutable_price_infos(); + void set_price_infos(PyContractPriceInfoList value); + + const PyContractQuantityInfoList &quantity_infos() const; + PyContractQuantityInfoList &mutable_quantity_infos(); + void set_quantity_infos(PyContractQuantityInfoList value); + + const PyContractQuantityInfoList ¬ional_quantity_infos() const; + PyContractQuantityInfoList &mutable_notional_quantity_infos(); + void set_notional_quantity_infos(PyContractQuantityInfoList value); + + std::string to_string() const; + + private: + PyContractPriceInfoList price_infos_; + PyContractQuantityInfoList quantity_infos_; + PyContractQuantityInfoList notional_quantity_infos_; +}; + +std::ostream &operator<<( + std::ostream &out, const PyContractSpecification &opt) noexcept; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +} // namespace bts::md::py_interop + +FMT_IMPL( + bts::md::py_interop::PyContractSpecification, + s, + R"({{ "price_infos": {}, "quantity_infos": {}, "notional_quantity_infos": {} }})", + s.price_infos(), + s.quantity_infos(), + s.notional_quantity_infos()); + +// template <> +// struct fmt::formatter { +// constexpr auto parse(fmt ::format_parse_context &ctx) +// -> decltype(ctx.end()) { +// return ctx.end(); +// } +// template +// auto format( +// const bts::md::py_interop::PyContractSpecification &spec, +// FormatContext &ctx) const -> decltype(ctx.out()) { +// return fmt::format_to( +// ctx.out(), +// R"({{ "price_infos": [{}], "quantity_infos": [{}], "notional_quantity_infos": [{}] }})", +// fmt::format("{}", fmt::join(spec.price_infos().items(), ", ")), +// fmt::format("{}", fmt::join(spec.quantity_infos().items(), ", ")), +// fmt::format( +// "{}", fmt::join(spec.notional_quantity_infos().items(), ", "))); +// } +// }; + +namespace bts::md::py_interop { + +inline const PyContractPriceInfoList & +PyContractSpecification::price_infos() const { + return price_infos_; +} +inline PyContractPriceInfoList &PyContractSpecification::mutable_price_infos() { + return price_infos_; +} +inline void PyContractSpecification::set_price_infos( + PyContractPriceInfoList value) { + price_infos_ = std::move(value); +} + +inline const PyContractQuantityInfoList & +PyContractSpecification::quantity_infos() const { + return quantity_infos_; +} +inline PyContractQuantityInfoList & +PyContractSpecification::mutable_quantity_infos() { + return quantity_infos_; +} +inline void PyContractSpecification::set_quantity_infos( + PyContractQuantityInfoList value) { + quantity_infos_ = std::move(value); +} + +inline const PyContractQuantityInfoList & +PyContractSpecification::notional_quantity_infos() const { + return notional_quantity_infos_; +} +inline PyContractQuantityInfoList & +PyContractSpecification::mutable_notional_quantity_infos() { + return notional_quantity_infos_; +} +inline void PyContractSpecification::set_notional_quantity_infos( + PyContractQuantityInfoList value) { + notional_quantity_infos_ = std::move(value); +} + +inline std::string PyContractSpecification::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyContractSpecification &spec) noexcept { + out << fmt::format("{}", spec); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_future.h b/src/lib_python_md/python_md/py_future.h new file mode 100644 index 000000000..53465810e --- /dev/null +++ b/src/lib_python_md/python_md/py_future.h @@ -0,0 +1,56 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" + +#include +#include +#include + +namespace bts::md::py_interop { + +/** + * Future contract expiration. + */ +class PyFuture { + public: + const std::string &expiration() const; + void set_expiration(std::string value); + + std::string to_string() const; + + private: + std::string expiration_; +}; + +void to_json(nlohmann::json &j, const PyFuture &fut); +void from_json(const nlohmann::json &j, PyFuture &fut); + +std::ostream &operator<<(std::ostream &out, const PyFuture &fut) noexcept; + +} // namespace bts::md::py_interop + +FMT_IMPL( + bts::md::py_interop::PyFuture, f, R"({{ "exp" : "{}" }})", f.expiration()); + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +namespace bts::md::py_interop { + +inline const std::string &PyFuture::expiration() const { return expiration_; } +inline void PyFuture::set_expiration(std::string value) { + expiration_ = std::move(value); +} + +inline std::string PyFuture::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyFuture &fut) noexcept { + out << fmt::format("{}", fut); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_md_executor.cpp b/src/lib_python_md/python_md/py_md_executor.cpp new file mode 100644 index 000000000..739d6e2f5 --- /dev/null +++ b/src/lib_python_md/python_md/py_md_executor.cpp @@ -0,0 +1,138 @@ +#include "py_md_executor.h" +#include "python_md/md_provider.h" +#include "python_md/md_sink.h" +#include "spark/utils/string_utils.h" +#include "spark/utils/thread_id.h" + +#include +#include +#include +#include +#include +#include + +namespace bts::md::py_interop { + +namespace py = pybind11; + +using bts::system::string_utils::snake_to_pascal_case; +using bts::system::string_utils::split; +using std::int64_t; +using std::size_t; +using std::string; + +/** + * Parses module and type name from a \p py_md_provider arg. The following formats are supported: + * 1) . + * 2) + * In this case, the type name defaults to the PascalCase equivalent of the module name. + * For example, the module "foo_bar" would have type name "FooBar". + */ +static void parse_py_md_provider( + const std::string &py_md_provider, + std::string *module_name, + std::string *type_name) { + auto parts = split(py_md_provider, "."); + if (parts.empty()) { + return; + } + if (parts.size() == 1) { + snake_to_pascal_case(parts.emplace_back(parts[0])); + } + *module_name = parts[0]; + *type_name = parts[1]; +} + +struct __attribute__((visibility("hidden"))) PyMdExecutor_PImpl { + std::string py_md_provider; + std::vector module_paths; + std::unique_ptr provider; + MdSink *sink; + std::optional provider_obj; + bool is_running = false; + size_t thread_id = BTS_THIS_THREAD_ID; + std::mutex instance_mx; + std::optional interpreter{}; + std::function securities_callback; + std::function books_callback; + std::function trades_callback; + + void start() { + check_access(); + { + std::lock_guard lock{instance_mx}; + if (is_running) { + return; + } + interpreter.emplace(false); + is_running = true; + } + provider_obj = create_provider(); + MdProvider *provider = provider_obj->cast(); + provider->start(sink); + } + + void stop() { + check_access(); + std::lock_guard lock{instance_mx}; + if (!provider_obj) { + return; + } + MdProvider *providerx = provider_obj->cast(); + providerx->stop(); + provider_obj = std::nullopt; + interpreter.reset(); + } + + py::object create_provider() { + string provider_module_name; + string provider_type_name; + parse_py_md_provider( + py_md_provider, &provider_module_name, &provider_type_name); + // Prepare module path + py::module sys = py::module::import("sys"); + for (const auto &module_path : module_paths) { + sys.attr("path").attr("append")(module_path.c_str()); + } + // Import provider module + py::module provider_module = + py::module::import(provider_module_name.c_str()); + // Instantiate provider + return provider_module.attr(provider_type_name.c_str())(); + } + + void check_access() { + if (BTS_THIS_THREAD_ID != thread_id) { + throw std::runtime_error{ + "All calls to PyMdExecutor must be on the same thread."}; + } + } +}; + +PyMdExecutor::PyMdExecutor( + std::string py_md_provider, + std::vector module_paths, + MdSink *sink) + : me_(new PyMdExecutor_PImpl()) { + auto *me = static_cast(me_); + me->py_md_provider = std::move(py_md_provider); + me->module_paths = std::move(module_paths); + me->sink = sink; +} + +PyMdExecutor::~PyMdExecutor() { + auto *me = static_cast(me_); + delete me; +} + +void PyMdExecutor::start() { + auto *me = static_cast(me_); + me->start(); +} + +void PyMdExecutor::stop() { + auto *me = static_cast(me_); + me->stop(); +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_md_executor.h b/src/lib_python_md/python_md/py_md_executor.h new file mode 100644 index 000000000..72b05b686 --- /dev/null +++ b/src/lib_python_md/python_md/py_md_executor.h @@ -0,0 +1,24 @@ +#pragma once + +#include "python_md/md_sink.h" + +#include + +namespace bts::md::py_interop { + +class PyMdExecutor { + public: + PyMdExecutor( + std::string py_md_provider, + std::vector module_paths, + MdSink *sink); + ~PyMdExecutor(); + + void start(); + void stop(); + + private: + void *me_; +}; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_md_provider.cpp b/src/lib_python_md/python_md/py_md_provider.cpp new file mode 100644 index 000000000..f4a386d81 --- /dev/null +++ b/src/lib_python_md/python_md/py_md_provider.cpp @@ -0,0 +1,7 @@ +#include "py_md_provider.h" + +namespace bts::md::py_interop { + +PyMdProvider::~PyMdProvider() = default; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_md_provider.h b/src/lib_python_md/python_md/py_md_provider.h new file mode 100644 index 000000000..d1aff32cc --- /dev/null +++ b/src/lib_python_md/python_md/py_md_provider.h @@ -0,0 +1,31 @@ +#pragma once + +#include "python_md/md_provider.h" +#include "python_md/md_sink.h" + +#include + +namespace bts::md::py_interop { + +/** + * An implementation of `bts::md::py_interop::MdProvider` that binds to a python object at runtime. + * + * @note The python object must derive from 'python_md_module.MdProvider', and define methods: + * 1. 'start(md_sink: python_md_module.MdSink)' + * 2. 'stop' + * @note 'python_md_module' is a python module defined by us in c++ (see 'py_module.cpp'). + */ +class PyMdProvider : public MdProvider { + public: + using MdProvider::MdProvider; + + ~PyMdProvider() override; + + void start(MdSink *sink) override { + PYBIND11_OVERLOAD_PURE(void, MdProvider, start, sink); + } + + void stop() override { PYBIND11_OVERLOAD_PURE(void, MdProvider, stop); } +}; + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_module.cpp b/src/lib_python_md/python_md/py_module.cpp new file mode 100644 index 000000000..94d11ed15 --- /dev/null +++ b/src/lib_python_md/python_md/py_module.cpp @@ -0,0 +1,197 @@ +#include "md_provider.h" +#include "python_md/md_sink.h" +#include "python_md/md_sink_impl.h" +#include "python_md/py_book_level.h" +#include "python_md/py_book_list.h" +#include "python_md/py_book_side.h" +#include "python_md/py_contract_price_info.h" +#include "python_md/py_contract_price_info_list.h" +#include "python_md/py_contract_quantity_info.h" +#include "python_md/py_contract_quantity_info_list.h" +#include "python_md/py_contract_specification.h" +#include "python_md/py_md_provider.h" +#include "python_md/py_security.h" +#include "python_md/py_security_list.h" +#include "python_md/py_trade.h" + +#include + +using bts::md::py_interop::MdSinkImpl; +using bts::md::py_interop::PyBook; +using bts::md::py_interop::PyBookLevel; +using bts::md::py_interop::PyBookList; +using bts::md::py_interop::PyBookSide; +using bts::md::py_interop::PyContractPriceInfo; +using bts::md::py_interop::PyContractPriceInfoList; +using bts::md::py_interop::PyContractQuantityInfo; +using bts::md::py_interop::PyContractQuantityInfoList; +using bts::md::py_interop::PyContractSpecification; +using bts::md::py_interop::PyFuture; +using bts::md::py_interop::PyOption; +using bts::md::py_interop::PySecurity; +using bts::md::py_interop::PySecurityList; +using bts::md::py_interop::PySpot; +using bts::md::py_interop::PyTrade; +using bts::md::py_interop::PyTradeList; + +namespace py = pybind11; + +#define _STR(x) #x +// In general, we bind c++ methods to python methods with the same name verbatim. +// The DEF macro avoids typos in the python method name for this common case. +#define DEF(type, member) def(_STR(member), &type::member) +#define EXPLICIT_DEF(type, member, member_type) \ + def(_STR(member), (member_type) & type::member) +// The PROP macro defines getter and setter methods according to +// Binds a pseudo property with getter/setter methods. +// Binds getter -> , and setter -> set_. +#define PROP(type, name) \ + def(_STR(name), &type::name).def(_STR(set_##name), &type::set_##name) + +// Define python module with c++ classes. +PYBIND11_MODULE(python_md_module, m) { + using BookSideGetter = PyBookSide &(PyBook::*)(); + using BookLevelGetter = PyBookLevel (PyBookSide::*)(int) const; + // security + py::class_(m, "PySpot") + .def(py::init<>()) + .def("__str__", &PySpot::to_string); + py::class_(m, "PyFuture") + .def(py::init<>()) + .PROP(PyFuture, expiration) + .def("__str__", &PyFuture::to_string); + py::class_(m, "PyOption") + .def(py::init<>()) + .PROP(PyOption, expiration) + .PROP(PyOption, is_call) + .PROP(PyOption, strike) + .def("__str__", &PyOption::to_string); + py::class_(m, "PySecurity") + .def(py::init<>()) + .PROP(PySecurity, id) + .PROP(PySecurity, exchange_id) + .PROP(PySecurity, venue) + .PROP(PySecurity, name) + .PROP(PySecurity, currency) + .PROP(PySecurity, group) + .PROP(PySecurity, asset) + .PROP(PySecurity, contract_spec) + .PROP(PySecurity, spot) + .PROP(PySecurity, future) + .PROP(PySecurity, option) + .def("__str__", &PySecurity::to_string); + py::class_(m, "PySecurityList") + .def(py::init<>()) + .DEF(PySecurityList, append) + .DEF(PySecurityList, clear) + .def("__len__", &PySecurityList::size) + .def("__str__", &PySecurityList::to_string); + // book + py::class_(m, "PyBookLevel") + .def(py::init<>()) + .PROP(PyBookLevel, price) + .PROP(PyBookLevel, quantity); + py::class_(m, "PyBookSide") + .def(py::init<>()) + .EXPLICIT_DEF(PyBookSide, get_level, BookLevelGetter) + .DEF(PyBookSide, set_level) + .PROP(PyBookSide, is_ascending) + .def("__len__", &PyBookSide::size) + .def("__str__", &PyBookSide::to_string); + py::class_(m, "PyBook") + .def(py::init<>()) + .PROP(PyBook, venue) + .PROP(PyBook, security_type) + .PROP(PyBook, exchange_security_id) + .EXPLICIT_DEF(PyBook, bids, BookSideGetter) + .DEF(PyBook, set_bids) + .EXPLICIT_DEF(PyBook, asks, BookSideGetter) + .DEF(PyBook, set_asks) + .def("__len__", &PyBook::size) + .def("__str__", &PyBook::to_string); + py::class_(m, "PyBookList") + .def(py::init<>()) + .DEF(PyBookList, append) + .DEF(PyBookList, clear) + .def("__len__", &PyBookList::size) + .def("__str__", &PyBookList::to_string); + // trade + py::class_(m, "PyTrade") + .def(py::init<>()) + .PROP(PyTrade, venue) + .PROP(PyTrade, security_type) + .PROP(PyTrade, exchange_security_id) + .PROP(PyTrade, price) + .PROP(PyTrade, quantity) + .PROP(PyTrade, aggressor_side) + .PROP(PyTrade, timestamp); + py::class_(m, "PyTradeList") + .def(py::init<>()) + .DEF(PyTradeList, append) + .DEF(PyTradeList, clear) + .def("__len__", &PyTradeList::size) + .def("__str__", &PyTradeList::to_string); + // contract spec + py::class_(m, "PyContractSpecification") + .def(py::init<>()) + .PROP(PyContractSpecification, price_infos) + .PROP(PyContractSpecification, quantity_infos) + .PROP(PyContractSpecification, notional_quantity_infos) + .def("__str__", &PyContractSpecification::to_string); + // price info + py::class_(m, "PyContractPriceInfo") + .def(py::init<>()) + .PROP(PyContractPriceInfo, tick_unit) + .PROP(PyContractPriceInfo, tick_base) + .PROP(PyContractPriceInfo, multiplier) + .PROP(PyContractPriceInfo, cash_per_point) + .PROP(PyContractPriceInfo, max_price) + .def("__str__", &PyContractPriceInfo::to_string); + py::class_(m, "PyContractPriceInfoList") + .def(py::init<>()) + .DEF(PyContractPriceInfoList, append) + .DEF(PyContractPriceInfoList, clear) + .DEF(PyContractPriceInfoList, items) + .def("__len__", &PyContractPriceInfoList::size) + .def("__str__", &PyContractPriceInfoList::to_string); + // quantity info + py::class_(m, "PyContractQuantityInfo") + .def(py::init<>()) + .PROP(PyContractQuantityInfo, min_value) + .PROP(PyContractQuantityInfo, max_value) + .PROP(PyContractQuantityInfo, tick_unit) + .PROP(PyContractQuantityInfo, tick_base) + .PROP(PyContractQuantityInfo, multiplier) + .PROP(PyContractQuantityInfo, max_price) + .def("__str__", &PyContractQuantityInfo::to_string); + py::class_(m, "PyContractQuantityInfoList") + .def(py::init<>()) + .DEF(PyContractQuantityInfoList, append) + .DEF(PyContractQuantityInfoList, clear) + .DEF(PyContractQuantityInfoList, items) + .def("__len__", &PyContractQuantityInfoList::size) + .def("__str__", &PyContractQuantityInfoList::to_string); + // md sink + py::class_(m, "MdSink") + .DEF(bts::md::py_interop::MdSink, on_securities) + .DEF(bts::md::py_interop::MdSink, on_books) + .DEF(bts::md::py_interop::MdSink, on_trades); + py::class_( + m, "MdSinkImpl") + .def(py::init<>()) + .DEF(bts::md::py_interop::MdSinkImpl, on_securities) + .DEF(bts::md::py_interop::MdSinkImpl, on_books) + .DEF(bts::md::py_interop::MdSinkImpl, on_trades); + // md provider + py::class_< + bts::md::py_interop::MdProvider, bts::md::py_interop::PyMdProvider>( + m, "MdProvider") + .def(py::init<>()) + .DEF(bts::md::py_interop::MdProvider, start) + .DEF(bts::md::py_interop::MdProvider, stop); +} + +#undef PROP +#undef EXPLICIT_DEF +#undef DEF +#undef _STR diff --git a/src/lib_python_md/python_md/py_option.h b/src/lib_python_md/python_md/py_option.h new file mode 100644 index 000000000..17f2db898 --- /dev/null +++ b/src/lib_python_md/python_md/py_option.h @@ -0,0 +1,74 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" + +#include +#include +#include + +namespace bts::md::py_interop { + +/** + * Option contract expiration, strike, and call/put. + */ +class PyOption { + public: + constexpr PyOption() = default; + + const std::string &expiration() const; + void set_expiration(std::string value); + + constexpr bool is_call() const; + void set_is_call(bool value); + + constexpr double strike() const; + void set_strike(double value); + + std::string to_string() const; + + private: + std::string expiration_; + bool is_call_{false}; + double strike_{std::numeric_limits::quiet_NaN()}; +}; + +std::ostream &operator<<(std::ostream &out, const PyOption &opt) noexcept; + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + bts::md::py_interop::PyOption, + f, + R"({{ "exp" : "{}", "k": {}, "cp": "{}" }})", + f.expiration(), + f.strike(), + f.is_call() ? 'C' : 'P'); + +namespace bts::md::py_interop { + +inline const std::string &PyOption::expiration() const { return expiration_; } +inline void PyOption::set_expiration(std::string value) { + expiration_ = std::move(value); +} + +constexpr bool PyOption::is_call() const { return is_call_; } +inline void PyOption::set_is_call(bool value) { is_call_ = value; } + +constexpr double PyOption::strike() const { return strike_; } +inline void PyOption::set_strike(double value) { strike_ = value; } + +inline std::string PyOption::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyOption &opt) noexcept { + out << fmt::format("{}", opt); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_security.cpp b/src/lib_python_md/python_md/py_security.cpp new file mode 100644 index 000000000..6b120215c --- /dev/null +++ b/src/lib_python_md/python_md/py_security.cpp @@ -0,0 +1,58 @@ +#include "py_security.h" +#include "spark/utils/overloaded.h" + +#include + +namespace bts::md::py_interop { + +using std::string; +using std::uint32_t; + +void to_json(nlohmann::json &j, const PySecurity &sec) { + j["id"] = sec.id(); + j["eid"] = sec.exchange_id(); + j["name"] = sec.name(); + j["venue"] = sec.venue(); + j["cxy"] = sec.currency(); + j["grp"] = sec.group(); + j["ass"] = sec.asset(); + std::visit( + overloaded{ + [&](const PySpot &) { j["typ"] = "SPOT"; }, + [&](const PyFuture &fut) { + j["typ"] = "FUT"; + j["exp"] = fut.expiration(); + }, + [&](const PyOption &opt) { + j["typ"] = "OPT"; + j["exp"] = opt.expiration(); + j["k"] = opt.strike(); + j["cp"] = opt.is_call() ? "C" : "P"; + }, + }, + sec.sec_); +} + +void from_json(const nlohmann::json &j, PySecurity &sec) { + sec.set_id(j.at("id").get()); + sec.set_exchange_id(j.at("eid").get()); + sec.set_name(j.at("name").get()); + sec.set_venue(j.at("venue").get()); + sec.set_currency(j.at("cxy").get()); + sec.set_group(j.at("grp").get()); + sec.set_asset(j.at("ass").get()); + const auto typ = j.at("typ").get(); + if (typ.starts_with('S')) { + sec.sec_.emplace(); + } else if (typ.starts_with('F')) { + auto &fut = sec.sec_.emplace(); + fut.set_expiration(j.at("exp").get()); + } else if (typ.starts_with('O')) { + auto &opt = sec.sec_.emplace(); + opt.set_expiration(j.at("exp").get()); + opt.set_is_call(j.at("cp").get().starts_with('C')); + opt.set_strike(j.at("k").get()); + } +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_security.h b/src/lib_python_md/python_md/py_security.h new file mode 100644 index 000000000..8603cbf02 --- /dev/null +++ b/src/lib_python_md/python_md/py_security.h @@ -0,0 +1,160 @@ +#pragma once + +#include "python_md/py_contract_specification.h" +#include "python_md/py_future.h" +#include "python_md/py_option.h" +#include "python_md/py_spot.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include +#include +#include +#include + +namespace bts::md::py_interop { + +class PySecurity { + public: + constexpr std::uint32_t id() const; + void set_id(std::uint32_t value); + + const std::string &exchange_id() const; + void set_exchange_id(std::string value); + + const std::string &name() const; + void set_name(std::string value); + + const std::string &venue() const; + void set_venue(std::string value); + + const std::string ¤cy() const; + void set_currency(std::string value); + + const std::string &group() const; + void set_group(std::string value); + + const std::string &asset() const; + void set_asset(std::string value); + + const PySpot &spot() const; + void set_spot(PySpot); + constexpr bool is_spot() const; + + const PyFuture &future() const; + void set_future(PyFuture); + constexpr bool is_future() const; + + const PyOption &option() const; + void set_option(PyOption); + constexpr bool is_option() const; + + const PyContractSpecification &contract_spec() const; + void set_contract_spec(PyContractSpecification value); + + std::string to_string() const; + + private: + std::uint32_t id_; + std::string exchange_id_; + std::string venue_; + std::string group_; + std::string asset_; + std::string name_; + std::string currency_; + PyContractSpecification contract_spec_; + std::variant sec_; + + friend struct fmt::formatter; + friend void to_json(nlohmann::json &j, const PySecurity &sec); + friend void from_json(const nlohmann::json &j, PySecurity &sec); +}; + +void to_json(nlohmann::json &j, const PySecurity &sec); +void from_json(const nlohmann::json &j, PySecurity &sec); + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +constexpr std::uint32_t PySecurity::id() const { return id_; } +inline void PySecurity::set_id(std::uint32_t value) { id_ = value; } + +inline const std::string &PySecurity::exchange_id() const { + return exchange_id_; +} +inline void PySecurity::set_exchange_id(std::string value) { + exchange_id_ = std::move(value); +} + +inline const std::string &PySecurity::name() const { return name_; } +inline void PySecurity::set_name(std::string value) { + name_ = std::move(value); +} + +inline const std::string &PySecurity::venue() const { return venue_; } +inline void PySecurity::set_venue(std::string value) { + venue_ = std::move(value); +} + +inline const std::string &PySecurity::currency() const { return currency_; } +inline void PySecurity::set_currency(std::string value) { + currency_ = std::move(value); +} + +inline const std::string &PySecurity::group() const { return group_; } +inline void PySecurity::set_group(std::string value) { + group_ = std::move(value); +} + +inline const std::string &PySecurity::asset() const { return asset_; } +inline void PySecurity::set_asset(std::string value) { + asset_ = std::move(value); +} + +inline const PySpot &PySecurity::spot() const { + if (std::holds_alternative(sec_)) { + return std::get(sec_); + } + throw std::runtime_error{"PySecurity is not a spot"}; +} +inline void PySecurity::set_spot(PySpot value) { sec_ = std::move(value); } +constexpr bool PySecurity::is_spot() const { + return std::holds_alternative(sec_); +} + +inline const PyFuture &PySecurity::future() const { + if (std::holds_alternative(sec_)) { + return std::get(sec_); + } + throw std::runtime_error{"PySecurity is not a future"}; +} +inline void PySecurity::set_future(PyFuture value) { sec_ = std::move(value); } +constexpr bool PySecurity::is_future() const { + return std::holds_alternative(sec_); +} + +inline const PyOption &PySecurity::option() const { + if (std::holds_alternative(sec_)) { + return std::get(sec_); + } + throw std::runtime_error{"PySecurity is not an option"}; +} +inline void PySecurity::set_option(PyOption value) { sec_ = std::move(value); } +constexpr bool PySecurity::is_option() const { + return std::holds_alternative(sec_); +} + +inline const PyContractSpecification &PySecurity::contract_spec() const { + return contract_spec_; +} +inline void PySecurity::set_contract_spec(PyContractSpecification value) { + contract_spec_ = std::move(value); +} + +inline std::string PySecurity::to_string() const { return name_; } + +} // namespace bts::md::py_interop + +FMT_IMPL(bts::md::py_interop::PySecurity, s, "{}", bts::io::json_formatter(s)); diff --git a/src/lib_python_md/python_md/py_security_list.h b/src/lib_python_md/python_md/py_security_list.h new file mode 100644 index 000000000..1f5d2a54a --- /dev/null +++ b/src/lib_python_md/python_md/py_security_list.h @@ -0,0 +1,54 @@ +#pragma once + +#include "python_md/py_security.h" +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include + +namespace bts::md::py_interop { + +class PySecurityList { + public: + void append(const PySecurity &security); + void clear(); + const std::vector &items() const; + constexpr std::size_t size() const; + std::string to_string() const; + + private: + std::vector items_; +}; + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + bts::md::py_interop::PySecurityList, + l, + "{}", + bts::io::json_formatter(l.items())); + +namespace bts::md::py_interop { + +inline void PySecurityList::append(const PySecurity &security) { + items_.push_back(security); +} + +inline void PySecurityList::clear() { items_.clear(); } + +constexpr std::size_t PySecurityList::size() const { return items_.size(); } + +inline const std::vector &PySecurityList::items() const { + return items_; +} + +inline std::string PySecurityList::to_string() const { + return fmt::format("{}", *this); +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_spot.h b/src/lib_python_md/python_md/py_spot.h new file mode 100644 index 000000000..9c36ca096 --- /dev/null +++ b/src/lib_python_md/python_md/py_spot.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +namespace bts::md::py_interop { + +/** + * Placeholder object that represents a Spot contract. + */ +class PySpot { + public: + std::string to_string() const; +}; + +std::ostream &operator<<(std::ostream &out, const PySpot &spot) noexcept; + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +inline std::string PySpot::to_string() const { return ""; } + +inline std::ostream &operator<<( + std::ostream &out, const PySpot & /*spot*/) noexcept { + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_trade.h b/src/lib_python_md/python_md/py_trade.h new file mode 100644 index 000000000..9a4c6238e --- /dev/null +++ b/src/lib_python_md/python_md/py_trade.h @@ -0,0 +1,157 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include +#include +#include + +namespace bts::md::py_interop { + +class PyTrade { + public: + /** + * Gets the exchange security id. This is typically the security's name + * (e.g., "BTS-PERPETUAL", or "ESH5"). + * + * @note Should be unique for each security at a particular venue (i.e., a single + * venue cannot have 2 securities with the same name). MUST be unique for each security + * of the same type (e.g., SPOT, FUTURE, OPTION) at a particular venue. + * + * @note There is no "security_id" member because that is an internal id that + * we generate elsewhere in c++ code. The python plugins just need to set the + * venue and exchange_security_id. + */ + const std::string &exchange_security_id() const; + /** + * Sets the exchange security id. + * + * @param value The new exchange security id. + */ + void set_exchange_security_id(std::string value); + + const std::string &venue() const; + void set_venue(std::string value); + + const std::string &security_type() const; + void set_security_type(std::string value); + + constexpr double price() const; + void set_price(double value); + + constexpr double quantity() const; + void set_quantity(double value); + + const std::string &aggressor_side() const; + void set_aggressor_side(std::string value); + + /** + * @brief The time at which the trade was executed (nanos since unix epoch). + */ + constexpr std::int64_t timestamp() const; + void set_timestamp(std::int64_t value); + + std::string to_string_pretty() const; + std::string to_string() const; + + private: + std::string venue_; + std::string security_type_; + std::string exchange_security_id_; + double price_; + double quantity_; + std::string aggressor_side_; + std::int64_t timestamp_; +}; + +void to_json(nlohmann::json &j, const PyTrade &t); +void from_json(const nlohmann::json &j, PyTrade &t); + +std::ostream &operator<<(std::ostream &out, const PyTrade &t) noexcept; + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL(bts::md::py_interop::PyTrade, t, "{}", bts::io::json_formatter(t)); + +namespace bts::md::py_interop { + +inline const std::string &PyTrade::venue() const { return venue_; } +inline void PyTrade::set_venue(std::string value) { venue_ = std::move(value); } + +inline const std::string &PyTrade::security_type() const { + return security_type_; +} +inline void PyTrade::set_security_type(std::string value) { + security_type_ = std::move(value); +} + +inline const std::string &PyTrade::exchange_security_id() const { + return exchange_security_id_; +} +inline void PyTrade::set_exchange_security_id(std::string value) { + exchange_security_id_ = std::move(value); +} + +constexpr double PyTrade::price() const { return price_; } +inline void PyTrade::set_price(double value) { price_ = value; } + +constexpr double PyTrade::quantity() const { return quantity_; } +inline void PyTrade::set_quantity(double value) { quantity_ = value; } + +inline const std::string &PyTrade::aggressor_side() const { + return aggressor_side_; +} +inline void PyTrade::set_aggressor_side(std::string value) { + aggressor_side_ = std::move(value); +} + +constexpr std::int64_t PyTrade::timestamp() const { return timestamp_; } +inline void PyTrade::set_timestamp(std::int64_t value) { timestamp_ = value; } + +inline std::string PyTrade::to_string() const { + return fmt::format("{}", *this); +} + +inline std::string PyTrade::to_string_pretty() const { + std::stringstream str; + if (!aggressor_side_.empty()) { + str << aggressor_side_ << " "; + } + str << quantity_ << exchange_security_id_ << " @ " << price_ << " (" + << venue_ << " ts " << timestamp_ << ")"; + return str.str(); +} + +inline void to_json(nlohmann::json &j, const PyTrade &t) { + j["sec"] = t.exchange_security_id(); + j["venue"] = t.venue(); + j["typ"] = t.security_type(); + j["agg"] = t.aggressor_side(); + j["p"] = t.price(); + j["q"] = t.quantity(); + j["ts"] = t.timestamp(); +} + +inline void from_json(const nlohmann::json &j, PyTrade &t) { + t.set_exchange_security_id(j.at("sec").get()); + t.set_venue(j.at("venue").get()); + t.set_security_type(j.at("typ").get()); + t.set_aggressor_side(j.at("agg").get()); + t.set_price(j.at("p").get()); + t.set_quantity(j.at("q").get()); + t.set_timestamp(j.at("ts").get()); +} + +inline std::ostream &operator<<(std::ostream &out, const PyTrade &t) noexcept { + out << fmt::format("{}", t); + return out; +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md/py_trade_list.h b/src/lib_python_md/python_md/py_trade_list.h new file mode 100644 index 000000000..483fe8130 --- /dev/null +++ b/src/lib_python_md/python_md/py_trade_list.h @@ -0,0 +1,52 @@ +#pragma once + +#include "python_md/py_trade.h" +#include "spark/io/json_formatter.h" + +#include + +namespace bts::md::py_interop { + +class PyTradeList { + public: + void append(const py_interop::PyTrade &trade); + void clear(); + const std::vector &items() const; + constexpr std::size_t size() const; + std::string to_string() const; + + private: + std::vector items_; +}; + +} // namespace bts::md::py_interop + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + bts::md::py_interop::PyTradeList, + l, + "{}", + bts::io::json_formatter(l.items())); + +namespace bts::md::py_interop { + +inline void PyTradeList::append(const py_interop::PyTrade &trade) { + items_.push_back(trade); +} + +inline void PyTradeList::clear() { items_.clear(); } + +constexpr std::size_t PyTradeList::size() const { return items_.size(); } + +inline const std::vector &PyTradeList::items() const { + return items_; +} + +inline std::string PyTradeList::to_string() const { + return fmt::format("{}", *this); +} + +} // namespace bts::md::py_interop diff --git a/src/lib_python_md/python_md_providers/binance_test.py b/src/lib_python_md/python_md_providers/binance_test.py new file mode 100644 index 000000000..d19fc32b9 --- /dev/null +++ b/src/lib_python_md/python_md_providers/binance_test.py @@ -0,0 +1,49 @@ +import json +from typing import Optional +from pathlib import Path + + +test_data_dir = Path("/").joinpath( + "home", + "bts", + ".local", + "share", + "bts", + "sparkd", + "data", + "test_data", + "binance", +) + + +def load_securities() -> list: + with open(test_data_dir.joinpath("exch_info.json")) as f: + return json.load(f)["symbols"] + return [] + + +def load_books() -> list: + with open(test_data_dir.joinpath("books.json")) as f: + return json.load(f)["books"] + return [] + + +if __name__ == "__main__": + raw_secs = load_securities() + for s in raw_secs: + obj = { + "venue": "Binance", + "name": s["symbol"], + "asset": s["baseAsset"], + "group": s["baseAsset"], + "currency": s["quoteAsset"], + } + print(json.dumps(obj)) + raw_books = load_books() + for b in raw_books: + obj = { + "name": b["name"], + "bids": b["bids"], + "asks": b["asks"], + } + print(json.dumps(obj)) diff --git a/src/lib_python_md/python_md_providers/binance_test_md_provider.py b/src/lib_python_md/python_md_providers/binance_test_md_provider.py new file mode 100644 index 000000000..7ce058dc8 --- /dev/null +++ b/src/lib_python_md/python_md_providers/binance_test_md_provider.py @@ -0,0 +1,161 @@ +import python_md_module as pymd +import json +from typing import Optional +from pathlib import Path + + +test_data_dir = Path("/").joinpath( + "home", + "bts", + ".local", + "share", + "bts", + "sparkd", + "data", + "test_data", + "binance", +) + + +def load_securities() -> list: + with open(test_data_dir.joinpath("exch_info.json")) as f: + return json.load(f)["symbols"] + return [] + + +def load_books() -> list: + with open(test_data_dir.joinpath("books.json")) as f: + return json.load(f)["books"] + return [] + + +def _get_security( + venue: str, + name: str, + asset: str, + group: str, + currency: str, + expiration: Optional[str] = None, + option_kind: Optional[str] = None, + strike: Optional[float] = None, +): + sec = pymd.PySecurity() + sec.set_venue(venue) + sec.set_exchange_id(name) + sec.set_name(name) + sec.set_currency(currency) + sec.set_asset(asset) + sec.set_group(group) + is_spot = expiration is None and option_kind is None and strike is None + is_future = expiration is not None and option_kind is None and strike is None + is_option = ( + expiration is not None and option_kind is not None and strike is not None + ) + if is_spot: + sec.set_spot(pymd.PySpot()) + elif is_future: + fut = pymd.PyFuture() + fut.set_expiration(expiration) + sec.set_future(fut) + elif is_option: + opt = pymd.PyOption() + opt.set_expiration(expiration) + opt.set_is_call(option_kind.lower().startswith("c")) + opt.set_strike(strike) + sec.set_option(opt) + else: + raise ValueError("Invalid parameters (unable to deduce security type)") + return sec + + +def _get_book_side(levels: list[(float, float)], is_bid_side: bool): + book_side = pymd.PyBookSide() + book_side.set_is_ascending(not is_bid_side) + for price, qty in levels: + book_level = pymd.PyBookLevel() + book_level.set_price(price) + book_level.set_quantity(qty) + book_side.set_level(book_level) + return book_side + + +def _get_trade( + venue: str, + security_type: str, + exchange_security_id: str, + price: float, + quantity: float, + aggressor_side: str, +): + trade = pymd.PyTrade() + trade.set_venue(venue) + trade.set_security_type(security_type) + trade.set_exchange_security_id(exchange_security_id) + trade.set_price(price) + trade.set_quantity(quantity) + trade.set_aggressor_side(aggressor_side) + return trade + + +class BinanceTestMdProvider(pymd.MdProvider): + def __init__(self): + super(BinanceTestMdProvider, self).__init__() + pass + + def start(self, sink: pymd.MdSink): + # start subscriptions, bind callbacks etc. + def add_securities(): + sec_list = pymd.PySecurityList() + raw_secs = load_securities() + for s in raw_secs: + sec_list.append( + _get_security( + venue="Binance", + name=s["symbol"], + asset=s["baseAsset"], + group=s["baseAsset"], + currency=s["quoteAsset"], + ) + ) + sink.on_securities(sec_list) + + def add_books(): + books = load_books() + for b in books: + bids = _get_book_side( + [(lvl["price"], lvl["quantity"]) for lvl in b["bids"]], + is_bid_side=True, + ) + asks = _get_book_side( + [(lvl["price"], lvl["quantity"]) for lvl in b["asks"]], + is_bid_side=False, + ) + book = pymd.PyBook() + book.set_venue("Binance") + book.set_security_type("SPOT") + book.set_exchange_security_id(b["name"]) + book.set_bids(bids) + book.set_asks(asks) + # pass book to sink + book_list = pymd.PyBookList() + book_list.append(book) + sink.on_books(book_list) + + add_securities() + add_books() + + def stop(self): + print("Stopping python DummyMdProvider") + + +if __name__ == "__main__": + raw_secs = load_securities() + for s in raw_secs: + obj = { + "venue": "Binance", + "name": s["symbol"], + "asset": s["baseAsset"], + "group": s["baseAsset"], + "currency": s["quoteAsset"], + } + print(json.dump(obj)) diff --git a/src/lib_python_md/python_md_providers/dummy_md_provider.py b/src/lib_python_md/python_md_providers/dummy_md_provider.py new file mode 100644 index 000000000..b20cac8a7 --- /dev/null +++ b/src/lib_python_md/python_md_providers/dummy_md_provider.py @@ -0,0 +1,65 @@ +import python_md_module as pymd +from py_md_utils import get_security, get_book_side, get_trade, get_contract_spec, get_price_info, get_quantity_info + + +class DummyMdProvider(pymd.MdProvider): + def __init__(self): + super(DummyMdProvider, self).__init__() + pass + + def start(self, sink: pymd.MdSink): + # start subscriptions, bind callbacks etc. + def add_fake_securities(): + sec_list = pymd.PySecurityList() + sec_list.append( + get_security( + venue="Glbx", + name="ESH8", + asset="ES", + group="ES", + currency="USD", + expiration="2026-03-28", + spec=get_contract_spec( + price_info=get_price_info( + tick_unit=25, + tick_base=1000, + cash_per_point=50, + ), + qty_info=get_quantity_info(tick_unit=1, tick_base=1), + ), + )) + sink.on_securities(sec_list) + + def add_fake_books(): + bids = get_book_side([(99.75, 8), (99.50, 11)], is_bid_side=True) + asks = get_book_side([(100.25, 3)], is_bid_side=False) + book = pymd.PyBook() + book.set_venue("Glbx") + book.set_security_type("FUTURE") + book.set_exchange_security_id("ESH8") + book.set_bids(bids) + book.set_asks(asks) + # pass book to sink + book_list = pymd.PyBookList() + book_list.append(book) + sink.on_books(book_list) + + def add_fake_trades(): + trade = get_trade( + venue="Glbx", + security_type="FUTURE", + exchange_security_id="ESH8", + price=100, + quantity=2, + aggressor_side="Buy", + ) + trade_list = pymd.PyTradeList() + trade_list.append(trade) + sink.on_trades(trade_list) + + add_fake_securities() + add_fake_books() + add_fake_trades() + + def stop(self): + print("Stopping python DummyMdProvider") diff --git a/src/lib_python_md/python_md_providers/py_md_utils.py b/src/lib_python_md/python_md_providers/py_md_utils.py new file mode 100644 index 000000000..6b666f28f --- /dev/null +++ b/src/lib_python_md/python_md_providers/py_md_utils.py @@ -0,0 +1,202 @@ +from typing import Optional +import python_md_module as pymd + + +def get_tick_factors(tick_sz: float): + """ + Returns a tuple of (tick unit, tick base) that represents the tick size as a + fraction. For example, if tick_sz is 0.01, returns (1, 100), as 1/100 == 0.01. + """ + if not (tick_sz > 0): + raise ValueError(f"Invalid tick size {tick_sz}") + tick_denom = 1.0 / tick_sz + match tick_denom: + case 1: + return (1, 1) + case 10: + return (10, 100) + case 100: + return (1, 100) + case 1_000: + return (1, 1_000) + case 10_000: + return (1, 10_000) + case 100_000: + return (1, 100_000) + case 1_000_000: + return (1, 1_000_000) + case 10_000_000: + return (1, 10_000_000) + case 100_000_000: + return (1, 100_000_000) + case 1_000_000_000: + return (1, 1_000_000_000) + case 4: + return (25, 100) + case 40: + return (25, 1_000) + case 400: + return (25, 10_000) + case 4_000: + return (25, 100_000) + case 20: + return (5, 100) + case 200: + return (5, 1_000) + case 2_000: + return (5, 10_000) + case 20_000: + return (5, 100_000) + case _: + raise ValueError(f"Invalid tick size {tick_sz}") + +def get_price_info( + tick_unit: float, + tick_base: float, + cash_per_point: Optional[float] = None, + multiplier: Optional[float] = None, + max_price: Optional[float] = None, +): + # Use 'not' checks to account for nans (for which every op evaluates to false) + if not (tick_unit > 0) or not (tick_base >= tick_unit): + raise ValueError(f"Invalid tick factors {tick_unit}/{tick_base}") + price_info = pymd.PyContractPriceInfo() + price_info.set_tick_unit(tick_unit) + price_info.set_tick_base(tick_base) + if cash_per_point: + price_info.set_cash_per_point(cash_per_point) + if max_price: + price_info.set_max_price(max_price) + if multiplier: + price_info.set_multiplier(multiplier) + return price_info + + +def get_quantity_info( + tick_unit: float, + tick_base: float, + min_value: Optional[float] = None, + max_value: Optional[float] = None, + multiplier: Optional[float] = None, + max_price: Optional[float] = None, +): + # Use 'not' checks to account for nans (for which every op evaluates to false) + if not (tick_unit > 0) or not (tick_base >= tick_unit): + raise ValueError(f"Invalid tick factors {tick_unit}/{tick_base}") + if not min_value: + min_value = tick_unit / tick_base + elif min_value < (tick_unit / tick_base): + # min_value should at least be 1 tick + raise ValueError(f"min_value ({min_value}) < tick ({tick_unit}/{tick_base})") + qty_info = pymd.PyContractQuantityInfo() + qty_info.set_tick_unit(tick_unit) + qty_info.set_tick_base(tick_base) + qty_info.set_min_value(min_value) + if max_value: + if not (max_value > min_value): + raise ValueError( + f"max_value ({max_value}) not greater than min_value ({min_value})" + ) + qty_info.set_max_value(max_value) + if max_price: + qty_info.set_max_price(max_price) + if multiplier: + qty_info.set_multiplier(multiplier) + return qty_info + + +def get_contract_spec( + price_info: Optional[pymd.PyContractPriceInfo] = None, + qty_info: Optional[pymd.PyContractQuantityInfo] = None, + notional_qty_info: Optional[pymd.PyContractQuantityInfo] = None, +): + price_infos = pymd.PyContractPriceInfoList() + if not price_info: + # Default to 3 decimal places + price_info = get_price_info(1, 1000) + price_infos.append(price_info) + qty_infos = pymd.PyContractQuantityInfoList() + if not qty_info: + # Default to 3 decimal places + qty_info = get_quantity_info(1, 1000) + qty_infos.append(qty_info) + notional_qty_infos = pymd.PyContractQuantityInfoList() + if notional_qty_info: + notional_qty_infos.append(notional_qty_info) + spec = pymd.PyContractSpecification() + spec.set_price_infos(price_infos) + spec.set_quantity_infos(qty_infos) + spec.set_notional_quantity_infos(notional_qty_infos) + return spec + + +def get_security( + venue: str, + name: str, + asset: str, + group: str, + currency: str, + expiration: Optional[str] = None, + option_kind: Optional[str] = None, + strike: Optional[float] = None, + spec: Optional[pymd.PyContractSpecification] = None, +): + sec = pymd.PySecurity() + sec.set_venue(venue) + sec.set_exchange_id(name) + sec.set_name(name) + sec.set_currency(currency) + sec.set_asset(asset) + sec.set_group(group) + if not spec: + spec = get_contract_spec() + sec.set_contract_spec(spec) + is_spot = expiration is None and option_kind is None and strike is None + is_future = expiration is not None and option_kind is None and strike is None + is_option = ( + expiration is not None and option_kind is not None and strike is not None + ) + if is_spot: + sec.set_spot(pymd.PySpot()) + elif is_future: + fut = pymd.PyFuture() + fut.set_expiration(expiration) + sec.set_future(fut) + elif is_option: + opt = pymd.PyOption() + opt.set_expiration(expiration) + opt.set_is_call(option_kind.lower().startswith("c")) + opt.set_strike(strike) + sec.set_option(opt) + else: + raise ValueError("Invalid parameters (unable to deduce security type)") + return sec + + +def get_book_side(levels: list[(float, float)], is_bid_side: bool): + book_side = pymd.PyBookSide() + book_side.set_is_ascending(not is_bid_side) + for price, qty in levels: + book_level = pymd.PyBookLevel() + book_level.set_price(price) + book_level.set_quantity(qty) + book_side.set_level(book_level) + return book_side + + +def get_trade( + venue: str, + security_type: str, + exchange_security_id: str, + price: float, + quantity: float, + aggressor_side: str, +): + trade = pymd.PyTrade() + trade.set_venue(venue) + trade.set_security_type(security_type) + trade.set_exchange_security_id(exchange_security_id) + trade.set_price(price) + trade.set_quantity(quantity) + trade.set_aggressor_side(aggressor_side) + return trade diff --git a/src/lib_spark/spark/api/md/MarketDataConfig.proto b/src/lib_spark/spark/api/md/MarketDataConfig.proto index 61aa5a3ac..a09bc8aa9 100644 --- a/src/lib_spark/spark/api/md/MarketDataConfig.proto +++ b/src/lib_spark/spark/api/md/MarketDataConfig.proto @@ -15,6 +15,7 @@ import "spark/api/md/GlbxMarketDataConfig.proto"; import "spark/api/md/TaifexMarketDataConfig.proto"; import "spark/api/md/TwseMarketDataConfig.proto"; import "spark/api/md/CboeMarketDataConfig.proto"; +import "spark/api/md/PyMarketDataProviderConfig.proto"; option csharp_namespace = "bts.api.md"; @@ -38,4 +39,5 @@ message MarketDataConfig { repeated EmumbaDeribitMarketDataConfig emumba_deribit = 100; repeated MarketDataRecordingConfig recording = 500; repeated MarketDataReplayConfig replay = 510; + repeated PyMarketDataProviderConfig python_md_providers = 600; } diff --git a/src/lib_spark/spark/api/md/PyMarketDataProviderConfig.proto b/src/lib_spark/spark/api/md/PyMarketDataProviderConfig.proto new file mode 100644 index 000000000..2de97de72 --- /dev/null +++ b/src/lib_spark/spark/api/md/PyMarketDataProviderConfig.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; + +option csharp_namespace = "bts.api.md"; + +import "spark/api/domain/Venue.proto"; + +package bts.api.md; + +message PyMarketDataProviderConfig { + string provider_type = 1; + repeated string module_path = 2; + bts.api.domain.Venue venue = 3; +} diff --git a/src/lib_spark/spark/utils/string_utils.h b/src/lib_spark/spark/utils/string_utils.h index ebe6eb52c..77f2ab639 100644 --- a/src/lib_spark/spark/utils/string_utils.h +++ b/src/lib_spark/spark/utils/string_utils.h @@ -2,9 +2,26 @@ #include #include +#include namespace bts::system::string_utils { +void snake_to_pascal_case(std::string &str); + +template +std::vector split(Range range, const std::string &delimiter); + +template +std::vector split( + Iterator first, Iterator last, const std::string &delimiter); + +template +void split( + Iterator first, + Iterator last, + const std::string &delimiter, + std::vector &parts); + template bool copy_to_array( const std::string &src, @@ -27,6 +44,85 @@ std::string copy_to_upper(const std::string &str); // Definition ////////////////////////////////////////////////// +inline void snake_to_pascal_case(std::string &str) { + std::size_t n = 0; + // Remove leading '_' + while (!str.empty() && str[0] == '_') { + n++; + } + if (n > 0) { + str.erase(0, n); + } + std::size_t pos = 0; + // Remove middle '_' (word delimiter), capitalize first letter of words + for (n = 0; n < str.size();) { + str[n] = toupper(str[n]); + pos = ++n; + while (n < str.size() && str[n] == '_') { + n++; + } + if (n > pos) { + str.erase(pos, n - pos); + } + } + // Remove trailing '_' + while (!str.empty() && str.back() == '_') { + n++; + } + if (n > 0) { + str.erase(str.size() - n); + } +} + +template +std::vector split(Range range, const std::string &delimiter) { + std::vector parts; + split(range.begin(), range.end(), delimiter, parts); + return parts; +} + +template +std::vector split( + Iterator first, Iterator last, const std::string &delimiter) { + std::vector parts; + split(first, last, delimiter, parts); + return parts; +} + +template +void split( + Iterator first, + Iterator last, + const std::string &delimiter, + std::vector &parts) { + + auto cursor = first; + auto curr_end = first; + auto curr_start = first; + + auto find_delim = [&cursor, &delimiter, &last]() { + for (auto it = cursor; it != last; it++) { + if (*it == delimiter[0]) { + if (std::equal( + it + 1, it + delimiter.size(), delimiter.begin() + 1, + delimiter.end())) { + return it; + } + } + } + return last; + }; + + while ((curr_end = find_delim()) != last) { + parts.push_back(std::string(curr_start, curr_end)); + curr_start = curr_end + delimiter.size(); + cursor = curr_end + delimiter.size(); + } + if (cursor != last) { + parts.push_back(std::string(cursor, last)); + } +} + template bool copy_to_array( const std::string &src, std::array &dest, bool null_terminate) { diff --git a/src/lib_spark/spark/utils/thread_id.h b/src/lib_spark/spark/utils/thread_id.h new file mode 100644 index 000000000..b6d280af4 --- /dev/null +++ b/src/lib_spark/spark/utils/thread_id.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +#define BTS_THREAD_ID(tid) std::hash{}(tid) +#define BTS_THIS_THREAD_ID \ + std::hash{}(std::this_thread::get_id())