From b227fc6254bc8c9b01e147049e27276946db91ef Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 15 May 2025 17:36:30 +0000 Subject: [PATCH] feat: Support python execution plugins --- CMakeLists.txt | 1 + src/app_sparkd/CMakeLists.txt | 31 +- .../configurations/binance_py_dev/.env | 2 + .../configurations/binance_py_dev/README.txt | 1 + .../binance_py_dev/binance_1.json | 8 + .../binance_usds_futures_1.json | 8 + .../configurations/binance_py_dev/init_env.py | 124 ++++ .../py_binance_usds_futures_1.json | 8 + .../configurations/binance_py_dev/spark.conf | 119 ++++ .../binance_py_dev/symbols.conf | 37 ++ .../execution/execution_gateway_provider.cpp | 81 ++- .../py_execution_gateway_adapter.cpp | 598 ++++++++++++++++++ .../execution/py_execution_gateway_adapter.h | 45 ++ .../execution/py_execution_gateway_config.h | 44 ++ src/lib_python_execution/CMakeLists.txt | 19 + src/lib_python_execution/Config.cmake.in | 12 + src/lib_python_execution/README.md | 112 ++++ src/lib_python_execution/pyrightconfig.json | 20 + .../python_execution/execution_gateway.cpp | 7 + .../python_execution/execution_gateway.h | 25 + .../execution_gateway_bridge.cpp | 7 + .../execution_gateway_bridge.h | 17 + .../execution_gateway_bridge_impl.cpp | 192 ++++++ .../execution_gateway_bridge_impl.h | 55 ++ .../py_cancel_order_request.cpp | 68 ++ .../py_cancel_order_request.h | 94 +++ .../py_cancel_replace_order_request.cpp | 80 +++ .../py_cancel_replace_order_request.h | 110 ++++ .../py_create_order_request.cpp | 101 +++ .../py_create_order_request.h | 117 ++++ .../python_execution/py_execution_gateway.cpp | 7 + .../python_execution/py_execution_gateway.h | 55 ++ .../python_execution/py_execution_report.cpp | 155 +++++ .../python_execution/py_execution_report.h | 276 ++++++++ .../python_execution/py_module.cpp | 137 ++++ .../python_execution/py_order_request.h | 16 + .../python_execution/py_position_info.cpp | 29 + .../python_execution/py_position_info.h | 134 ++++ .../python_execution_gateways/binance.env | 191 ++++++ .../binance_client.py | 503 +++++++++++++++ .../binance_env_helper.py | 100 +++ .../binance_execution_gateway.py | 242 +++++++ .../bybit_execution_gateway.py | 303 +++++++++ .../dummy_execution_gateway.py | 241 +++++++ .../py_execution_utils.py | 158 +++++ .../python_execution_gateways/simple_test.py | 241 +++++++ 46 files changed, 4898 insertions(+), 33 deletions(-) create mode 100644 src/app_sparkd/configurations/binance_py_dev/.env create mode 100644 src/app_sparkd/configurations/binance_py_dev/README.txt create mode 100644 src/app_sparkd/configurations/binance_py_dev/binance_1.json create mode 100755 src/app_sparkd/configurations/binance_py_dev/binance_usds_futures_1.json create mode 100644 src/app_sparkd/configurations/binance_py_dev/init_env.py create mode 100644 src/app_sparkd/configurations/binance_py_dev/py_binance_usds_futures_1.json create mode 100644 src/app_sparkd/configurations/binance_py_dev/spark.conf create mode 100644 src/app_sparkd/configurations/binance_py_dev/symbols.conf create mode 100644 src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.cpp create mode 100644 src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.h create mode 100644 src/app_sparkd/sparkd/execution/py_execution_gateway_config.h create mode 100644 src/lib_python_execution/CMakeLists.txt create mode 100644 src/lib_python_execution/Config.cmake.in create mode 100644 src/lib_python_execution/README.md create mode 100644 src/lib_python_execution/pyrightconfig.json create mode 100644 src/lib_python_execution/python_execution/execution_gateway.cpp create mode 100644 src/lib_python_execution/python_execution/execution_gateway.h create mode 100644 src/lib_python_execution/python_execution/execution_gateway_bridge.cpp create mode 100644 src/lib_python_execution/python_execution/execution_gateway_bridge.h create mode 100644 src/lib_python_execution/python_execution/execution_gateway_bridge_impl.cpp create mode 100644 src/lib_python_execution/python_execution/execution_gateway_bridge_impl.h create mode 100644 src/lib_python_execution/python_execution/py_cancel_order_request.cpp create mode 100644 src/lib_python_execution/python_execution/py_cancel_order_request.h create mode 100644 src/lib_python_execution/python_execution/py_cancel_replace_order_request.cpp create mode 100644 src/lib_python_execution/python_execution/py_cancel_replace_order_request.h create mode 100644 src/lib_python_execution/python_execution/py_create_order_request.cpp create mode 100644 src/lib_python_execution/python_execution/py_create_order_request.h create mode 100644 src/lib_python_execution/python_execution/py_execution_gateway.cpp create mode 100644 src/lib_python_execution/python_execution/py_execution_gateway.h create mode 100644 src/lib_python_execution/python_execution/py_execution_report.cpp create mode 100644 src/lib_python_execution/python_execution/py_execution_report.h create mode 100644 src/lib_python_execution/python_execution/py_module.cpp create mode 100644 src/lib_python_execution/python_execution/py_order_request.h create mode 100644 src/lib_python_execution/python_execution/py_position_info.cpp create mode 100644 src/lib_python_execution/python_execution/py_position_info.h create mode 100644 src/lib_python_execution/python_execution_gateways/binance.env create mode 100644 src/lib_python_execution/python_execution_gateways/binance_client.py create mode 100644 src/lib_python_execution/python_execution_gateways/binance_env_helper.py create mode 100644 src/lib_python_execution/python_execution_gateways/binance_execution_gateway.py create mode 100644 src/lib_python_execution/python_execution_gateways/bybit_execution_gateway.py create mode 100644 src/lib_python_execution/python_execution_gateways/dummy_execution_gateway.py create mode 100644 src/lib_python_execution/python_execution_gateways/py_execution_utils.py create mode 100644 src/lib_python_execution/python_execution_gateways/simple_test.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e96fce553..aefed1c70 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -119,6 +119,7 @@ else() add_subdirectory(src/lib_onixs_fix) add_subdirectory(src/lib_binance_execution) add_subdirectory(src/lib_okx_execution) + add_subdirectory(src/lib_python_execution) add_subdirectory(src/lib_python_md) add_subdirectory(src/app_sparkd) add_subdirectory(src/data_files) diff --git a/src/app_sparkd/CMakeLists.txt b/src/app_sparkd/CMakeLists.txt index 5363af3b0..1e18b8212 100644 --- a/src/app_sparkd/CMakeLists.txt +++ b/src/app_sparkd/CMakeLists.txt @@ -107,19 +107,19 @@ target_link_directories( # The dirs are relative to sparkd's path, represented by "$ORIGIN". set_target_properties( ${PROJECT_NAME} PROPERTIES - BUILD_RPATH "$ORIGIN/../lib_spark;$ORIGIN/../lib_python_md" + BUILD_RPATH "$ORIGIN/../lib_spark;$ORIGIN/../lib_python_core;$ORIGIN/../lib_python_execution;$ORIGIN/../lib_python_md" INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" ) -# Python interop (for python md providers) +include(${CMAKE_SOURCE_DIR}/cmake/SymLink.cmake) + +# Py md 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 @@ -128,10 +128,29 @@ sym_link_file( ) get_target_property(providers python_md_providers INTERFACE_PYTHON_SCRIPTS_DIR) sym_link_dir( - TARGET_NAME link_python_md_providers + TARGET_NAME ${PROJECT_NAME}_link_python_md_providers SOURCE ${providers} DEST ${CMAKE_CURRENT_BINARY_DIR}/python_md_providers ) +# Py execution +add_dependencies(${PROJECT_NAME} + python_execution + python_execution_module + python_execution_gateways + copy_python_execution_gateways +) +sym_link_local_lib(python_execution) +sym_link_file( + SOURCE ${CMAKE_BINARY_DIR}/src/lib_python_execution/python_execution_module.cpython-310-x86_64-linux-gnu.so + DEST ${CMAKE_CURRENT_BINARY_DIR}/python_execution_module.cpython-310-x86_64-linux-gnu.so + INSTALL_DEST ${CMAKE_INSTALL_BINDIR}/ +) +get_target_property(gateways python_execution_gateways INTERFACE_PYTHON_SCRIPTS_DIR) +sym_link_dir( + TARGET_NAME ${PROJECT_NAME}_link_python_execution_gateways + SOURCE ${gateways} + DEST ${CMAKE_CURRENT_BINARY_DIR}/python_execution_gateways +) target_link_libraries( sparkd @@ -140,6 +159,8 @@ target_link_libraries( okx_execution python_md python_md_module + python_execution + python_execution_module databento::databento ${emumba-deribit-connector-library_LIBRARIES} tbb diff --git a/src/app_sparkd/configurations/binance_py_dev/.env b/src/app_sparkd/configurations/binance_py_dev/.env new file mode 100644 index 000000000..a8c1ed7bf --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/.env @@ -0,0 +1,2 @@ +SPARKD__CONFIG_DIR=src/app_sparkd/configurations/binance_py_dev +SPARKD__SHM_SIZE=8gb diff --git a/src/app_sparkd/configurations/binance_py_dev/README.txt b/src/app_sparkd/configurations/binance_py_dev/README.txt new file mode 100644 index 000000000..618589ac2 --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/README.txt @@ -0,0 +1 @@ +* Connects to Binance test nets for market data and execution diff --git a/src/app_sparkd/configurations/binance_py_dev/binance_1.json b/src/app_sparkd/configurations/binance_py_dev/binance_1.json new file mode 100644 index 000000000..9871f2d8c --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/binance_1.json @@ -0,0 +1,8 @@ +{ + "api_key": "${BINANCE_API_KEY}", + "secret_key": "${HOME}/sparkdata/conf/.secrets/binance_1.pem", + "account": "BINANCE_DEV", + "rest_endpoint": "https://testnet.binance.vision", + "ws_endpoint": "wss://ws-api.testnet.binance.vision/ws-api/v3", + "ws_stream_endpoint": "wss://stream.testnet.binance.vision:9443" +} diff --git a/src/app_sparkd/configurations/binance_py_dev/binance_usds_futures_1.json b/src/app_sparkd/configurations/binance_py_dev/binance_usds_futures_1.json new file mode 100755 index 000000000..e4525f2dd --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/binance_usds_futures_1.json @@ -0,0 +1,8 @@ +{ + "api_key": "${BINANCE_USDS_FUTURES_API_KEY}", + "secret_key": "${BINANCE_USDS_FUTURES_SECRET_KEY}", + "account": "BINANCE_DEV", + "rest_endpoint": "https://testnet.binancefuture.com", + "ws_endpoint": "wss://testnet.binancefuture.com/ws-fapi/v1", + "ws_stream_endpoint": "wss://stream.binancefuture.com" +} diff --git a/src/app_sparkd/configurations/binance_py_dev/init_env.py b/src/app_sparkd/configurations/binance_py_dev/init_env.py new file mode 100644 index 000000000..d6af3512c --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/init_env.py @@ -0,0 +1,124 @@ +import traceback +import botocore +import json +import os + +from boto3.session import Session +from botocore.exceptions import ClientError +from fileinput import FileInput + + +def update_env_file(path, env_vars: dict): + """Update or add vars in a .env file in place.""" + if not env_vars: + # Nothing to update + return + if not os.path.exists(path): + with open(path, "w") as file: + for k, v in env_vars.items(): + file.write(f"{k}={v}\n") + return + + with FileInput(path, inplace=True) as file: + for line in file: + if not line.startswith("#"): + stripped: str = line.lstrip() + key_len = stripped.find("=") + if key_len >= 0: + k = stripped[0:key_len] + if k in env_vars: + print(f"{k}={env_vars[k]}") + del env_vars[k] + continue + print(line, end="") + + if len(env_vars) > 0: + with open(path, "a") as file: + for k, v in env_vars.items(): + file.write(f"{k}={v}\n") + + +def write_pem_file(file_path: str, text: str): + try: + dir_path = os.path.dirname(file_path) + os.makedirs(dir_path, exist_ok=True) + # rw------- + mode = 0o600 + fd = os.open(file_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode) + with os.fdopen(fd, "x") as f: + f.write(text) + return True + except Exception: + print(f"Error writing pem file '{file_path}'.") + traceback.print_exc() + return False + + +def get_secret(secret_name: str, profile_name: str): + session = Session(profile_name=profile_name) + client = session.client(service_name="secretsmanager") + + def on_token_error(e: Exception): + print(f""" +Failed to get secret value '{secret_name}'. {e} +Verify you are logged in to aws, then try again. + + aws sso login --profile {profile_name} + +If this error persists, verify you have access to these api keys. +For more help or information, talk to John. +""") + + try: + get_secret_value_response = client.get_secret_value( + SecretId=secret_name) + except ClientError as e: + print(f"Failed to get secret value.\n{e}") + raise e + except botocore.exceptions.SSOTokenLoadError as tl_err: + on_token_error(tl_err) + return None + except botocore.exceptions.TokenRetrievalError as tr_err: + on_token_error(tr_err) + return None + return get_secret_value_response["SecretString"] + + +def _init_binance_1(): + this_dir = os.path.dirname(__file__) + secret_str = get_secret("dev/binance/john", "bts-us-east-1") + if secret_str is None: + exit(1) + secret = json.loads(secret_str) + env_vars = {} + if "api-key" in secret: + env_vars["BINANCE_API_KEY"] = secret["api-key"] + if "secret-key-pem" in secret: + sk_pem = secret["secret-key-pem"] + sk_pem = "\n".join(sk_pem) + write_pem_file(f"{this_dir}/.secrets/binance_1.pem", sk_pem) + update_env_file(f"{this_dir}/.env.local", env_vars) + + +def _init_binance_usds_futures_1(): + this_dir = os.path.dirname(__file__) + secret_str = get_secret("dev/binance_usds_futures/john.hmac", + "bts-us-east-1") + if secret_str is None: + exit(1) + secret = json.loads(secret_str) + env_vars = {} + if "api-key" in secret: + env_vars["BINANCE_USDS_FUTURES_API_KEY"] = secret["api-key"] + if "secret-key" in secret: + env_vars["BINANCE_USDS_FUTURES_SECRET_KEY"] = secret["secret-key"] + update_env_file(f"{this_dir}/.env.local", env_vars) + + +def _run(): + _init_binance_1() + _init_binance_usds_futures_1() + + +if __name__ == "__main__": + _run() diff --git a/src/app_sparkd/configurations/binance_py_dev/py_binance_usds_futures_1.json b/src/app_sparkd/configurations/binance_py_dev/py_binance_usds_futures_1.json new file mode 100644 index 000000000..3a9c4ae93 --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/py_binance_usds_futures_1.json @@ -0,0 +1,8 @@ +{ + "gateway_type": "dummy_execution_gateway.DummyExecutionGateway", + "account": "BINANCE_DEV", + "module_path": [ + "python_execution_gateways" + ], + "venue": "VENUE_BINANCE_USDS_FUTURES" +} diff --git a/src/app_sparkd/configurations/binance_py_dev/spark.conf b/src/app_sparkd/configurations/binance_py_dev/spark.conf new file mode 100644 index 000000000..62f5f474e --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/spark.conf @@ -0,0 +1,119 @@ +JetFIX { + value { + # connection { + # name: "binance_1" + # venue: VENUE_BINANCE + # max_order_msgs_per_window: 300 + # window_duration_msecs: 1000 + # } + connection { + name: "binance_usds_futures_1" + venue: VENUE_BINANCE_USDS_FUTURES + max_order_msgs_per_window: 300 + window_duration_msecs: 1000 + } + } +} + +PublisherOptions { + value { + network_interface: "0.0.0.0" + heartbeat_ms: 5000 + heartbeat_boot_seconds: 60 + skip_options: true + hot_initial: 1024 + hot_growth: 1024 + cold_initial: 8192 + cold_growth: 2048 + channel_prefix: "" + disable_heartbeat: true + } +} + +Logging { + value { + initial_queue_size: 120001 + max_queue_growth: 4 + console { + default_level: "Info" + subsystem { + name: "OrderMan" + level: "Diag" + } + } + file { + default_level: "Info" + # subsystem { + # name: "md" + # level: "Diag" + # } + subsystem { + name: "OrderMan" + level: "Diag" + } + subsystem { + name: "Http" + level: "Diag" + } + } + } +} + +MarketDataConfig { + value { + # binance { + # num_depth_levels: 5 + # # url_rest_base: "wss://ws-api.binance.com:9443" + # # According to Binance, the "apiN" urls offer performance at the cost of stability. + # # https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-api-information + # # url_rest_base: "https://api1.binance.com:9443" + # # url_rest_base: "https://api.binance.com" + # url_rest_base: "https://testnet.binance.vision" + # # url_ws_base: "wss://ws-api.binance.com" + # url_ws_base: "wss://testnet.binance.vision" + + # security_criteria { + # clauses { + # security_types: SECURITY_TYPE_SPOT + # symbols: @SymbolLists.list[Binance].symbol + # name_regexps: "USDC|USDT$" + # } + # } + # } + + binance_usds_futures { + num_depth_levels: 5 + # url_rest_base: "https://fapi.binance.com" + # url_ws_base: "wss://fstream.binance.com" + url_rest_base: "https://testnet.binancefuture.com" + url_ws_base: "wss://stream.binancefuture.com" + + security_criteria { + clauses { + security_types: SECURITY_TYPE_FUTURE + symbols: @SymbolLists.list[BinanceUsdsFutures].symbol + } + } + } + } +} + +NotSimExecution { + value { + # entries { + # venue: VENUE_BINANCE + # } + entries { + venue: VENUE_BINANCE_USDS_FUTURES + } + # entries { + # venue: VENUE_GLBX + # } + # entries { + # venue: VENUE_OKX + # } + # entries { + # venue: VENUE_TAIFEX + # } + } +} diff --git a/src/app_sparkd/configurations/binance_py_dev/symbols.conf b/src/app_sparkd/configurations/binance_py_dev/symbols.conf new file mode 100644 index 000000000..7245f134b --- /dev/null +++ b/src/app_sparkd/configurations/binance_py_dev/symbols.conf @@ -0,0 +1,37 @@ +SymbolLists { + value { + list { + key: "Binance" + symbol: "AAVE" + symbol: "AVAX" + symbol: "BNB" + symbol: "BTC" + symbol: "DOGE" + symbol: "EIGEN" + symbol: "ETH" + } + list { + key: "BinanceUsdsFutures" + symbol: "AAVE" + symbol: "AVAX" + symbol: "BNB" + symbol: "BTC" + symbol: "DOGE" + symbol: "EIGEN" + symbol: "ETH" + } + } +} + +Symbols { + value { + venues { + name: "VENUE_BINANCE" + spot: @SymbolLists.list[Binance].symbol + } + venues { + name: "VENUE_BINANCE_USDS_FUTURES" + future: @SymbolLists.list[BinanceUsdsFutures].symbol + } + } +} diff --git a/src/app_sparkd/sparkd/execution/execution_gateway_provider.cpp b/src/app_sparkd/sparkd/execution/execution_gateway_provider.cpp index 549bcefa0..280c2869a 100644 --- a/src/app_sparkd/sparkd/execution/execution_gateway_provider.cpp +++ b/src/app_sparkd/sparkd/execution/execution_gateway_provider.cpp @@ -5,7 +5,10 @@ #include "binance_execution/usds_futures/usds_futures_gateway.h" #include "okx_execution/okx_execution_gateway.h" #include "onixs_fix/OnixFIXAdapter.h" +#include "spark/api/domain/Venue.h" +#include "spark/domain/DomainSecurityUtils.h" #include "spark/domain_model/Security.pb.h" +#include "spark/domain_model/Venue.h" #include "spark/io/JsonReader.h" #include "spark/orderman/gateways/CCAPIExecutionGateway.h" #include "spark/orderman/gateways/FakeExecutionGateway.h" @@ -17,6 +20,10 @@ #include "spark/orderman/gateways/sim/SimExecutionGatewayFactory.h" #include "spark/orderman/gateways/sim/SimExecutionGatewayUniqueWrapper.h" #include "spark/utils/PBUtils.h" +#include "spark/utils/bts_assert.h" +#include "spark/utils/type_name.h" +#include "sparkd/execution/py_execution_gateway_adapter.h" +#include "sparkd/execution/py_execution_gateway_config.h" namespace bts::orderman { @@ -33,6 +40,17 @@ using std::optional; using std::string; using std::vector; +template +static std::unique_ptr make_gw( + const config::JetFIX::Connection &conn, Args &&...args) { + LOG(OrderMan, Info, + R"([create_exe_gw.json]){{ "name": "{}", "venue": "{}", "type": "{}", "ts": {} }})", + conn.name(), bts::api::venue_name_pretty(conn.venue()), + std::string(bts::utils::cached_type_name()), + bts::core::TimeStamp::now_ns()); + return std::make_unique(std::forward(args)...); +} + struct ExecutionGatewayProvider::PImpl { PImpl( trace::PerfLog *l, @@ -63,43 +81,51 @@ struct ExecutionGatewayProvider::PImpl { std::unique_ptr create_gateway( const config::JetFIX::Connection &conn) { INFO_FN("create_gateway", "conn: {}", utils::pb::to_string(conn)); + // ************************************* + // Simple hack to integrate python execution gateways: + // If a json file exists with the same name as the jetfix connection, + // but with a "py_" prefix, assume that file defines python gateway + // config for that connection. + // ************************************* + auto py_cfg_j = load_config_json(fmt::format("py_{}", conn.name())); + if (py_cfg_j) { + auto py_cfg = py_cfg_j->get(); + bts_assert( + domain::DomainSecurityUtils::convert(conn.venue()) == + py_cfg.venue); + return make_gw( + conn, o, std::move(py_cfg), conn); + } if (SimExecutionGatewayFactory::is_sim_execution_on(conn.venue())) { - return std::make_unique( - conn.venue()); + return make_gw(conn, conn.venue()); } switch (conn.venue()) { case api::VENUE_ICE: case api::VENUE_SIMICE: - return std::make_unique(conn, *l, o); - case api::VENUE_GLBX: { - if (conn.use_ilink3()) - return std::make_unique( - conn, *l, o); - return std::make_unique(conn, *l, o); - } + return make_gw(conn, conn, *l, o); + case api::VENUE_GLBX: + if (conn.use_ilink3()) { + make_gw(conn, conn, *l, o); + } + return make_gw(conn, conn, *l, o); case api::VENUE_DERIBIT: - return std::make_unique(conn.venue(), o); - case api::VENUE_CBOE: { - std::unique_ptr adapter = - std::make_unique(o); - return std::make_unique( - conn.venue(), std::move(adapter), o); - } - case api::VENUE_OKX: { - return std::make_unique(o); - } + return make_gw(conn, conn.venue(), o); + case api::VENUE_CBOE: + return make_gw( + conn, conn.venue(), std::make_unique(o), o); + case api::VENUE_OKX: + return make_gw(conn, o); case api::VENUE_BINANCE: { auto cfg = parse_config_json(conn.name()); cfg.expand_env(); cfg.deduce_key_type(); if (cfg.use_cross_margin_api) { - return std::make_unique< - binance_execution::cross_margin::CrossMarginGateway>( - o, std::move(cfg), conn); + return make_gw( + conn, o, std::move(cfg), conn); } - return std::make_unique( - o, std::move(cfg), conn); + return make_gw( + conn, o, std::move(cfg), conn); } case api::VENUE_BINANCE_USDS_FUTURES: { auto cfg = @@ -111,12 +137,11 @@ struct ExecutionGatewayProvider::PImpl { "Config has 'use_cross_margin_api' set to true, but this is " "only supported for spots (using regular api)."); } - return std::make_unique< - binance_execution::usds_futures::UsdsFuturesGateway>( - o, std::move(cfg), conn); + return make_gw( + conn, o, std::move(cfg), conn); } default: - return std::make_unique(o); + return make_gw(conn, o); } } diff --git a/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.cpp b/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.cpp new file mode 100644 index 000000000..36088c15b --- /dev/null +++ b/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.cpp @@ -0,0 +1,598 @@ +#include "py_execution_gateway_adapter.h" +#include "python_core/py_contract_price_info.h" +#include "python_core/py_contract_specification.h" +#include "python_core/py_security.h" +#include "python_core/python_activator.h" +#include "python_execution/execution_gateway.h" +#include "python_execution/execution_gateway_bridge.h" +#include "python_execution/execution_gateway_bridge_impl.h" +#include "python_execution/py_cancel_order_request.h" +#include "python_execution/py_cancel_replace_order_request.h" +#include "python_execution/py_create_order_request.h" +#include "python_execution/py_execution_gateway.h" +#include "python_execution/py_execution_report.h" +#include "spark/api/domain/Venue.h" +#include "spark/api/service_helpers/AdminServiceUtils.h" +#include "spark/api/services/AdminService.pb.h" +#include "spark/api/services/OrderService.h" +#include "spark/api/services/exec_type.h" +#include "spark/api/services/native_order_status.h" +#include "spark/api/services/native_order_type.h" +#include "spark/api/services/time_in_force.h" +#include "spark/config/protos/jetfix.pb.h" +#include "spark/core/TimeStamp.h" +#include "spark/core/start_stop_state_machine.h" +#include "spark/domain/tick_utils.h" +#include "spark/domain_model/Security.h" +#include "spark/domain_model/Security.pb.h" +#include "spark/domain_model/SecurityType.h" +#include "spark/domain_model/Side.h" +#include "spark/domain_model/Venue.h" +#include "spark/domain_model/formatted_security.h" +#include "spark/io/json_formatter.h" +#include "spark/logging/logging.h" +#include "spark/logging/trace_log.h" +#include "spark/md/SecurityOracle.h" +#include "spark/mercury/events/Update.h" +#include "spark/orderman/CancelOrderMsg.h" +#include "spark/orderman/CancelReplaceOrderMsg.h" +#include "spark/orderman/CreateOrderMsg.h" +#include "spark/orderman/RFQMsg.h" +#include "spark/orderman/events/NewAdminDataEvent.h" +#include "spark/orderman/events/NewSecuritiesEvent.h" +#include "spark/orderman/gateways/IExecutionGateway.h" +#include "spark/orderman/log_messages/cancel_order_log.h" +#include "spark/orderman/log_messages/create_order_log.h" +#include "spark/orderman/log_messages/execution_report_log.h" +#include "spark/orderman/log_messages/modify_order_log.h" +#include "spark/orderman/orderman_utils/ExchangePosition.h" +#include "spark/orderman/orderman_utils/ExecutionReport.h" +#include "spark/orderman/orderman_utils/execution_report_store.h" +#include "spark/orderman/orderman_utils/orderman_common.h" +#include "spark/orderman/orderman_utils/simple_validation.h" +#include "spark/utils/PBUtils.h" +#include "spark/utils/bts_lock_guard.h" +#include "spark/utils/overloaded.h" +#include "spark/utils/stopwatch.h" +#include "spark/utils/string_utils.h" +#include "sparkd/execution/py_execution_gateway_config.h" + +#include +#include +#include +#include +#include + +namespace bts::orderman { + +#define ASSERT_FN(test, fn, ...) \ + bts_assert_msgf(test, "PyExecutionGatewayAdapter::" fn ". " __VA_ARGS__) +#define LOG_FN(level, fn, ...) \ + LOG(OrderMan, level, "PyExecutionGatewayAdapter::" 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__) + +#define _LOG_TRACE(level, name) \ + LOG_TRACE(OrderMan, level, std::string("py_exe_gw_adapt"), std::string(name)) +#define INFO_TRACE(name) _LOG_TRACE(bts::Info, name) +#define WARN_TRACE(name) _LOG_TRACE(bts::Warn, name) +#define ERROR_TRACE(name) _LOG_TRACE(bts::Error, name) + +#define _LOG_TRACE_PARAMS(level, name, params) \ + LOG_TRACE_PARAMS( \ + OrderMan, level, std::string("py_exe_gw_adapt"), std::string(name), \ + params) +#define DIAG_TRACE_PARAMS(name, params) \ + _LOG_TRACE_PARAMS(bts::Diag, name, params) +#define ERROR_TRACE_PARAMS(name, params) \ + _LOG_TRACE_PARAMS(bts::Error, name, params) + +#define INFO_TRACE_PARAMS(name, params) \ + LOG_TRACE_PARAMS( \ + OrderMan, bts::Info, std::string("py_exe_gw_adapt"), std::string(name), \ + params) + +using bts::Quantity; +using bts::api::security_type_parse_smart; +using bts::api::SecurityType; +using bts::api::Venue; +using bts::api::venue_parse_smart; +using bts::api::admin::BTSAccount; +using bts::api::orderman::exec_type_parse_smart; +using bts::api::orderman::native_order_status_parse_smart; +using bts::api::orderman::time_in_force_parse_smart; +using bts::core::Delegate; +using bts::core::StartStopStateMachine; +using bts::core::TimeStamp; +using bts::md::SecurityOracle; +using bts::orderman::CancelOrderMsg; +using bts::orderman::CancelReplaceOrderMsg; +using bts::orderman::CreateOrderMsg; +using bts::orderman::ExchangeOrderID64; +using bts::orderman::ExchangePosition; +using bts::orderman::ExecutionReport; +using bts::orderman::ExecutionReportStore; +using bts::orderman::NewAdminDataEvent; +using bts::orderman::NewSecuritiesEvent; +using bts::orderman::OrderKey; +using bts::orderman::OrderMsg; +using bts::orderman::RFQMsg; +using bts::system::string_utils::parse_uint; +using nlohmann::json; +using python_core::PythonActivatorT; +using python_execution::ExecutionGatewayBridgeImpl; +using python_execution::PyCancelOrderRequest; +using python_execution::PyCancelReplaceOrderRequest; +using python_execution::PyCreateOrderRequest; +using python_execution::PyExecutionGateway; +using std::int64_t; +using std::optional; +using std::shared_ptr; +using std::size_t; +using std::string; +using std::thread; +using std::uint32_t; +using std::uint64_t; +using std::vector; + +struct ExecutionGatewayCallbacks { + bts::orderman::OnExeReport exe_report; + bts::orderman::OnGwStatusChange gw_status_change; + bts::orderman::OnCancelReject cancel_reject; + bts::orderman::OnExchangePositionState exchange_position_state; + bts::orderman::OnExchangeOpenOrdersState exchange_open_orders; +}; + +struct PyExecutionGatewayAdapter::PImpl { + explicit PImpl( + bts::md::SecurityOracle sec_oracle, + PyExecutionGatewayConfig config, + bts::config::JetFIX::Connection jetfix_connection) + : sec_oracle(std::move(sec_oracle)), config(std::move(config)), + bridge( + jetfix_connection.name(), + this->config.gateway_type, + this->config.module_path), + jetfix_connection(std::make_shared( + std::move(jetfix_connection))), + orders(this->config.account, this->jetfix_connection) { + bts_assert(this->jetfix_connection->venue() != api::VENUE_UNSET); + bts_assert(!this->jetfix_connection->name().empty()); + pos.exchange = this->jetfix_connection->venue(); + sm.set_name(fmt::format( + "{}_py_gw", + string{bts::api::Venue_Name(this->jetfix_connection->venue())})); + sm.set_subsystem(bts::log::OrderMan); + sm.start_core_impl.bind<&PImpl::start_impl>(*this); + sm.stop_core_impl.bind<&PImpl::stop_impl>(*this); + } + + ~PImpl() { stop(); } + + enum RequestType { + ORDER, + POSITION, + }; + + SecurityOracle sec_oracle; + PyExecutionGatewayConfig config; + ExecutionGatewayBridgeImpl bridge; + optional> py_gw_activator; + shared_ptr jetfix_connection; + optional pos_snapshot_thread; + optional py_thread; + bool is_ready = false; + bool is_ready_dirty = false; + volatile bool py_keep_going = false; + uint32_t n_active = 0; + + StartStopStateMachine sm; + // SimpleOrderKeyMap key_map; + + ExecutionReportStore orders; + ExecutionGatewayCallbacks callbacks; + ExchangePosition pos; + BTSAccount account; + OnExeReport exe_report_callback; + + void to_exe_report( + bts::orderman::ExecutionReport &er, + const python_execution::PyExecutionReport &pyer, + std::function + find_sec) { + *er.order_key = pyer.key(); + er.account_name->copy_from(pyer.account()); + if (std::holds_alternative(er.exchange_order_id)) { + std::get(er.exchange_order_id) + ->copy_from(pyer.exchange_order_id()); + } else { + er.exchange_order_id = ExchangeOrderID{pyer.exchange_order_id()}; + } + native_order_type_parse_smart(pyer.order_type(), &er.order_type); + native_order_status_parse_smart(pyer.order_status(), &er.order_status); + time_in_force_parse_smart(pyer.time_in_force(), &er.time_in_force); + exec_type_parse_smart(pyer.exec_type(), &er.exec_type); + Venue venue; + bts_assert(venue_parse_smart(pyer.venue(), &venue)); + SecurityType sec_type; + bts_assert(security_type_parse_smart(pyer.security_type(), &sec_type)); + er.security = find_sec(venue, sec_type, pyer.exchange_security_id()); + er.side = pyer.is_buy() ? bts::api::SIDE_BUY : bts::api::SIDE_SELL; + *er.price = pyer.price(); + *er.stop_price = std::numeric_limits::quiet_NaN(); + er.quantity = Quantity::create_new(pyer.quantity()); + *er.avg_price = pyer.avg_filled_price(); + er.filled_quantity = Quantity::create_new(pyer.filled_quantity()); + *er.last_price = pyer.last_filled_price(); + er.last_shares = Quantity::create_new(pyer.last_filled_quantity()); + er.transact_time = + ExchangeTimeStamp64{static_cast(pyer.transact_time())}; + } + + void start() { + INFO_TRACE("start"); + sm.start(); + } + + // should not be called directly (use the state machine) + void start_impl() { + INFO_TRACE("start_impl"); + bts_assert(!py_thread); + py_keep_going = true; + py_thread.emplace([&]() { bridge.run_py(&py_keep_going); }); + } + + void stop() { + INFO_TRACE("stop"); + sm.stop(); + } + + void stop_impl() { + INFO_TRACE("stop_impl"); + py_keep_going = false; + if (py_thread) { + py_thread->join(); + py_thread.reset(); + } + } + + void create_order(const CreateOrderMsg &m) { + LOG_CREATE_ORDER(Info, m); + PyCreateOrderRequest py_req; + to_py(py_req, m); + bridge.on_order_msg( + std::make_shared(std::move(py_req))); + } + + void update_order(const CancelReplaceOrderMsg &m) { + LOG_MODIFY_ORDER(Info, m); + PyCancelReplaceOrderRequest py_req; + to_py(py_req, m); + bridge.on_order_msg( + std::make_shared(std::move(py_req))); + } + + void cancel_order(const CancelOrderMsg &m) { + LOG_CANCEL_ORDER(Info, m); + PyCancelOrderRequest req; + to_py(req, m); + bridge.on_order_msg( + std::make_shared(std::move(req))); + } + + void get_position_info() { + sm.invoke_if_active([&](auto) { + // + }); + } + + void dispatch_is_ready() { + BTS_LOCK_GUARD(sm.mutex()); + if (is_ready_dirty) { + is_ready_dirty = false; + callbacks.gw_status_change(is_ready); + } + } + + void from_py( + const python_execution::PyExecutionReport &py_er, + ExecutionReport &er) const { + *er.order_key = py_er.key(); + bts_assert(venue_parse_smart(py_er.venue(), &er.exchange)); + SecurityType sec_type; + bts_assert(security_type_parse_smart(py_er.security_type(), &sec_type)); + er.transact_time = + ExchangeTimeStamp64{static_cast(py_er.transact_time())}; + uint64_t exch_oid; + if (parse_uint(py_er.exchange_order_id(), exch_oid)) { + er.exchange_order_id.emplace().value() = exch_oid; + } else { + er.exchange_order_id.emplace().value() = + py_er.exchange_order_id(); + } + er.security = sec_oracle.get_security( + er.exchange, sec_type, py_er.exchange_security_id()); + er.leg_security = nullptr; + er.side = py_er.is_buy() ? api::SIDE_BUY : api::SIDE_SELL; + time_in_force_parse_smart(py_er.time_in_force(), &er.time_in_force); + native_order_type_parse_smart(py_er.order_type(), &er.order_type); + exec_type_parse_smart(py_er.exec_type(), &er.exec_type); + native_order_status_parse_smart(py_er.order_status(), &er.order_status); + er.manual_order_indicator = bts::api::orderman::MANUAL_ORDER_INDICATOR_NO; + er.price.value() = py_er.price(); + er.quantity = py_er.quantity(); + er.filled_quantity = py_er.filled_quantity(); + er.last_shares = py_er.last_filled_quantity(); + er.last_price.value() = py_er.last_filled_price(); + er.avg_price.value() = py_er.avg_filled_price(); + er.stop_price.value() = std::numeric_limits::quiet_NaN(); + const string &tx_id = py_er.transact_id(); + bts_assert(tx_id.size() < er.exchange_fill_id.value().size()); + bts::system::string_utils::copy_to_array<40>( + py_er.transact_id(), er.exchange_fill_id.value()); + } + + void to_py(PyCreateOrderRequest &py_req, const CreateOrderMsg &msg) { + py_req.set_key(msg.key.value()); + py_req.set_exchange_security_id(msg.security_name()); + py_req.set_venue(bts::api::venue_name_pretty(msg.venue())); + py_req.set_is_buy(msg.side == bts::api::SIDE_BUY); + py_req.set_price(msg.price.value()); + py_req.set_quantity(msg.quantity.full_value_float()); + py_req.set_order_type( + bts::api::orderman::native_order_type_name_pretty(msg.order_type)); + py_req.set_time_in_force( + bts::api::orderman::time_in_force_name_pretty(msg.time_in_force)); + } + + void to_py( + PyCancelReplaceOrderRequest &py_req, + const bts::orderman::CancelReplaceOrderMsg &msg) { + auto &cf = msg.create_fields; + py_req.set_key(cf.key.value()); + py_req.set_exchange_order_id( + std::to_string(msg.exchange_order_id.value())); + py_req.set_exchange_security_id(cf.security_name()); + py_req.set_venue(bts::api::venue_name_pretty(cf.venue())); + py_req.set_is_buy(cf.side == bts::api::SIDE_BUY); + py_req.set_price(cf.price.value()); + py_req.set_quantity(cf.quantity.full_value_float()); + } + + void to_py(PyCancelOrderRequest &py_req, const CancelOrderMsg &msg) { + py_req.set_key(msg.key.value()); + py_req.set_exchange_order_id( + std::to_string(msg.exchange_order_id.value())); + py_req.set_exchange_security_id(msg.security_name()); + py_req.set_venue(bts::api::venue_name_pretty(msg.venue())); + py_req.set_is_buy(msg.side == bts::api::SIDE_BUY); + } + + void dispatch_order_updates() { + BTS_LOCK_GUARD(sm.mutex()); + std::shared_ptr py_er_p; + utils::Stopwatch sw; + uint32_t n_dequed = 0; + uint32_t n_invalid = 0; + sw.start(); + while (bridge.pop_exe_report(py_er_p)) { + n_dequed++; + const python_execution::PyExecutionReport py_er = *py_er_p; + shared_ptr er_p = + orders.update(OrderKey{py_er.key()}, [&](auto &er_p, bool) { + from_py(py_er, *er_p); + }); + const ExecutionReport &er = *er_p; + string error; + if (!validate(er, error)) { + LOG_EXECUTION_REPORT(Error, er_p, "INVALID_STATE", error); + n_invalid++; + continue; + } + LOG_EXECUTION_REPORT(Info, er_p); + switch (er.order_status) { + case api::orderman::NATIVE_ORDER_STATUS_FILLED: + case api::orderman::NATIVE_ORDER_STATUS_CANCELED: + case api::orderman::NATIVE_ORDER_STATUS_REJECTED: { + orders.erase(er.order_key); + INFO_FN( + "dispatch_order_updates", + "Order reached terminal state {} (id={})", er.order_status, + er.exchange_order_id); + break; + } + default: + break; + } + INFO_FN( + "dispatch_order_updates", + "Firing exe report callback. {} {} {} @ {} {} (filled {}/{}, " + "id={}). {} active orders", + er.side, er.security_name(), er.quantity, er.price, + er.order_status, er.filled_quantity, er.quantity, er.order_key, + orders.size()); + callbacks.exe_report(er_p, {}); + } + sw.stop(); + if (n_dequed > 0) { + INFO( + R"([py_exe_gw_disp_ord_stats.json]{{ "n_active": {}, "n_dequed": {}, "n_invalid": {}, "dur": {}, "ts": {} }})", + orders.size(), n_dequed, n_invalid, sw.total_elapsed().nanos(), + TimeStamp::now_ns()); + } + } +}; + +PyExecutionGatewayAdapter::PyExecutionGatewayAdapter( + SecurityOracle sec_oracle, + PyExecutionGatewayConfig session_cfg, + bts::config::JetFIX::Connection jetfix_connection) + : me(std::make_unique( + std::move(sec_oracle), + std::move(session_cfg), + std::move(jetfix_connection))) { + bts_assert( + me->config.account.size() <= + ExecutionReport{}.account_name.value().max_size()); +} + +PyExecutionGatewayAdapter::~PyExecutionGatewayAdapter() = default; + +void PyExecutionGatewayAdapter::start() { me->start(); } + +void PyExecutionGatewayAdapter::on_securities( + const bts::mercury::Update & /*update*/) { + INFO_FN( + "on_securities", "t_id: {} t_name: {}", bts::os::get_thread_id(), + bts::os::get_thread_name()); + std::vector secs = + me->sec_oracle.get_securities([&](const bts::api::Security &sec) { + return sec.exchange() == me->jetfix_connection->venue(); + }); + std::vector> py_secs; + for (const auto *sec : secs) { + bts::md::py_interop::PySecurity py_sec; + py_sec.set_id(sec->id()); + py_sec.set_asset(sec->symbol()); + py_sec.set_venue(bts::api::venue_name_pretty(sec->exchange())); + py_sec.set_currency(sec->currency()); + // Exchange ID and name + std::string name = bts::securities::descriptor(*sec); + py_sec.set_exchange_id(name); + py_sec.set_name(std::move(name)); + // Contract spec + md::py_interop::PyContractSpecification py_spec; + md::py_interop::PyContractPriceInfo &py_price_info = + py_spec.mutable_price_infos().emplace_back(); + float tick_unit; + float tick_base; + if (!domain::get_tick_factors( + sec->contract_spec(), tick_unit, tick_base)) { + WARN_FN( + "on_securities", "Security {} {} has invalid contract spec: {}. ", + sec->exchange(), bts::securities::descriptor(*sec), + utils::pb::to_string(sec->contract_spec())); + tick_unit = 0.01f; + tick_base = 0.01f; + } + py_price_info.set_tick_unit(tick_unit); + py_price_info.set_tick_base(tick_base); + py_sec.set_contract_spec(std::move(py_spec)); + // Spot/Future/Option + switch (sec->Contract_case()) { + case bts::api::Security::kSpot: { + py_sec.set_spot(bts::md::py_interop::PySpot{}); + break; + } + case bts::api::Security::kFuture: { + const bts::api::FutureContract &fut = sec->future(); + bts::md::py_interop::PyFuture py_fut; + py_fut.set_expiration(fmt::format( + "{}-{:02}-{:02}", fut.expiration_year(), fut.expiration_month(), + fut.expiration_day())); + py_sec.set_future(std::move(py_fut)); + break; + } + case bts::api::Security::kOption: { + const bts::api::OptionContract &opt = sec->option(); + bts::md::py_interop::PyOption py_opt; + py_opt.set_expiration(fmt::format( + "{}-{:02}-{:02}", opt.expiration_year(), opt.expiration_month(), + opt.expiration_day())); + py_opt.set_strike(opt.strike()); + py_opt.set_is_call(opt.call_put() == bts::api::PUTORCALL_CALL); + py_sec.set_option(std::move(py_opt)); + break; + } + default: + bts_assert_msg(false, "Only spots, futures, and options supported"); + break; + } + py_secs.push_back( + std::make_shared(std::move(py_sec))); + } + me->bridge.on_securities(std::move(py_secs)); +} + +void PyExecutionGatewayAdapter::on_admin_data( + const bts::mercury::Update &update) { + INFO_FN( + "on_admin_data", "t_id: {} t_name: {}", bts::os::get_thread_id(), + bts::os::get_thread_name()); + if (update.events == nullptr) { + return; + } + std::lock_guard lock{me->sm.mutex()}; + const auto *account = bts::admin::AdminServiceUtils::find_account( + *update.events->back().admin_data, me->config.account); + if (account == nullptr) { + WARN_FN( + "on_admin_data", + "Gateway account not found. Cannot execute orders. name: '{}'", + me->config.account); + return; + } + if (me->account.name() == account->name() && + me->account.id() == account->id()) { + return; + } + me->account.CopyFrom(*account); + INFO_FN("on_admin_data", "Resolved gateway account '{}'", account->name()); +} + +void PyExecutionGatewayAdapter::send_msgs( + vector const &msg_vec, bts::trace::CorID) { + INFO_FN("send_msgs", "count: {}", msg_vec.size()); + for (const auto &msg : msg_vec) { + std::visit( + bts::overloaded{ + [&](const CreateOrderMsg &m) { me->create_order(m); }, + [&](const CancelReplaceOrderMsg &m) { me->update_order(m); }, + [&](const CancelOrderMsg &m) { me->cancel_order(m); }, + [&](const RFQMsg &) { + bts_assert_msg( + false, "PyExecutionGatewayAdapter RFQ not implemented"); + }, + }, + msg); + } +} + +void PyExecutionGatewayAdapter::send_fix( + const bts::jetfix::OutFIXPtr &, bts::trace::CorID) { + bts_assert_msg(false, "ExecutionGateway does not support fix"); +} + +void PyExecutionGatewayAdapter::dispatch_incoming_fix_messages() { + me->dispatch_is_ready(); + me->dispatch_order_updates(); +} + +// Callbacks +bts::orderman::OnExeReport &PyExecutionGatewayAdapter::on_exe_report() { + return me->callbacks.exe_report; +} +bts::orderman::OnGwStatusChange & +PyExecutionGatewayAdapter::on_gw_status_change() { + return me->callbacks.gw_status_change; +} +bts::orderman::OnCancelReject &PyExecutionGatewayAdapter::on_cancel_reject() { + return me->callbacks.cancel_reject; +} +bts::orderman::OnExchangePositionState & +PyExecutionGatewayAdapter::on_exchange_position_state() { + return me->callbacks.exchange_position_state; +} +bts::orderman::OnExchangeOpenOrdersState & +PyExecutionGatewayAdapter::on_exchange_open_orders() { + return me->callbacks.exchange_open_orders; +} + +} // namespace bts::orderman diff --git a/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.h b/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.h new file mode 100644 index 000000000..9e5e85d81 --- /dev/null +++ b/src/app_sparkd/sparkd/execution/py_execution_gateway_adapter.h @@ -0,0 +1,45 @@ +#pragma once + +#include "spark/config/protos/jetfix.pb.h" +#include "spark/md/SecurityOracle.h" +#include "spark/orderman/gateways/IExecutionGateway.h" + +#include + +namespace bts::orderman { + +struct PyExecutionGatewayConfig; + +class PyExecutionGatewayAdapter : public bts::orderman::IExecutionGateway { + public: + explicit PyExecutionGatewayAdapter( + bts::md::SecurityOracle sec_oracle, + PyExecutionGatewayConfig session_cfg, + bts::config::JetFIX::Connection jetfix_connection); + ~PyExecutionGatewayAdapter() override; + + void start() override; + void dispatch_incoming_fix_messages() override; + void on_securities( + const bts::mercury::Update &) + override; + void on_admin_data( + const bts::mercury::Update &) override; + void send_fix(const bts::jetfix::OutFIXPtr &, bts::trace::CorID) override; + void send_msgs( + std::vector const &, + bts::trace::CorID) override; + + bts::orderman::OnExeReport &on_exe_report() override; + bts::orderman::OnGwStatusChange &on_gw_status_change() override; + bts::orderman::OnCancelReject &on_cancel_reject() override; + bts::orderman::OnExchangePositionState & + on_exchange_position_state() override; + bts::orderman::OnExchangeOpenOrdersState &on_exchange_open_orders() override; + + private: + struct PImpl; + std::unique_ptr me; +}; + +} // namespace bts::orderman diff --git a/src/app_sparkd/sparkd/execution/py_execution_gateway_config.h b/src/app_sparkd/sparkd/execution/py_execution_gateway_config.h new file mode 100644 index 000000000..ea1e15e7c --- /dev/null +++ b/src/app_sparkd/sparkd/execution/py_execution_gateway_config.h @@ -0,0 +1,44 @@ +#pragma once + +#include "spark/api/domain/Venue.pb.h" + +#include +#include +#include + +namespace bts::orderman { + +struct PyExecutionGatewayConfig { + std::string gateway_type; + std::string account; + std::vector module_path; + api::domain::Venue venue; +}; + +inline void to_json(nlohmann::json &j, const PyExecutionGatewayConfig &cfg) { + j["gateway_type"] = cfg.gateway_type; + j["account"] = cfg.account; + j["module_path"] = cfg.module_path; + j["venue"] = cfg.venue; +} + +inline void from_json(const nlohmann::json &j, PyExecutionGatewayConfig &cfg) { + auto it = j.find("gateway_type"); + if (it != j.end()) { + it->get_to(cfg.gateway_type); + } + it = j.find("account"); + if (it != j.end()) { + it->get_to(cfg.account); + } + it = j.find("module_path"); + if (it != j.end()) { + it->get_to(cfg.module_path); + } + it = j.find("venue"); + if (it != j.end()) { + it->get_to(cfg.venue); + } +} + +} // namespace bts::orderman diff --git a/src/lib_python_execution/CMakeLists.txt b/src/lib_python_execution/CMakeLists.txt new file mode 100644 index 000000000..3d58fb471 --- /dev/null +++ b/src/lib_python_execution/CMakeLists.txt @@ -0,0 +1,19 @@ +cmake_minimum_required(VERSION 3.23) +project(python_execution) +include(${CMAKE_SOURCE_DIR}/cmake/InitLibrary.cmake) +include(${CMAKE_SOURCE_DIR}/cmake/InitPythonModule.cmake) +include(${CMAKE_SOURCE_DIR}/cmake/InitPythonPlugin.cmake) + +# Find Python from the virtual environment +find_package(Python3 REQUIRED COMPONENTS Interpreter Development) +find_package(pybind11 REQUIRED) +# Shared lib (for c++ to link) +init_library(SHARED) +target_include_directories(${PROJECT_NAME} PUBLIC ${Python3_INCLUDE_DIRS}) +target_link_directories(${PROJECT_NAME} PUBLIC ${Python3_LIBRARY_DIRS}) +target_link_libraries(${PROJECT_NAME} PUBLIC spark python_core pybind11::embed + ${Python3_LIBRARIES}) +# CPython module (for .py files to import) +init_python_module() +# Py plugin (for sparkd to load at runtime) +init_python_plugin(PLUGIN_NAME python_execution_gateways) diff --git a/src/lib_python_execution/Config.cmake.in b/src/lib_python_execution/Config.cmake.in new file mode 100644 index 000000000..8cd046cf0 --- /dev/null +++ b/src/lib_python_execution/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@_gatewaysTargets.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@_gateways) diff --git a/src/lib_python_execution/README.md b/src/lib_python_execution/README.md new file mode 100644 index 000000000..10b72436e --- /dev/null +++ b/src/lib_python_execution/README.md @@ -0,0 +1,112 @@ + + +[pybind11]: https://github.com/pybind/pybind11 +[lib_spark]: ../lib_spark/README.md + +# lib_python_execution + +This library binds c++ execution gateways to python modules which can be loaded at runtime. + +## **Dependencies** + +* **[Pybind11][pybind11]** +* **[lib_spark][lib_spark]** + +## Notes + +* Because this is *python*, order/security enums 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: + + | Enum | Examples | + |------|---------| + | **OrderType** | "LIMIT", "MARKET" | + | **OrderStatus** | "NEW", "PARTIALLY_FILLED", "FILLED", "CANCELED" | + | **SecurityType** | "SPOT", "FUTURE", "OPTION" | + | **Venue** | "BYBIT", "GATEIO", "DERIBIT", "COINBASE" | + | **Side** | "BUY", "SELL" | + +* All .py files in the `python_execution_gateways` dir are copied to a special plugins directory + at build time, so they may be loaded at runtime. +* For intellisense, symlink the *.so* and *.pyi* files in the `python_execution_gateways` dir + > *These files are excluded from source control via .gitignore, so don't worry about accidentally checking them in* +```bash +# Run in src/lib_python_execution/python_execution_gateways +ln -s ../../../build/sparkd-debug-clang/src/lib_python_execution/stubs/python_execution_module.pyi . +ln -s ../../../build/sparkd-debug-clang/src/lib_python_execution/python_execution_module.cpython-310-x86_64-linux-gnu.so . +``` + + +## Example +```python +import json +import logging +import threading +from typing import Optional +import python_execution_module as pyexe +from py_execution_utils import configure_logger, run_websocket + + +class ExecutionGatewayExample(pyexe.ExecutionGateway): + def __init__(self): + super(ExecutionGatewayExample, self).__init__() + self.bridge: Optional[pyexe.ExecutionGatewayBridge] = None + self.stop_event = threading.Event() + # Logs to file /home/bts/sparkdata/data/logging.sparkd/_log + # (name is 'py_execution_example' in this case). + self.logger = configure_logger(logging.getLogger("py_execution_example")) + + def start_impl(self, bridge: pyexe.ExecutionGatewayBridge): + def on_message(msg: str): + # This example assumes msg has a particular structure. Obviously, each exchange is + # different, so this isn't a one-size-fits-all solution. + data = json.loads(msg) + event = data.get("e") + if event == "executionReport": + upd = json.loads(str(msg)) + er = pyexe.PyExecutionReport() + # TODO: Resolve exch key to bts key + # er.set_key(bts_key) + er.set_exchange_security_id(upd["s"]) + er.set_security_type("SPOT") + er.set_is_buy(upd["S"] == "BUY") + er.set_price(float(upd["p"])) + er.set_quantity(float(upd["q"])) + er.set_last_filled_price(upd["L"]) + er.set_last_filled_quantity(upd["l"]) + # ... + # TODO: Fill in remaining fields + bridge.on_execution_report(er) + else: + self.logger.error("Unknown event %s. Full msg %s" % (event, msg)) + + run_websocket( + "wss://some_exch.com/ws", self.stop_event, self.logger, on_message + ) + + def start(self, bridge: pyexe.ExecutionGatewayBridge): + # Connect to the exchange, subscribe to order updates, etc. Don't block this thread. + # Spawn new thread(s) for long running operations websocket msg loops, ping loops, etc. + self.logger.info("Starting ExecutionGatewayExample") + self.bridge = bridge + self.ws_thread = threading.Thread(target=lambda: self.start_impl(bridge)) + self.ws_thread.start() + + def stop(self): + self.logger.info("Stopping ExecutionGatewayExample") + self.stop_event.set() + + def create_order(self, req: pyexe.PyCreateOrderRequest): + self.logger.info("create_order. %s" % str(req)) + # TODO: Send REST or ws request + + def cancel_replace_order(self, req: pyexe.PyCancelReplaceOrderRequest): + self.logger.info("cancel_replace_order. %s" % str(req)) + # TODO: Send REST or ws request + + def cancel_order(self, req: pyexe.PyCancelOrderRequest): + self.logger.info("cancel_order. %s" % str(req)) + # TODO: Send REST or ws request + +``` diff --git a/src/lib_python_execution/pyrightconfig.json b/src/lib_python_execution/pyrightconfig.json new file mode 100644 index 000000000..1cc374d36 --- /dev/null +++ b/src/lib_python_execution/pyrightconfig.json @@ -0,0 +1,20 @@ +{ + "include": [ + ".", + ], + "exclude": [ + "**/__pycache__" + ], + "reportMissingImports": true, + "reportMissingTypeStubs": false, + "stubPath": "../../build/sparkd-debug-clang/src/lib_python_execution/stubs", + "extraPaths": [ + "../lib_python_core/python_core_plugins", + "../../build/sparkd-debug-clang/src/lib_python_core/stubs", + ], + "pythonVersion": "3.10", + "pythonPlatform": "Linux", + "typeCheckingMode": "basic", + "venvPath": "../../", + "venv": ".venv" +} diff --git a/src/lib_python_execution/python_execution/execution_gateway.cpp b/src/lib_python_execution/python_execution/execution_gateway.cpp new file mode 100644 index 000000000..780e9365d --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway.cpp @@ -0,0 +1,7 @@ +#include "execution_gateway.h" + +namespace python_execution { + +ExecutionGateway::~ExecutionGateway() = default; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/execution_gateway.h b/src/lib_python_execution/python_execution/execution_gateway.h new file mode 100644 index 000000000..e8b5a0013 --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway.h @@ -0,0 +1,25 @@ +#pragma once + +#include "python_core/py_security.h" +#include "python_execution/execution_gateway_bridge.h" +#include "python_execution/py_cancel_order_request.h" +#include "python_execution/py_cancel_replace_order_request.h" +#include "python_execution/py_create_order_request.h" + +namespace python_execution { + +class ExecutionGateway { + public: + virtual ~ExecutionGateway(); + virtual void start(ExecutionGatewayBridge *bridge) = 0; + virtual void create_order(std::shared_ptr req) = 0; + virtual void cancel_order(std::shared_ptr req) = 0; + virtual void cancel_replace_order( + std::shared_ptr req) = 0; + virtual void on_securities( + const std::vector> + &securities) = 0; + virtual void stop() = 0; +}; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/execution_gateway_bridge.cpp b/src/lib_python_execution/python_execution/execution_gateway_bridge.cpp new file mode 100644 index 000000000..dfc0c8498 --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway_bridge.cpp @@ -0,0 +1,7 @@ +#include "execution_gateway_bridge.h" + +namespace python_execution { + +ExecutionGatewayBridge::~ExecutionGatewayBridge() = default; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/execution_gateway_bridge.h b/src/lib_python_execution/python_execution/execution_gateway_bridge.h new file mode 100644 index 000000000..8b334c21b --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway_bridge.h @@ -0,0 +1,17 @@ +#pragma once + +#include "python_execution/py_execution_report.h" +#include "python_execution/py_position_info.h" + +namespace python_execution { + +class ExecutionGatewayBridge { + public: + virtual ~ExecutionGatewayBridge(); + // Python interface + virtual void on_execution_report(std::shared_ptr) {} + virtual void on_position_info(std::shared_ptr) {} + virtual void on_is_ready(bool) {} +}; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.cpp b/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.cpp new file mode 100644 index 000000000..ca6d676c8 --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.cpp @@ -0,0 +1,192 @@ +#include "python_execution/execution_gateway_bridge_impl.h" +#include "python_core/python_activator.h" +#include "python_core/python_interpreter.h" +#include "python_execution/execution_gateway.h" +#include "python_execution/py_cancel_order_request.h" +#include "python_execution/py_create_order_request.h" +#include "python_execution/py_position_info.h" +#include "spark/core/TimeSpan.h" +#include "spark/io/json_formatter.h" +#include "spark/logging/logging.h" +#include "spark/logging/trace_log.h" +#include "spark/logging/trace_log_var.h" +#include "spark/orderman/OrderMsg.h" +#include "spark/orderman/log_messages/execution_report_log.h" +#include "spark/orderman/orderman_utils/ExecutionReport.h" +#include "spark/utils/stopwatch.h" + +#include + +using std::shared_ptr; + +namespace py = pybind11; + +namespace python_execution { + +using bts::core::Delegate; +using bts::core::TimeSpan; +using bts::io::json_formatter; +using bts::orderman::RFQMsg; +using python_core::PythonActivatorT; +using std::string; +using std::vector; + +#define ASSERT_FN(test, fn, ...) \ + bts_assert_msgf(test, "exe_gw_bridge::" fn ". " __VA_ARGS__) +#define LOG_FN(level, fn, ...) \ + LOG(OrderMan, level, "exe_gw_bridge::" 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__) + +#define _LOG_TRACE(level, name) \ + LOG_TRACE(OrderMan, level, std::string("exe_gw_bridge"), std::string(name)) +#define INFO_TRACE(name) _LOG_TRACE(bts::Info, name) +#define WARN_TRACE(name) _LOG_TRACE(bts::Warn, name) +#define ERROR_TRACE(name) _LOG_TRACE(bts::Error, name) + +#define INFO_TRACE_PARAMS(name, params) \ + LOG_TRACE_PARAMS( \ + OrderMan, bts::Info, std::string("exe_gw_bridge"), std::string(name), \ + params) + +#define WARN_TRACE_PARAMS(name, params) \ + LOG_TRACE_PARAMS( \ + OrderMan, bts::Warn, std::string("exe_gw_bridge"), std::string(name), \ + params) + +ExecutionGatewayBridgeImpl::ExecutionGatewayBridgeImpl( + string name, string target, vector module_paths) + : name(std::move(name)), target(std::move(target)), + module_paths(std::move(module_paths)) {} + +void ExecutionGatewayBridgeImpl::on_order_msg(PyOrderRequest msg) { + INFO_TRACE("on_order_msg"); + outgoing_reqs.push(std::move(msg)); +} + +void ExecutionGatewayBridgeImpl::on_execution_report( + std::shared_ptr er) { + INFO_TRACE_PARAMS("on_execution_report", er->to_string()); + incoming_exe_reports.push(std::move(er)); +} + +void ExecutionGatewayBridgeImpl::on_position_info( + std::shared_ptr pi) { + INFO_TRACE_PARAMS("on_execution_report", pi->to_string()); + incoming_pos_infos.push(std::move(pi)); +} + +void ExecutionGatewayBridgeImpl::on_is_ready(bool value) { + INFO_TRACE_PARAMS("on_is_ready", json_formatter(value)); + is_ready.set_value_if_changed(value); +} + +bool ExecutionGatewayBridgeImpl::wait_for_ready(TimeSpan timeout) { + is_ready.wait_for_until_value(timeout, true); + return is_ready.value(); +} + +bool ExecutionGatewayBridgeImpl::pop_exe_report( + shared_ptr &result) { + auto res = incoming_exe_reports.pop(); + if (res) { + result = std::move(*res); + return true; + } + result = nullptr; + return false; +} + +void ExecutionGatewayBridgeImpl::on_securities( + std::vector> securities) { + INFO_TRACE_PARAMS( + "on_securities", + json_formatter( + fmt::format("Received {} securities", this->securities.size()))); + this->securities = std::move(securities); + this->is_securities_dirty = true; +} + +shared_ptr +ExecutionGatewayBridgeImpl::pop_exe_report() { + auto res = incoming_exe_reports.pop(); + return res ? *res : nullptr; +} + +int ExecutionGatewayBridgeImpl::run_py(volatile bool *keep_going) { + INFO_TRACE_PARAMS("run_py", json_formatter("Begin")); + bts_assert(keep_going != nullptr); + PythonActivatorT gw_activator{target, module_paths}; + gw = gw_activator.get_target( + [&](ExecutionGateway &local_gw) { local_gw.start(this); }, name); + INFO_TRACE_PARAMS("run_py", json_formatter("Waiting for ready...")); + auto sw = bts::utils::Stopwatch::start_new(); + while (!wait_for_ready(TimeSpan::from_seconds(1)) && *keep_going) { + INFO_TRACE_PARAMS( + "run", json_formatter(fmt::format( + "PyExecutionGateway still not ready after {:.2f}s", + sw.total_elapsed().total_seconds()))); + } + while (is_ready.value() && *keep_going) { + INFO_TRACE_PARAMS("run_py", json_formatter("Waiting for request...")); + if (is_securities_dirty) { + INFO_TRACE_PARAMS( + "run_py", + json_formatter(fmt::format( + "Sending {} securities to py gw", securities.size()))); + python_core::PythonInterpreter::exec( + [&]() { gw->on_securities(securities); }); + is_securities_dirty = false; + } + auto req = outgoing_reqs.wait_for_until_pop( + bts::core::TimeSpan::from_seconds(1)); + if (!req) { + continue; + } + INFO_TRACE_PARAMS( + "run_py", json_formatter("Forwarding request to py gateway")); + enum ReqType { CREATE = 0, CANCEL_REPLACE = 1, CANCEL = 2 }; + static const std::string req_type_names[]{"CREATE", "CXL_REP", "CXL"}; + ReqType req_type; + sw.restart(); + python_core::PythonInterpreter::exec([&]() { + std::visit( + bts::overloaded{ + [&](std::shared_ptr req) { + req_type = ReqType::CREATE; + gw->create_order(std::move(req)); + }, + [&](std::shared_ptr req) { + req_type = ReqType::CANCEL_REPLACE; + gw->cancel_replace_order(std::move(req)); + }, + [&](std::shared_ptr req) { + req_type = ReqType::CANCEL; + gw->cancel_order(std::move(req)); + }, + [&](const RFQMsg &) { + bts_assert_msg(false, "RFQ not implemented"); + }, + }, + *req); + }); + sw.stop(); + INFO_TRACE_PARAMS( + "run_py", + fmt::format( + R"({{ "typ": "{}", "hndl_dur": "{:.3f}ms" }})", + req_type_names[req_type], sw.total_elapsed().total_millis())); + } + python_core::PythonInterpreter::exec([&]() { gw->stop(); }); + return 0; +} + +ExecutionGatewayBridgeImpl::~ExecutionGatewayBridgeImpl() = default; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.h b/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.h new file mode 100644 index 000000000..795c4e6b9 --- /dev/null +++ b/src/lib_python_execution/python_execution/execution_gateway_bridge_impl.h @@ -0,0 +1,55 @@ +#pragma once + +#include "python_core/py_security.h" +#include "python_execution/execution_gateway.h" +#include "python_execution/execution_gateway_bridge.h" +#include "python_execution/py_execution_report.h" +#include "python_execution/py_order_request.h" +#include "python_execution/py_position_info.h" +#include "spark/collections/concurrent_queue.h" +#include "spark/utils/Delegate.h" +#include "spark/utils/concurrent_value_store.h" + +namespace python_execution { + +class ExecutionGatewayBridgeImpl : public ExecutionGatewayBridge { + public: + ExecutionGatewayBridgeImpl( + std::string name, + std::string target, + std::vector module_paths); + ~ExecutionGatewayBridgeImpl() override; + + // Python interface + void on_execution_report(std::shared_ptr) override; + void on_position_info(std::shared_ptr) override; + void on_is_ready(bool) override; + + // C++ interface + bts::core::Delegate)> & + exe_report_callback(); + void on_order_msg(PyOrderRequest msg); + void on_securities( + std::vector> + securities); + bool wait_for_ready(bts::core::TimeSpan timeout); + bool pop_exe_report(std::shared_ptr &result); + std::shared_ptr pop_exe_report(); + int run_py(volatile bool *keep_going); + + private: + std::string name; + std::string target; + std::vector module_paths; + bts::utils::ConcurrentValueStore is_ready; + bts::collections::ConcurrentQueue> + incoming_exe_reports; + bts::collections::ConcurrentQueue> + incoming_pos_infos; + bts::collections::ConcurrentQueue outgoing_reqs; + std::vector> securities; + volatile bool is_securities_dirty = false; + ExecutionGateway *gw; +}; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_cancel_order_request.cpp b/src/lib_python_execution/python_execution/py_cancel_order_request.cpp new file mode 100644 index 000000000..7ade575d9 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_cancel_order_request.cpp @@ -0,0 +1,68 @@ +#include "py_cancel_order_request.h" +#include "spark/domain_model/Venue.h" +#include "spark/orderman/CancelOrderMsg.h" + +#include + +namespace python_execution { + +using std::string; +using std::uint32_t; + +uint32_t PyCancelOrderRequest::key() const { return key_; } +void PyCancelOrderRequest::set_key(uint32_t value) { key_ = value; } + +const string &PyCancelOrderRequest::exchange_order_id() const { + return exchange_order_id_; +} +void PyCancelOrderRequest::set_exchange_order_id(string value) { + exchange_order_id_ = std::move(value); +} + +const string &PyCancelOrderRequest::exchange_security_id() const { + return exchange_security_id_; +} +void PyCancelOrderRequest::set_exchange_security_id(string value) { + exchange_security_id_ = std::move(value); +} + +const string &PyCancelOrderRequest::venue() const { return venue_; } +void PyCancelOrderRequest::set_venue(string value) { + venue_ = std::move(value); +} + +bool PyCancelOrderRequest::is_buy() const { return is_buy_; } +void PyCancelOrderRequest::set_is_buy(bool value) { + is_buy_ = std::move(value); +} + +void to_json(nlohmann::json &j, const PyCancelOrderRequest &req) { + j["key"] = req.key(); + j["eoid"] = req.exchange_order_id(); + j["esid"] = req.exchange_security_id(); + j["venue"] = req.venue(); + j["side"] = req.is_buy() ? 'B' : 'S'; +} + +void from_json(const nlohmann::json &j, PyCancelOrderRequest &req) { + j.at("key").get_to(req.key_); + j.at("eoid").get_to(req.exchange_order_id_); + j.at("esid").get_to(req.exchange_security_id_); + j.at("venue").get_to(req.venue_); + const auto str = j.at("side").get(); + if (!str.empty()) { + switch (str[0]) { + case 'S': + case 's': + case 'A': + case 'a': + req.is_buy_ = false; + break; + case 'B': + case 'b': + req.is_buy_ = true; + } + } +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_cancel_order_request.h b/src/lib_python_execution/python_execution/py_cancel_order_request.h new file mode 100644 index 000000000..7ff5de6ed --- /dev/null +++ b/src/lib_python_execution/python_execution/py_cancel_order_request.h @@ -0,0 +1,94 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" +#include +#include +#include + +namespace bts::orderman { +struct CancelOrderMsg; +} + +namespace python_execution { + +class PyCancelOrderRequest { + public: + std::uint32_t key() const; + void set_key(std::uint32_t value); + + const std::string &exchange_order_id() const; + void set_exchange_order_id(std::string value); + + const std::string &exchange_security_id() const; + void set_exchange_security_id(std::string value); + + const std::string &venue() const; + void set_venue(std::string value); + + bool is_buy() const; + void set_is_buy(bool value); + + void set_data( + std::uint32_t key, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + bool is_buy); + + std::string to_string() const; + + private: + std::uint32_t key_; + std::string exchange_order_id_; + std::string exchange_security_id_; + std::string venue_; + bool is_buy_; + + friend void from_json(const nlohmann::json &j, PyCancelOrderRequest &req); +}; + +void to_json(nlohmann::json &j, const PyCancelOrderRequest &req); +void from_json(const nlohmann::json &j, PyCancelOrderRequest &req); + +std::ostream &operator<<( + std::ostream &out, const PyCancelOrderRequest &req) noexcept; + +} // namespace python_execution + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + python_execution::PyCancelOrderRequest, + r, + "{}", + bts::io::json_formatter(r)); + +namespace python_execution { + +inline void PyCancelOrderRequest::set_data( + std::uint32_t key, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + bool is_buy) { + key_ = key; + exchange_order_id_ = std::move(exchange_order_id); + exchange_security_id_ = std::move(exchange_security_id); + venue_ = std::move(venue); + is_buy_ = is_buy; +} + +inline std::string PyCancelOrderRequest::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyCancelOrderRequest &req) noexcept { + out << fmt::format("{}", req); + return out; +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_cancel_replace_order_request.cpp b/src/lib_python_execution/python_execution/py_cancel_replace_order_request.cpp new file mode 100644 index 000000000..dc8566fd5 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_cancel_replace_order_request.cpp @@ -0,0 +1,80 @@ +#include "py_cancel_replace_order_request.h" +#include "spark/domain_model/Venue.h" +#include "spark/orderman/CancelReplaceOrderMsg.h" + +#include + +namespace python_execution { + +using std::string; +using std::uint32_t; + +uint32_t PyCancelReplaceOrderRequest::key() const { return key_; } +void PyCancelReplaceOrderRequest::set_key(uint32_t value) { key_ = value; } + +const string &PyCancelReplaceOrderRequest::exchange_order_id() const { + return exchange_order_id_; +} +void PyCancelReplaceOrderRequest::set_exchange_order_id(string value) { + exchange_order_id_ = std::move(value); +} + +const string &PyCancelReplaceOrderRequest::exchange_security_id() const { + return exchange_security_id_; +} +void PyCancelReplaceOrderRequest::set_exchange_security_id(string value) { + exchange_security_id_ = std::move(value); +} + +const string &PyCancelReplaceOrderRequest::venue() const { return venue_; } +void PyCancelReplaceOrderRequest::set_venue(string value) { + venue_ = std::move(value); +} + +bool PyCancelReplaceOrderRequest::is_buy() const { return is_buy_; } +void PyCancelReplaceOrderRequest::set_is_buy(bool value) { + is_buy_ = std::move(value); +} + +float PyCancelReplaceOrderRequest::price() const { return price_; } +void PyCancelReplaceOrderRequest::set_price(float value) { price_ = value; } + +float PyCancelReplaceOrderRequest::quantity() const { return quantity_; } +void PyCancelReplaceOrderRequest::set_quantity(float value) { + quantity_ = value; +} + +void to_json(nlohmann::json &j, const PyCancelReplaceOrderRequest &req) { + j["key"] = req.key(); + j["eoid"] = req.exchange_order_id(); + j["esid"] = req.exchange_security_id(); + j["venue"] = req.venue(); + j["side"] = req.is_buy() ? 'B' : 'S'; + j["px"] = req.price(); + j["qty"] = req.quantity(); +} + +void from_json(const nlohmann::json &j, PyCancelReplaceOrderRequest &req) { + j.at("key").get_to(req.key_); + j.at("eoid").get_to(req.exchange_order_id_); + j.at("esid").get_to(req.exchange_security_id_); + j.at("venue").get_to(req.venue_); + const auto str = j.at("side").get(); + if (!str.empty()) { + switch (str[0]) { + case 'S': + case 's': + case 'A': + case 'a': + req.is_buy_ = false; + break; + case 'B': + case 'b': + req.is_buy_ = true; + } + } + j.at("px").get_to(req.price_); + j.at("qty").get_to(req.quantity_); +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_cancel_replace_order_request.h b/src/lib_python_execution/python_execution/py_cancel_replace_order_request.h new file mode 100644 index 000000000..7cae98b5f --- /dev/null +++ b/src/lib_python_execution/python_execution/py_cancel_replace_order_request.h @@ -0,0 +1,110 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include + +namespace bts::orderman { +struct CancelReplaceOrderMsg; +} + +namespace python_execution { + +class PyCancelReplaceOrderRequest { + public: + std::uint32_t key() const; + void set_key(std::uint32_t value); + + const std::string &exchange_order_id() const; + void set_exchange_order_id(std::string value); + + const std::string &exchange_security_id() const; + void set_exchange_security_id(std::string value); + + const std::string &venue() const; + void set_venue(std::string value); + + bool is_buy() const; + void set_is_buy(bool value); + + float price() const; + void set_price(float value); + + float quantity() const; + void set_quantity(float value); + + void set_data( + std::uint32_t key, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + bool is_buy, + double price, + double quantity); + + std::string to_string() const; + + private: + std::uint32_t key_; + std::string exchange_order_id_; + std::string exchange_security_id_; + std::string venue_; + float price_; + float quantity_; + bool is_buy_; + + friend void from_json( + const nlohmann::json &j, PyCancelReplaceOrderRequest &req); +}; + +void to_json(nlohmann::json &j, const PyCancelReplaceOrderRequest &req); +void from_json(const nlohmann::json &j, PyCancelReplaceOrderRequest &req); + +std::ostream &operator<<( + std::ostream &out, const PyCancelReplaceOrderRequest &req) noexcept; + +} // namespace python_execution + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + python_execution::PyCancelReplaceOrderRequest, + r, + "{}", + bts::io::json_formatter(r)); + +namespace python_execution { + +inline void PyCancelReplaceOrderRequest::set_data( + std::uint32_t key, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + bool is_buy, + double price, + double quantity) { + key_ = key; + exchange_order_id_ = std::move(exchange_order_id); + exchange_security_id_ = std::move(exchange_security_id); + venue_ = std::move(venue); + is_buy_ = is_buy; + price_ = price; + quantity_ = quantity; +} + +inline std::string PyCancelReplaceOrderRequest::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyCancelReplaceOrderRequest &req) noexcept { + out << fmt::format("{}", req); + return out; +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_create_order_request.cpp b/src/lib_python_execution/python_execution/py_create_order_request.cpp new file mode 100644 index 000000000..5761a3b69 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_create_order_request.cpp @@ -0,0 +1,101 @@ +#include "py_create_order_request.h" +#include "spark/api/services/native_order_type.h" +#include "spark/api/services/time_in_force.h" +#include "spark/domain_model/Security.pb.h" +#include "spark/domain_model/Venue.h" +#include "spark/orderman/CreateOrderMsg.h" + +#include + +namespace python_execution { + +using std::string; +using std::uint32_t; + +uint32_t PyCreateOrderRequest::key() const { return key_; } +void PyCreateOrderRequest::set_key(uint32_t value) { key_ = value; } + +const string &PyCreateOrderRequest::exchange_security_id() const { + return exchange_security_id_; +} +void PyCreateOrderRequest::set_exchange_security_id(string value) { + exchange_security_id_ = std::move(value); +} + +const string &PyCreateOrderRequest::venue() const { return venue_; } +void PyCreateOrderRequest::set_venue(string value) { + venue_ = std::move(value); +} + +float PyCreateOrderRequest::price() const { return price_; } +void PyCreateOrderRequest::set_price(float value) { price_ = value; } + +float PyCreateOrderRequest::quantity() const { return quantity_; } +void PyCreateOrderRequest::set_quantity(float value) { quantity_ = value; } + +const string &PyCreateOrderRequest::order_type() const { return order_type_; } +void PyCreateOrderRequest::set_order_type(string value) { + order_type_ = std::move(value); +} + +const string &PyCreateOrderRequest::time_in_force() const { + return time_in_force_; +} +void PyCreateOrderRequest::set_time_in_force(string value) { + time_in_force_ = std::move(value); +} + +bool PyCreateOrderRequest::is_buy() const { return is_buy_; } +void PyCreateOrderRequest::set_is_buy(bool value) { + is_buy_ = std::move(value); +} + +void PyCreateOrderRequest::copy_from(const bts::orderman::CreateOrderMsg &msg) { + key_ = msg.key.value(); + exchange_security_id_ = msg.security_name(); + venue_ = bts::api::venue_name_pretty(msg.venue()); + is_buy_ = msg.side == bts::api::SIDE_BUY; + price_ = msg.price.value(); + quantity_ = msg.quantity.full_value_float(); + order_type_ = + bts::api::orderman::native_order_type_name_pretty(msg.order_type); + time_in_force_ = + bts::api::orderman::time_in_force_name_pretty(msg.time_in_force); +} + +void to_json(nlohmann::json &j, const PyCreateOrderRequest &req) { + j["key"] = req.key(); + j["esid"] = req.exchange_security_id(); + j["venue"] = req.venue(); + j["side"] = req.is_buy() ? "B" : "S"; + j["px"] = req.price(); + j["qty"] = req.quantity(); + j["typ"] = req.order_type(); + j["tif"] = req.time_in_force(); +} + +void from_json(const nlohmann::json &j, PyCreateOrderRequest &req) { + j.at("key").get_to(req.key_); + j.at("eid").get_to(req.exchange_security_id_); + j.at("venue").get_to(req.venue_); + const auto str = j.at("side").get(); + if (!str.empty()) { + switch (str[0]) { + case 'S': + case 's': + case 'A': + case 'a': + req.is_buy_ = false; + break; + case 'B': + case 'b': + req.is_buy_ = true; + } + } + j.at("px").get_to(req.price_); + j.at("qty").get_to(req.quantity_); + j.at("typ").get_to(req.order_type_); + j.at("tif").get_to(req.time_in_force_); +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_create_order_request.h b/src/lib_python_execution/python_execution/py_create_order_request.h new file mode 100644 index 000000000..88f08c1b0 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_create_order_request.h @@ -0,0 +1,117 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include + +namespace bts::orderman { +struct CreateOrderMsg; +} + +namespace python_execution { + +class PyCreateOrderRequest { + public: + std::uint32_t key() const; + void set_key(std::uint32_t value); + + const std::string &exchange_security_id() const; + void set_exchange_security_id(std::string value); + + const std::string &venue() const; + void set_venue(std::string value); + + bool is_buy() const; + void set_is_buy(bool value); + + float price() const; + void set_price(float value); + + float quantity() const; + void set_quantity(float value); + + const std::string &order_type() const; + void set_order_type(std::string value); + + const std::string &time_in_force() const; + void set_time_in_force(std::string value); + + void set_data( + std::uint32_t key, + std::string exchange_security_id, + std::string venue, + bool is_buy, + double price, + double quantity, + std::string order_type, + std::string time_in_force); + + void copy_from(const bts::orderman::CreateOrderMsg &msg); + std::string to_string() const; + + private: + std::uint32_t key_; + float price_; + float quantity_; + std::string exchange_security_id_; + std::string venue_; + std::string order_type_; + std::string time_in_force_; + bool is_buy_; + + friend void from_json(const nlohmann::json &j, PyCreateOrderRequest &req); +}; + +void to_json(nlohmann::json &j, const PyCreateOrderRequest &req); +void from_json(const nlohmann::json &j, PyCreateOrderRequest &req); + +std::ostream &operator<<( + std::ostream &out, const PyCreateOrderRequest &req) noexcept; + +} // namespace python_execution + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + python_execution::PyCreateOrderRequest, + r, + "{}", + bts::io::json_formatter(r)); + +namespace python_execution { + +inline void PyCreateOrderRequest::set_data( + std::uint32_t key, + std::string exchange_security_id, + std::string venue, + bool is_buy, + double price, + double quantity, + std::string order_type, + std::string time_in_force) { + key_ = key; + exchange_security_id_ = std::move(exchange_security_id); + venue_ = std::move(venue); + is_buy_ = is_buy; + price_ = price; + quantity_ = quantity; + order_type_ = std::move(order_type); + time_in_force_ = std::move(time_in_force); +} + +inline std::string PyCreateOrderRequest::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyCreateOrderRequest &req) noexcept { + out << fmt::format("{}", req); + return out; +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_execution_gateway.cpp b/src/lib_python_execution/python_execution/py_execution_gateway.cpp new file mode 100644 index 000000000..c748b388d --- /dev/null +++ b/src/lib_python_execution/python_execution/py_execution_gateway.cpp @@ -0,0 +1,7 @@ +#include "py_execution_gateway.h" + +namespace python_execution { + +PyExecutionGateway::~PyExecutionGateway() = default; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_execution_gateway.h b/src/lib_python_execution/python_execution/py_execution_gateway.h new file mode 100644 index 000000000..24a4e67bb --- /dev/null +++ b/src/lib_python_execution/python_execution/py_execution_gateway.h @@ -0,0 +1,55 @@ +#pragma once + +#include "python_execution/execution_gateway.h" +#include "python_execution/execution_gateway_bridge.h" +#include "python_execution/py_create_order_request.h" + +#include + +namespace python_execution { + +/** + * An implementation of `ExecutionGateway` that binds to a python object at runtime. + * + * @note The python object must derive from 'python_execution.ExecutionGateway', and define methods: + * * 'start(bridge: python_execution.ExecutionGatewayBridge)' + * * 'stop' + * * 'create_order' + * * 'cancel_order' + * * 'cancel_replace_order' + * @note 'python_execution_module' is a python module defined by us in c++ (see 'py_module.cpp'). + */ +class PyExecutionGateway : public ExecutionGateway { + public: + using ExecutionGateway::ExecutionGateway; + + ~PyExecutionGateway() override; + + // cpp calls into py + void start(ExecutionGatewayBridge *bridge) override { + PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, start, bridge); + } + void create_order(std::shared_ptr req) override { + PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, create_order, req); + } + void cancel_order(std::shared_ptr req) override { + PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, cancel_order, req); + } + void cancel_replace_order( + std::shared_ptr req) override { + PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, cancel_replace_order, req); + } + + // cpp calls into py + void on_securities( + const std::vector> + &securities) override { + PYBIND11_OVERLOAD_PURE( + void, ExecutionGateway, on_securities, std::move(securities)); + } + void stop() override { + PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, stop); + } +}; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_execution_report.cpp b/src/lib_python_execution/python_execution/py_execution_report.cpp new file mode 100644 index 000000000..f53c98a66 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_execution_report.cpp @@ -0,0 +1,155 @@ +#include "py_execution_report.h" +#include "spark/api/services/exec_type.h" +#include "spark/api/services/native_order_status.h" +#include "spark/api/services/native_order_type.h" +#include "spark/api/services/time_in_force.h" +#include "spark/domain_model/Security.pb.h" +#include "spark/domain_model/SecurityType.h" +#include "spark/domain_model/Venue.h" +#include "spark/domain_model/common.h" +#include "spark/orderman/orderman_utils/ExecutionReport.h" +#include "spark/orderman/orderman_utils/exchange_order_id.h" +#include "spark/orderman/orderman_utils/orderman_common.h" + +#include + +namespace python_execution { + +using bts::api::security_type_parse_smart; +using bts::api::venue_parse_smart; +using bts::api::orderman::exec_type_parse_smart; +using bts::api::orderman::native_order_status_parse_smart; +using bts::api::orderman::native_order_type_parse_smart; +using bts::api::orderman::time_in_force_parse_smart; +using bts::orderman::ExchangeOrderID; +using bts::orderman::ExchangeTimeStamp64; +using std::uint64_t; + +void PyExecutionReport::set_data( + std::uint32_t key, + std::string account, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + std::string security_type, + std::string order_type, + std::string order_status, + std::string time_in_force, + std::string exec_type, + bool is_buy, + double price, + double quantity, + double filled_quantity, + double last_filled_quantity, + double last_filled_price, + double avg_filled_price, + std::int64_t transact_id, + std::int64_t transact_time) { + key_ = key; + account_ = std::move(account); + exchange_order_id_ = std::move(exchange_order_id); + exchange_security_id_ = std::move(exchange_security_id); + venue_ = std::move(venue); + security_type_ = std::move(security_type); + order_type_ = std::move(order_type); + order_status_ = std::move(order_status); + time_in_force_ = std::move(time_in_force); + exec_type_ = std::move(exec_type); + is_buy_ = is_buy; + price_ = price; + quantity_ = quantity; + filled_quantity_ = filled_quantity; + last_filled_quantity_ = last_filled_quantity; + last_filled_price_ = last_filled_price; + avg_filled_price_ = avg_filled_price; + transact_id_ = transact_id; + transact_time_ = transact_time; + quantity_ = quantity; +} + +void PyExecutionReport::to_execution_report( + bts::orderman::ExecutionReport &er, + std::function + find_sec) { + *er.order_key = key_; + er.account_name->copy_from(account_); + if (std::holds_alternative(er.exchange_order_id)) { + std::get(er.exchange_order_id) + ->copy_from(exchange_order_id_); + } else { + er.exchange_order_id = ExchangeOrderID{exchange_order_id_}; + } + native_order_type_parse_smart(order_type_, &er.order_type); + native_order_status_parse_smart(order_status_, &er.order_status); + time_in_force_parse_smart(time_in_force_, &er.time_in_force); + exec_type_parse_smart(exec_type_, &er.exec_type); + bts::api::Venue venue; + venue_parse_smart(this->venue(), &venue); + bts::api::SecurityType sec_type; + security_type_parse_smart(security_type(), &sec_type); + er.security = find_sec(venue, sec_type, exchange_security_id()); + er.side = is_buy_ ? bts::api::SIDE_BUY : bts::api::SIDE_SELL; + *er.price = price_; + *er.stop_price = std::numeric_limits::quiet_NaN(); + er.quantity = bts::Quantity::create_new(quantity_); + *er.avg_price = avg_filled_price_; + er.filled_quantity = bts::Quantity::create_new(filled_quantity_); + *er.last_price = last_filled_price_; + er.last_shares = bts::Quantity::create_new(last_filled_quantity_); + er.transact_time = + ExchangeTimeStamp64{static_cast(transact_time_)}; +} + +void to_json(nlohmann::json &j, const PyExecutionReport &req) { + j["key"] = req.key(); + j["acc"] = req.account(); + j["esid"] = req.exchange_security_id(); + j["st"] = req.order_status(); + j["exec"] = req.exec_type(); + j["venue"] = req.venue(); + j["styp"] = req.security_type(); + j["side"] = req.is_buy() ? "B" : "S"; + j["px"] = req.price(); + j["qty"] = req.quantity(); + j["fqty"] = req.filled_quantity(); + j["lfqty"] = req.last_filled_quantity(); + j["lfpx"] = req.last_filled_price(); + j["afpx"] = req.avg_filled_price(); + j["typ"] = req.order_type(); + j["tt"] = req.transact_time(); +} + +void from_json(const nlohmann::json &j, PyExecutionReport &req) { + j.at("key").get_to(req.key_); + j.at("acc").get_to(req.account_); + j.at("esid").get_to(req.exchange_security_id_); + j.at("st").get_to(req.order_status_); + j.at("exec").get_to(req.exec_type_); + j.at("venue").get_to(req.venue_); + j.at("styp").get_to(req.security_type_); + std::string str; + j.at("side").get_to(str); + if (!str.empty()) { + switch (str[0]) { + case 'b': + case 'B': + req.is_buy_ = true; + break; + case 's': + case 'S': + req.is_buy_ = false; + break; + } + } + j.at("px").get_to(req.price_); + j.at("qty").get_to(req.quantity_); + j.at("fqty").get_to(req.filled_quantity_); + j.at("lfqty").get_to(req.last_filled_quantity_); + j.at("lfpx").get_to(req.last_filled_price_); + j.at("afpx").get_to(req.avg_filled_price_); + j.at("typ").get_to(req.order_type_); + j.at("tt").get_to(req.transact_time_); +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_execution_report.h b/src/lib_python_execution/python_execution/py_execution_report.h new file mode 100644 index 000000000..50cac122c --- /dev/null +++ b/src/lib_python_execution/python_execution/py_execution_report.h @@ -0,0 +1,276 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/domain_model/Security.pb.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include +#include + +namespace bts::orderman { +class ExecutionReport; +} + +namespace python_execution { + +class PyExecutionReport { + public: + std::uint32_t key() const; + void set_key(std::uint32_t value); + + const std::string &account() const; + void set_account(std::string value); + + const std::string &exchange_order_id() const; + void set_exchange_order_id(std::string value); + + const std::string &exchange_security_id() const; + 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); + + const std::string &order_type() const; + void set_order_type(std::string value); + + const std::string &order_status() const; + void set_order_status(std::string value); + + const std::string &time_in_force() const; + void set_time_in_force(std::string value); + + const std::string &exec_type() const; + void set_exec_type(std::string value); + + bool is_buy() const; + void set_is_buy(bool value); + + float price() const; + void set_price(float value); + + float quantity() const; + void set_quantity(float value); + + float filled_quantity() const; + void set_filled_quantity(float value); + + float last_filled_quantity() const; + void set_last_filled_quantity(float value); + + float last_filled_price() const; + void set_last_filled_price(float value); + + float avg_filled_price() const; + void set_avg_filled_price(float value); + + const std::string &transact_id() const; + void set_transact_id(std::string value); + + std::int64_t transact_time() const; + void set_transact_time(std::int64_t value); + + /** + * Sets all data at once (more performant than setting props one at a time + * when calling from python). + */ + void set_data( + std::uint32_t key, + std::string account, + std::string exchange_order_id, + std::string exchange_security_id, + std::string venue, + std::string security_type, + std::string order_type, + std::string order_status, + std::string time_in_force, + std::string exec_type, + bool is_buy, + double price, + double quantity, + double filled_quantity, + double last_filled_quantity, + double last_filled_price, + double avg_filled_price, + std::int64_t transact_id, + std::int64_t transact_time); + + void to_execution_report(bts::orderman::ExecutionReport &er); + void to_execution_report( + bts::orderman::ExecutionReport &er, + std::function + find_sec); + std::string to_string() const; + + private: + std::uint32_t key_; + std::string account_; + std::string exchange_order_id_; + std::string exchange_security_id_; + std::string venue_; + std::string security_type_; + std::string order_type_; + std::string order_status_; + std::string time_in_force_; + std::string exec_type_; + bool is_buy_; + float price_; + float quantity_; + float filled_quantity_; + float last_filled_quantity_; + float last_filled_price_; + float avg_filled_price_; + std::string transact_id_; + std::int64_t transact_time_; + + friend void from_json(const nlohmann::json &j, PyExecutionReport &req); +}; + +void to_json(nlohmann::json &j, const PyExecutionReport &req); +void from_json(const nlohmann::json &j, PyExecutionReport &req); + +std::ostream &operator<<( + std::ostream &out, const PyExecutionReport &req) noexcept; + +} // namespace python_execution + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL( + python_execution::PyExecutionReport, r, "{}", bts::io::json_formatter(r)); + +namespace python_execution { + +inline std::uint32_t PyExecutionReport::key() const { return key_; } +inline void PyExecutionReport::set_key(std::uint32_t value) { key_ = value; } + +inline const std::string &PyExecutionReport::account() const { + return account_; +} +inline void PyExecutionReport::set_account(std::string value) { + account_ = std::move(value); +} + +inline const std::string &PyExecutionReport::exchange_order_id() const { + return exchange_order_id_; +} +inline void PyExecutionReport::set_exchange_order_id(std::string value) { + exchange_order_id_ = std::move(value); +} + +inline const std::string &PyExecutionReport::exchange_security_id() const { + return exchange_security_id_; +} +inline void PyExecutionReport::set_exchange_security_id(std::string value) { + exchange_security_id_ = std::move(value); +} + +inline const std::string &PyExecutionReport::venue() const { return venue_; } +inline void PyExecutionReport::set_venue(std::string value) { + venue_ = std::move(value); +} + +inline const std::string &PyExecutionReport::security_type() const { + return security_type_; +} +inline void PyExecutionReport::set_security_type(std::string value) { + security_type_ = std::move(value); +} + +inline const std::string &PyExecutionReport::order_type() const { + return order_type_; +} +inline void PyExecutionReport::set_order_type(std::string value) { + order_type_ = std::move(value); +} + +inline const std::string &PyExecutionReport::order_status() const { + return order_status_; +} +inline void PyExecutionReport::set_order_status(std::string value) { + order_status_ = std::move(value); +} + +inline const std::string &PyExecutionReport::time_in_force() const { + return time_in_force_; +} +inline void PyExecutionReport::set_time_in_force(std::string value) { + time_in_force_ = std::move(value); +} + +inline const std::string &PyExecutionReport::exec_type() const { + return exec_type_; +} +inline void PyExecutionReport::set_exec_type(std::string value) { + exec_type_ = std::move(value); +} + +inline bool PyExecutionReport::is_buy() const { return is_buy_; } +inline void PyExecutionReport::set_is_buy(bool value) { is_buy_ = value; } + +inline float PyExecutionReport::price() const { return price_; } +inline void PyExecutionReport::set_price(float value) { price_ = value; } + +inline float PyExecutionReport::quantity() const { return quantity_; } +inline void PyExecutionReport::set_quantity(float value) { quantity_ = value; } + +inline float PyExecutionReport::filled_quantity() const { + return filled_quantity_; +} +inline void PyExecutionReport::set_filled_quantity(float value) { + filled_quantity_ = value; +} + +inline float PyExecutionReport::last_filled_quantity() const { + return last_filled_quantity_; +} +inline void PyExecutionReport::set_last_filled_quantity(float value) { + last_filled_quantity_ = value; +} + +inline float PyExecutionReport::last_filled_price() const { + return last_filled_price_; +} +inline void PyExecutionReport::set_last_filled_price(float value) { + last_filled_price_ = value; +} + +inline float PyExecutionReport::avg_filled_price() const { + return avg_filled_price_; +} +inline void PyExecutionReport::set_avg_filled_price(float value) { + avg_filled_price_ = value; +} + +inline const std::string &PyExecutionReport::transact_id() const { + return transact_id_; +} +inline void PyExecutionReport::set_transact_id(std::string value) { + transact_id_ = std::move(value); +} + +inline std::int64_t PyExecutionReport::transact_time() const { + return transact_time_; +} +inline void PyExecutionReport::set_transact_time(std::int64_t value) { + transact_time_ = value; +} + +inline std::string PyExecutionReport::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyExecutionReport &req) noexcept { + out << fmt::format("{}", req); + return out; +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_module.cpp b/src/lib_python_execution/python_execution/py_module.cpp new file mode 100644 index 000000000..173f11bf8 --- /dev/null +++ b/src/lib_python_execution/python_execution/py_module.cpp @@ -0,0 +1,137 @@ +#include "py_cancel_order_request.h" +#include "py_cancel_replace_order_request.h" +#include "py_create_order_request.h" +#include "python_execution/execution_gateway.h" +#include "python_execution/execution_gateway_bridge.h" +#include "python_execution/py_execution_gateway.h" +#include "python_execution/py_execution_report.h" +#include "python_execution/py_position_info.h" + +#include +#include +#include +#include + +using python_execution::ExecutionGateway; +using python_execution::ExecutionGatewayBridge; +using python_execution::PyCancelOrderRequest; +using python_execution::PyCancelReplaceOrderRequest; +using python_execution::PyCreateOrderRequest; +using python_execution::PyExecutionGateway; +using python_execution::PyExecutionReport; +using python_execution::PyPositionInfo; +using std::shared_ptr; + +PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr) + +namespace py = pybind11; + +#define PY_ARG(arg) pybind11::arg(#arg) + +#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 DEF_ARGS(type, member, ...) \ + def(_STR(member), &type::member, __VA_ARGS__) +#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, py::arg(#name)) + +PYBIND11_MODULE(python_execution_module, m) { + py::class_>( + m, "PyCreateOrderRequest") + .def(py::init<>()) + .PROP(PyCreateOrderRequest, key) + .PROP(PyCreateOrderRequest, exchange_security_id) + .PROP(PyCreateOrderRequest, venue) + .PROP(PyCreateOrderRequest, is_buy) + .PROP(PyCreateOrderRequest, price) + .PROP(PyCreateOrderRequest, quantity) + .PROP(PyCreateOrderRequest, order_type) + .PROP(PyCreateOrderRequest, time_in_force) + .def("__str__", &PyCreateOrderRequest::to_string); + py::class_>( + m, "PyCancelOrderRequest") + .def(py::init<>()) + .PROP(PyCancelOrderRequest, key) + .PROP(PyCancelOrderRequest, exchange_order_id) + .PROP(PyCancelOrderRequest, exchange_security_id) + .PROP(PyCancelOrderRequest, venue) + .PROP(PyCancelOrderRequest, is_buy) + .def("__str__", &PyCancelOrderRequest::to_string); + py::class_< + PyCancelReplaceOrderRequest, shared_ptr>( + m, "PyCancelReplaceOrderRequest") + .def(py::init<>()) + .PROP(PyCancelReplaceOrderRequest, key) + .PROP(PyCancelReplaceOrderRequest, exchange_order_id) + .PROP(PyCancelReplaceOrderRequest, exchange_security_id) + .PROP(PyCancelReplaceOrderRequest, venue) + .PROP(PyCancelReplaceOrderRequest, is_buy) + .PROP(PyCancelReplaceOrderRequest, price) + .PROP(PyCancelReplaceOrderRequest, quantity) + .def("__str__", &PyCancelReplaceOrderRequest::to_string); + py::class_>( + m, "PyExecutionReport") + .def(py::init<>()) + .PROP(PyExecutionReport, key) + .PROP(PyExecutionReport, account) + .PROP(PyExecutionReport, exchange_order_id) + .PROP(PyExecutionReport, exchange_security_id) + .PROP(PyExecutionReport, order_status) + .PROP(PyExecutionReport, time_in_force) + .PROP(PyExecutionReport, exec_type) + .PROP(PyExecutionReport, venue) + .PROP(PyExecutionReport, security_type) + .PROP(PyExecutionReport, is_buy) + .PROP(PyExecutionReport, price) + .PROP(PyExecutionReport, quantity) + .PROP(PyExecutionReport, filled_quantity) + .PROP(PyExecutionReport, last_filled_quantity) + .PROP(PyExecutionReport, last_filled_price) + .PROP(PyExecutionReport, avg_filled_price) + .PROP(PyExecutionReport, order_type) + .PROP(PyExecutionReport, transact_time) + .def( + "set_data", &PyExecutionReport::set_data, py::arg("key"), + py::arg("account"), py::arg("exchange_order_id"), + py::arg("exchange_security_id"), py::arg("venue"), + py::arg("security_type"), py::arg("order_type"), + py::arg("order_status"), py::arg("time_in_force"), + py::arg("exec_type"), py::arg("is_buy"), py::arg("price"), + py::arg("quantity"), py::arg("filled_quantity"), + py::arg("last_filled_quantity"), py::arg("last_filled_price"), + py::arg("avg_filled_price"), py::arg("transact_id"), + py::arg("transact_time")) + .def("__str__", &PyExecutionReport::to_string); + py::class_>(m, "PyPositionInfo") + .def(py::init<>()) + .PROP(PyPositionInfo, account) + .PROP(PyPositionInfo, exchange_security_id) + .PROP(PyPositionInfo, venue) + .PROP(PyPositionInfo, security_type) + .PROP(PyPositionInfo, long_quantity) + .PROP(PyPositionInfo, long_avg_cost) + .PROP(PyPositionInfo, short_quantity) + .PROP(PyPositionInfo, short_avg_cost) + .PROP(PyPositionInfo, transact_time) + .def("__str__", &PyPositionInfo::to_string); + py::class_(m, "ExecutionGatewayBridge") + .def(py::init<>()) + .DEF(ExecutionGatewayBridge, on_execution_report) + .DEF(ExecutionGatewayBridge, on_position_info) + .DEF(ExecutionGatewayBridge, on_is_ready); + py::class_(m, "ExecutionGateway") + .def(py::init<>()) + .DEF_ARGS(ExecutionGateway, start, py::arg("bridge")) + .DEF_ARGS(ExecutionGateway, create_order, py::arg("req")) + .DEF_ARGS(ExecutionGateway, cancel_order, py::arg("req")) + .DEF_ARGS(ExecutionGateway, cancel_replace_order, py::arg("req")) + .DEF(ExecutionGateway, stop); +} diff --git a/src/lib_python_execution/python_execution/py_order_request.h b/src/lib_python_execution/python_execution/py_order_request.h new file mode 100644 index 000000000..4fdc46dce --- /dev/null +++ b/src/lib_python_execution/python_execution/py_order_request.h @@ -0,0 +1,16 @@ +#pragma once + +#include "python_execution/py_cancel_order_request.h" +#include "python_execution/py_cancel_replace_order_request.h" +#include "python_execution/py_create_order_request.h" + +#include + +namespace python_execution { + +using PyOrderRequest = std::variant< + std::shared_ptr, + std::shared_ptr, + std::shared_ptr>; + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_position_info.cpp b/src/lib_python_execution/python_execution/py_position_info.cpp new file mode 100644 index 000000000..0715f2d0f --- /dev/null +++ b/src/lib_python_execution/python_execution/py_position_info.cpp @@ -0,0 +1,29 @@ +#include "py_position_info.h" + +namespace python_execution { + +void to_json(nlohmann::json &j, const PyPositionInfo &pi) { + j["acc"] = pi.account(); + j["esid"] = pi.exchange_security_id(); + j["styp"] = pi.security_type(); + j["venue"] = pi.venue(); + j["lacost"] = pi.long_avg_cost(); + j["lqty"] = pi.long_quantity(); + j["sacost"] = pi.short_avg_cost(); + j["sqty"] = pi.short_quantity(); + j["tt"] = pi.transact_time(); +} + +void from_json(const nlohmann::json &j, PyPositionInfo &pi) { + j.at("acc").get_to(pi.account_); + j.at("esid").get_to(pi.exchange_security_id_); + j.at("styp").get_to(pi.security_type_); + j.at("venue").get_to(pi.venue_); + j.at("lacost").get_to(pi.long_avg_cost_); + j.at("lqty").get_to(pi.long_quantity_); + j.at("sacost").get_to(pi.short_avg_cost_); + j.at("sqty").get_to(pi.short_quantity_); + j.at("tt").get_to(pi.transact_time_); +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution/py_position_info.h b/src/lib_python_execution/python_execution/py_position_info.h new file mode 100644 index 000000000..74f1d4c9f --- /dev/null +++ b/src/lib_python_execution/python_execution/py_position_info.h @@ -0,0 +1,134 @@ +#pragma once + +#include "spark/core/FMT_IMPL.h" +#include "spark/io/json_formatter.h" + +#include +#include +#include +#include + +namespace python_execution { + +class PyPositionInfo { + public: + const std::string &account() const; + void set_account(std::string value); + + const std::string &exchange_security_id() const; + 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); + + float long_quantity() const; + void set_long_quantity(float value); + + float long_avg_cost() const; + void set_long_avg_cost(float value); + + float short_quantity() const; + void set_short_quantity(float value); + + float short_avg_cost() const; + void set_short_avg_cost(float value); + + std::int64_t transact_time() const; + void set_transact_time(std::int64_t value); + + std::string to_string() const; + + private: + std::string account_; + std::string exchange_security_id_; + std::string venue_; + std::string security_type_; + float long_quantity_; + float long_avg_cost_; + float short_quantity_; + float short_avg_cost_; + std::int64_t transact_time_; + + friend void from_json(const nlohmann::json &j, PyPositionInfo &req); +}; + +void to_json(nlohmann::json &j, const PyPositionInfo &req); +void from_json(const nlohmann::json &j, PyPositionInfo &req); + +std::ostream &operator<<(std::ostream &out, const PyPositionInfo &req) noexcept; + +} // namespace python_execution + +////////////////////////////////////////////////// +// Definition +////////////////////////////////////////////////// + +FMT_IMPL(python_execution::PyPositionInfo, r, "{}", bts::io::json_formatter(r)); + +namespace python_execution { + +inline const std::string &PyPositionInfo::account() const { return account_; } +inline void PyPositionInfo::set_account(std::string value) { + account_ = std::move(value); +} + +inline const std::string &PyPositionInfo::exchange_security_id() const { + return exchange_security_id_; +} +inline void PyPositionInfo::set_exchange_security_id(std::string value) { + exchange_security_id_ = std::move(value); +} + +inline const std::string &PyPositionInfo::venue() const { return venue_; } +inline void PyPositionInfo::set_venue(std::string value) { + venue_ = std::move(value); +} + +inline const std::string &PyPositionInfo::security_type() const { + return security_type_; +} +inline void PyPositionInfo::set_security_type(std::string value) { + security_type_ = std::move(value); +} + +inline float PyPositionInfo::long_quantity() const { return long_quantity_; } +inline void PyPositionInfo::set_long_quantity(float value) { + long_quantity_ = value; +} + +inline float PyPositionInfo::long_avg_cost() const { return long_avg_cost_; } +inline void PyPositionInfo::set_long_avg_cost(float value) { + long_avg_cost_ = value; +} + +inline float PyPositionInfo::short_quantity() const { return short_quantity_; } +inline void PyPositionInfo::set_short_quantity(float value) { + short_quantity_ = value; +} + +inline float PyPositionInfo::short_avg_cost() const { return short_avg_cost_; } +inline void PyPositionInfo::set_short_avg_cost(float value) { + short_avg_cost_ = value; +} + +inline std::int64_t PyPositionInfo::transact_time() const { + return transact_time_; +} +inline void PyPositionInfo::set_transact_time(std::int64_t value) { + transact_time_ = value; +} + +inline std::string PyPositionInfo::to_string() const { + return fmt::format("{}", *this); +} + +inline std::ostream &operator<<( + std::ostream &out, const PyPositionInfo &req) noexcept { + out << fmt::format("{}", req); + return out; +} + +} // namespace python_execution diff --git a/src/lib_python_execution/python_execution_gateways/binance.env b/src/lib_python_execution/python_execution_gateways/binance.env new file mode 100644 index 000000000..c5dd93878 --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/binance.env @@ -0,0 +1,191 @@ +BINANCE_USDS_FUTURES_PROD_URL="https://fapi.binance.com" +BINANCE_USDS_FUTURES_PROD_WS_URL="wss://fstream.binance.com:443/ws" + +BINANCE_USDS_FUTURES_DEV_URL="https://testnet.binancefuture.com" +BINANCE_USDS_FUTURES_DEV_WS_URL="wss://stream.binancefuture.com:443/ws" +BINANCE_USDS_FUTURES_DEV_API_KEY="b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0" +BINANCE_USDS_FUTURES_DEV_SECRET_KEY="a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492" + +BINANCE_USDS_FUTURES_EXCHANGE_INFO_PATH="/fapi/v1/exchangeInfo" + +BINANCE_USDS_FUTURES_USER_DATA_PATH="/ws/${LISTEN_KEY}" + +BINANCE_USDS_FUTURES_DEPTH_PATH="/fapi/v1/depth" +BINANCE_USDS_FUTURES_DEPTH_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-5}' + +BINANCE_USDS_FUTURES_RECENT_TRADES_PATH="/fapi/v1/trades" +BINANCE_USDS_FUTURES_RECENT_TRADES_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-500}' + +BINANCE_USDS_FUTURES_HISTORICAL_TRADES_PATH="/fapi/v1/historicalTrades" +BINANCE_USDS_FUTURES_HISTORICAL_TRADES_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-500}' + +BINANCE_USDS_FUTURES_MARK_PRICE_PATH="/fapi/v1/premiumIndex" +BINANCE_USDS_FUTURES_MARK_PRICE_PARAMS='symbol=${SYMBOL}' + +BINANCE_USDS_FUTURES_PRICE_TICKER_PATH="/fapi/v1/ticker/price" +BINANCE_USDS_FUTURES_PRICE_TICKER_PARAMS='symbol=${SYMBOL}' + +BINANCE_USDS_FUTURES_BBO_PATH="/fapi/v1/ticker/bookTicker" +BINANCE_USDS_FUTURES_BBO_PARAMS='symbol=${SYMBOL}' + +BINANCE_USDS_FUTURES_OPEN_INTEREST_PATH="/dapi/v1/openInterest" +BINANCE_USDS_FUTURES_OPEN_INTEREST_PARAMS='symbol=${SYMBOL}' + +BINANCE_USDS_FUTURES_LONG_SHORT_RATIO_PATH="/futures/data/globalLongShortAccountRatio" +BINANCE_USDS_FUTURES_LONG_SHORT_RATIO_PARAMS='symbol=${SYMBOL}&period=${PERIOD:-30}&limit=${LIMIT:-10}' + +BINANCE_USDS_FUTURES_CREATE_ORDER_PATH="/fapi/v1/order" +BINANCE_USDS_FUTURES_CREATE_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_CREATE_ORDER_METHOD="POST" +BINANCE_USDS_FUTURES_CREATE_ORDER_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_MODIFY_ORDER_PATH="/fapi/v1/order" +BINANCE_USDS_FUTURES_MODIFY_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&priceMatch=${PRICE_MATCH:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_MODIFY_ORDER_METHOD="PUT" +BINANCE_USDS_FUTURES_MODIFY_ORDER_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_CANCEL_ORDER_PATH="/fapi/v1/order" +BINANCE_USDS_FUTURES_CANCEL_ORDER_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_CANCEL_ORDER_METHOD="DELETE" +BINANCE_USDS_FUTURES_CANCEL_ORDER_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_PATH="/fapi/v1/allOpenOrders" +BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_METHOD="DELETE" +BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_QUERY_ORDER_PATH="/fapi/v1/order" +BINANCE_USDS_FUTURES_QUERY_ORDER_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_QUERY_ORDER_METHOD="GET" +BINANCE_USDS_FUTURES_QUERY_ORDER_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_PATH="/fapi/v1/allOrders" +BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&startTime=${START_TIME:-OMIT}&endTime=${END_TIME:-OMIT}&limit=${LIMIT:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_METHOD="GET" +BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_OPEN_ORDERS_PATH="/fapi/v1/openOrders" +BINANCE_USDS_FUTURES_OPEN_ORDERS_PARAMS='symbol=${SYMBOL:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_OPEN_ORDERS_METHOD="GET" +BINANCE_USDS_FUTURES_OPEN_ORDERS_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_ACCOUNT_TRADES_PATH="/fapi/v1/userTrades" +BINANCE_USDS_FUTURES_ACCOUNT_TRADES_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&startTime=${START_TIME:-OMIT}&endTime=${END_TIME:-OMIT}&fromId=${FROM_ID:-OMIT}&limit=${LIMIT:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_ACCOUNT_TRADES_METHOD="GET" +BINANCE_USDS_FUTURES_ACCOUNT_TRADES_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_POSITION_INFO_PATH="/fapi/v3/positionRisk" +BINANCE_USDS_FUTURES_POSITION_INFO_PARAMS='symbol=${SYMBOL:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_USDS_FUTURES_POSITION_INFO_METHOD="GET" +BINANCE_USDS_FUTURES_POSITION_INFO_IS_SIGNED=1 + +BINANCE_USDS_FUTURES_LISTEN_KEY_PATH="/fapi/v1/listenKey" +BINANCE_USDS_FUTURES_LISTEN_KEY_PARAMS='' +BINANCE_USDS_FUTURES_LISTEN_KEY_METHOD="POST" +BINANCE_USDS_FUTURES_LISTEN_KEY_IS_KEYED=1 + +BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_PATH="/fapi/v1/listenKey" +BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY:-OMIT}' +BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_METHOD="PUT" +BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_IS_KEYED=1 + +BINANCE_COIN_FUTURES_PROD_URL="https://dapi.binance.com" +BINANCE_COIN_FUTURES_DEV_URL="https://testnet.binancefuture.com" +BINANCE_COIN_FUTURES_EXCHANGE_INFO_PATH="/dapi/v1/exchangeInfo" +BINANCE_COIN_FUTURES_DEPTH_PATH="/dapi/v1/depth" +BINANCE_COIN_FUTURES_RECENT_TRADES_PATH="/dapi/v1/trades" +BINANCE_COIN_FUTURES_HISTORICAL_TRADES_PATH="/dapi/v1/historicalTrades" +BINANCE_COIN_FUTURES_MARK_PRICE_PATH="/dapi/v1/premiumIndex" +BINANCE_COIN_FUTURES_PRICE_TICKER_PATH="/dapi/v1/ticker/price" +BINANCE_COIN_FUTURES_BBO_PATH="/dapi/v1/ticker/bookTicker" +BINANCE_COIN_FUTURES_OPEN_INTEREST_PATH="/dapi/v1/openInterest" +BINANCE_COIN_FUTURES_LONG_SHORT_RATIO_PATH="/futures/data/globalLongShortAccountRatio" + +BINANCE_PROD_URL="https://api.binance.com" +BINANCE_PROD_WS_URL="wss://stream.binance.com:9443/ws" +BINANCE_DEV_URL="https://testnet.binance.vision" +BINANCE_DEV_WS_URL="wss://stream.testnet.binance.vision:9443/ws" +BINANCE_DEV_API_KEY="QGwn9OVcpRTU76gOLV0gmQyVAJUmXW6w7H6y9tH8ctanzVnpZN1TP27liObE1Wsd" +BINANCE_DEV_SECRET_KEY="7ohKg6X3DcsZMGaJmngC84EglsCFse9flMl8aKisa5FUY18LjGCEEdm0KEZljk9T" + +BINANCE_EXCHANGE_INFO_PATH="/api/v3/exchangeInfo" + +BINANCE_DEPTH_PATH="/api/v3/depth" +BINANCE_DEPTH_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-5}' + +BINANCE_OPEN_ORDERS_PATH="/api/v3/openOrders" +BINANCE_OPEN_ORDERS_PARAMS='symbol=${SYMBOL:-OMIT}' +BINANCE_OPEN_ORDERS_IS_SIGNED=1 + +BINANCE_ACCOUNT_PATH="/api/v3/account" +BINANCE_ACCOUNT_PARAMS='recvWindow=${RECV_WINDOW:-6000}' +BINANCE_ACCOUNT_IS_SIGNED=1 + +BINANCE_CANCEL_OPEN_ORDERS_PATH="/api/v3/openOrders" +BINANCE_CANCEL_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CANCEL_OPEN_ORDERS_METHOD="DELETE" +BINANCE_CANCEL_OPEN_ORDERS_IS_SIGNED=1 + +BINANCE_CREATE_ORDER_PATH="/api/v3/order" +BINANCE_CREATE_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CREATE_ORDER_METHOD="POST" +BINANCE_CREATE_ORDER_IS_SIGNED=1 + +BINANCE_CANCEL_REPLACE_PATH="/api/v3/order/cancelReplace" +BINANCE_CANCEL_REPLACE_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&cancelReplaceMode=${CANCEL_REPLACE_MODE:-STOP_ON_FAILURE}&cancelNewClientOrderId=${CANCEL_NEW_CLIENT_ORDER_ID:-OMIT}&cancelOrigClientOrderId=${CANCEL_ORIG_CLIENT_ORDER_ID:-OMIT}&cancelOrderId=${CANCEL_ORDER_ID:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CANCEL_REPLACE_METHOD="POST" +BINANCE_CANCEL_REPLACE_IS_SIGNED=1 + +BINANCE_LISTEN_KEY_PATH="/api/v3/userDataStream" +BINANCE_LISTEN_KEY_PARAMS='' +BINANCE_LISTEN_KEY_METHOD="POST" +BINANCE_LISTEN_KEY_IS_KEYED=1 + +BINANCE_REFRESH_LISTEN_KEY_PATH="/api/v3/userDataStream" +BINANCE_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY}' +BINANCE_REFRESH_LISTEN_KEY_METHOD="PUT" +BINANCE_REFRESH_LISTEN_KEY_IS_KEYED=1 + +BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_PATH="/sapi/v1/margin/crossMarginCollateralRatio" +BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_METHOD="GET" +BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_IS_SIGNED=1 + +BINANCE_CROSS_MARGIN_PAIRS_PATH="/sapi/v1/margin/allPairs" +BINANCE_CROSS_MARGIN_PAIRS_PARAMS='symbol=${SYMBOL:-OMIT}' +BINANCE_CROSS_MARGIN_PAIRS_METHOD="GET" +BINANCE_CROSS_MARGIN_PAIRS_IS_SIGNED=1 + +BINANCE_CROSS_MARGIN_ORDER_PATH="/sapi/v1/margin/order" +BINANCE_CROSS_MARGIN_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE}&type=${TYPE}&quantity=${QUANTITY}&price=${PRICE}&timeInForce=GTC&autoRepayAtCancel=true&sideEffectType=AUTO_BORROW_REPAY&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CROSS_MARGIN_ORDER_METHOD="POST" +BINANCE_CROSS_MARGIN_ORDER_IS_SIGNED=1 + +BINANCE_CROSS_MARGIN_OPEN_ORDERS_PATH="/sapi/v1/margin/openOrders" +BINANCE_CROSS_MARGIN_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&isIsolated=${IS_ISOLATED:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CROSS_MARGIN_OPEN_ORDERS_METHOD="GET" +BINANCE_CROSS_MARGIN_OPEN_ORDERS_IS_SIGNED=1 + +BINANCE_CROSS_MARGIN_CANCEL_PATH="/sapi/v1/margin/order" +BINANCE_CROSS_MARGIN_CANCEL_PARAMS='symbol=${SYMBOL}&isIsolated=${IS_ISOLATED:-OMIT}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_CROSS_MARGIN_CANCEL_METHOD="DELETE" +BINANCE_CROSS_MARGIN_CANCEL_IS_SIGNED=1 + +BINANCE_CROSS_MARGIN_LISTEN_KEY_PATH="/sapi/v1/userDataStream" +BINANCE_CROSS_MARGIN_LISTEN_KEY_PARAMS='' +BINANCE_CROSS_MARGIN_LISTEN_KEY_METHOD="POST" +BINANCE_CROSS_MARGIN_LISTEN_KEY_IS_KEYED=1 + +BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_PATH="/sapi/v1/userDataStream" +BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY}' +BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_METHOD="PUT" +BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_IS_KEYED=1 + +BINANCE_ISOLATED_MARGIN_SYMBOL_PATH="/sapi/v1/margin/order" +BINANCE_ISOLATED_MARGIN_SYMBOL_PARAMS='symbol=${SYMBOL}&side=${SIDE}&type=${TYPE}&quantity=${QUANTITY}&price=${PRICE}&autoRepayAtCancel=true&recvWindow=${RECV_WINDOW:-6000}' +BINANCE_ISOLATED_MARGIN_SYMBOL_METHOD="GET" +BINANCE_ISOLATED_MARGIN_SYMBOL_IS_SIGNED=1 + +BINANCE_ALL_MARGIN_ASSETS_PATH="/sapi/v1/margin/allAssets" +BINANCE_ALL_MARGIN_ASSETS_PARAMS='asset=${ASSET:-OMIT}' +BINANCE_ALL_MARGIN_ASSETS_METHOD="GET" +BINANCE_ALL_MARGIN_ASSETS_IS_SIGNED=1 diff --git a/src/lib_python_execution/python_execution_gateways/binance_client.py b/src/lib_python_execution/python_execution_gateways/binance_client.py new file mode 100644 index 000000000..fd5d35a90 --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/binance_client.py @@ -0,0 +1,503 @@ +import argparse +import uuid +import hmac +import hashlib +import os +import logging +import sys +import time +import websocket +import json +import requests +import python_execution_module as pyexe +from string import Template +from threading import Thread +from typing import Any, Callable, Mapping, MutableMapping, Optional, TextIO + +from binance_env_helper import ( + required_env_var, + expand_vars, + expand_defaults, + load_env, +) + + +def hmac_hashing(api_secret: str, payload: str): + m = hmac.new(api_secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256) + return m.hexdigest() + + +def rest_request(base_url: str, api_key: str, api_secret: str, parameters: dict = {}): + parameters["timestamp"] = int(time.time() * 1000) + sorted_keys = list(parameters) + sorted_keys.sort() + query_params = "&".join([f"{k}={parameters[k]}" for k in sorted_keys]) + signature = hmac_hashing(api_secret=api_secret, payload=query_params) + parameters["signature"] = signature + query_params += "&signature=" + signature + url = base_url + "/api/v3/userDataStream" + "?" + query_params + res = requests.post(url, headers={"X-MBX-APIKEY": api_key}) + return res.text + + +class CircularBufferWriter: + def __init__(self, buffer_line_count: int, sink: TextIO = sys.stdout): + self.buffer_lines = [] + self.buffer_line_count = buffer_line_count + self.sink = sink + + def print(self, msg): + if self.buffer_line_count <= 0: + self.sink.write(msg + "\n") + return + for _ in range(0, len(self.buffer_lines)): + self.sink.write("\x1b[1A\x1b[2K") # move up cursor and delete whole line + if len(self.buffer_lines) == self.buffer_line_count: + self.buffer_lines.pop() + self.buffer_lines.insert(0, msg) + lines = "" + num_lines = len(self.buffer_lines) + for i in range(0, num_lines): + lines += self.buffer_lines[num_lines - i - 1] + "\n" + self.sink.write(lines) + + +def _get_arg_parser(): + # Cli Args + arg_parser = argparse.ArgumentParser(description="Request market data at Binance") + arg_parser.add_argument( + "--streams", + help="Streams to subscribe (e.g, btcusdt@depth5@500ms)", + ) + arg_parser.add_argument( + "--prod", action="store_const", const="PROD", dest="mode", help="Run at prod" + ) + arg_parser.add_argument( + "--dev", action="store_const", const="DEV", dest="mode", help="Run at testnet" + ) + arg_parser.add_argument( + "--spot", + action="store_const", + const="BINANCE", + dest="venue", + help="Run at spots", + ) + arg_parser.add_argument("--op", help="The op to run") + arg_parser.add_argument( + "--param", help="Parameter(s) formatted as key=val)", nargs="+" + ) + arg_parser.add_argument("--create-order", action="store_true", help="Create order") + arg_parser.add_argument( + "--usds-future", + action="store_const", + const="BINANCE_USDS_FUTURES", + dest="venue", + help="Run at usds futures", + ) + arg_parser.add_argument("--user-data", action="store_true", help="User data") + arg_parser.add_argument( + "--exch-info", + action="store_const", + const="EXCHANGE_INFO", + dest="op", + help="Get exchangeInfo (REST)", + ) + arg_parser.add_argument( + "--list-symbols", action="store_true", help="Get symbols (REST)" + ) + arg_parser.add_argument( + "--listen-key", + action="store_const", + const="LISTEN_KEY", + dest="op", + help="Get listen key (needed for streams)", + ) + arg_parser.add_argument( + "--list-streams", action="store_true", help="List all streams" + ) + arg_parser.add_argument( + "--display-lines", + help="Cap the number of lines to display from incoming messages (applies circular buffer to console output).", + ) + arg_parser.add_argument("--url", help="The url to send requests to") + arg_parser.set_defaults(mode="DEV", venue="BINANCE", user_data=False, op=None) + return arg_parser + + +def _parse_bool(s: Optional[str]): + match s: + case "1": + return True + case "true": + return True + case "on": + return True + case "y": + return True + case "yes": + return True + case _: + return False + + +class BinanceClient: + def __init__(self, venue="BINANCE", mode="DEV", logger=None): + self.venue = venue + self.mode = mode + self.rest_url = required_env_var(f"{venue}_{mode}_URL") + self.ws_url = required_env_var(f"{venue}_{mode}_WS_URL") + self._user_data_ping_thread: Optional[Thread] = None + self.threads: list[Thread] = [] + self.logger = logger or logging.getLogger(__name__) + self.api_key = os.environ.get(f"{self.venue}_{self.mode}_API_KEY") + self.secret_key = os.environ.get(f"{self.venue}_{self.mode}_SECRET_KEY") + self.orders = {} + + def _on_open_with_ping( + self, on_open: Optional[Callable[[websocket.WebSocket], None]] + ): + def wrapper(ws): + def ping_loop(): + time.sleep(10) + # if isinstance(ws, websocket.WebSocketApp): + # wsa: websocket.WebSocketApp = ws + # ws = wsa.sock + while True: + ws.sock.ping() + time.sleep(25) + + self._user_data_ping_thread = Thread(target=ping_loop) + self._user_data_ping_thread.start() + if on_open: + on_open(ws) + + return wrapper + + def _get_base_url(self, op, is_ws: bool = False, vars: Optional[Mapping] = None): + """Gets the base url for the request (includes host and path parts, but not query params).""" + url_var_suffix = "WS_URL" if is_ws else "URL" + url = os.environ.get(f"{self.venue}_{self.mode}_{url_var_suffix}") or "" + req_path = os.environ.get(f"{self.venue}_{op}_PATH") or "" + if vars: + req_path = expand_vars(req_path, vars) + if req_path: + n = 1 if req_path.startswith("/") else 0 + n += 1 if self.rest_url.endswith("/") else 0 + match n: + case 0: + url += "/" + req_path + case 1: + url += req_path + case 2: + url += req_path[1:] + return url + + def _index_transaction(self, bts_key: int): + exch_key = uuid.uuid1().hex + self.orders[exch_key] = bts_key + return exch_key + + def _get_params_str(self, op, **kwargs): + params = os.environ.get(f"{self.venue}_{op}_PARAMS") or "" + params = expand_vars(params, kwargs) + params = expand_defaults(params) + return params + + def _get_params_dict(self, op, **kwargs): + params = self._get_params_str(op=op, **kwargs) + if not params: + return {} + return {p[0]: p[1] for p in map(lambda x: x.split("="), params.split("&"))} + + def _invoke(self, target: Callable[[], Any], run_in_background: bool): + if run_in_background: + t = Thread(target=target) + self.threads.append(t) + t.start() + else: + target() + + def request(self, op, **kwargs): + print( + "Preparing request. op=%s, params=[%s]" + % (op, ", ".join([f"{k}={v}" for k, v in kwargs.items()])), + flush=True, + ) + self.logger.info( + "Preparing request. op=%s, params=[%s]" + % (op, ", ".join([f"{k}={v}" for k, v in kwargs.items()])) + ) + is_signed = _parse_bool(os.environ.get(f"{self.venue}_{op}_IS_SIGNED")) + is_keyed = _parse_bool(os.environ.get(f"{self.venue}_{op}_IS_KEYED")) + method = os.environ.get(f"{self.venue}_{op}_METHOD") + params = self._get_params_dict(op, **kwargs) + base_url = self._get_base_url(op, is_ws=False) + res = None + if is_keyed or is_signed: + if not self.api_key: + self.logger.error("Unable to make signed request. Api key not defined") + return + headers = {"Content-Type": "application/json", "X-MBX-APIKEY": self.api_key} + if is_signed: + if not self.secret_key: + self.logger.error( + "Unable to make signed request. Secret key not defined" + ) + return + params["timestamp"] = str(int(time.time() * 1000)) + base_url = self._get_base_url(op) + sorted_keys = list(params) + sorted_keys.sort() + params_str = "&".join([f"{k}={params[k]}" for k in sorted_keys]) + signature = hmac_hashing(api_secret=self.secret_key, payload=params_str) + params_str += "&signature=" + signature + url = base_url + "?" + params_str + if not method: + method = "POST" + headers = {"X-MBX-APIKEY": self.api_key} + # print("ABOUT TO SEND.", flush=True) + self.logger.info("Sending %s %s" % (method, url)) + try: + print( + "Requesting %s %s (%s)" + % ( + method, + url, + ", ".join([f"{k}={v}" for k, v in headers.items()]), + ), + flush=True, + ) + res = requests.request(method, url, headers=headers) + # if res: + print("RESULT. %s", str(res), flush=True) + self.logger.log( + logging.INFO if res.ok else logging.ERROR, + "Received %i %s" % (res.status_code, str(res.text)), + ) + except Exception as ex: + print("OH NO %s" % str(ex), flush=True) + self.logger.error("Request threw %s" % str(ex)) + else: + params_str = "&".join([f"{k}={v}" for k, v in params.items()]) + url = base_url + if params_str: + url += "?" + params_str + if not method: + method = "GET" + headers = {"Content-Type": "application/json", "X-MBX-APIKEY": self.api_key} + self.logger.info( + "Sending request %s %s (headers=[%s])" + % (method, url, ", ".join([f"{k}={v}" for k, v in headers.items()])) + ) + try: + res = requests.request(method, url, headers=headers) + self.logger.log( + logging.INFO if res.ok else logging.ERROR, + "Received response. %s" % str(res), + ) + except Exception as e: + self.logger.error("Request threw: %s" % str(e)) + self.logger.log( + logging.INFO if res and res.ok else logging.ERROR, + "Request failed. op=%s, res=\n%s", + op, + str(res), + ) + return res + + def create_order(self, req: pyexe.PyCreateOrderRequest): + self.logger.info("Create order. %s" % str(req)) + self.request( + op="CREATE_ORDER", + symbol=req.exchange_security_id(), + side="BUY" if req.is_buy() else "SELL", + type=req.order_type(), + price=req.price(), + quantity=f"{req.quantity():.6f}", + new_client_order_id=self._index_transaction(req.key()), + ) + + def cancel_order(self, req: pyexe.PyCancelOrderRequest): + self.request( + op="CANCEL_ORDER", + symbol=req.exchange_security_id(), + side="BUY" if req.is_buy() else "SELL", + orig_client_order_id=str(req.exchange_order_id()), + new_client_order_id=self._index_transaction(req.key()), + ) + + def subscribe_user_data( + self, + on_message: Optional[Callable[[websocket.WebSocket, Any], None]] = None, + on_error: Optional[Callable[[websocket.WebSocket, Any], None]] = None, + on_close: Optional[Callable[[websocket.WebSocket, Any, Any], None]] = None, + on_open: Optional[Callable[[websocket.WebSocket], None]] = None, + run_in_background: bool = True, + ): + self.logger.info("Requesting listen key") + res = self.request("LISTEN_KEY") + if res is None: + print("'listen_key_res' is none (this is unexpected)") + return + self.logger.log( + logging.INFO if res and res.ok else logging.ERROR, + "Received listen key. %s" % str(res), + ) + if not res.ok: + self.logger.error("Failed to get listen key") + lkey = res.json().get("listenKey") + self.logger.info("Received listen key %s" % lkey) + url = self._get_base_url("USER_DATA", is_ws=True, vars={"LISTEN_KEY": lkey}) + ws_app = websocket.WebSocketApp( + url=url, + on_message=on_message, + on_error=on_error, + on_close=on_close, + on_open=self._on_open_with_ping(on_open), + ) + self.logger.info("Starting user data websocket %s" % url) + self._invoke( + lambda: ws_app.run_forever(ping_interval=600, ping_timeout=180), + run_in_background, + ) + + def subscribe_streams( + self, + streams, + on_message: Optional[Callable[[websocket.WebSocket, Any], None]] = None, + on_error: Optional[Callable[[websocket.WebSocket, Any], None]] = None, + on_close: Optional[Callable[[websocket.WebSocket, Any, Any], None]] = None, + run_in_background: bool = True, + **kwargs, + ): + def on_open(ws: websocket.WebSocket): + self.logger.info("Stream websocket connected") + try: + req = { + "method": "SUBSCRIBE", + "params": streams, + "id": 1, + } + req_str = json.dumps(req) + self.logger.info("Requesting stream. %s", req_str) + ws.send_text(req_str) + except Exception as ex: + self.logger.error("Stream request failed. %s", ex) + self.logger.info("Disconnecting stream websocket") + ws.close() + + url = self._get_base_url("STREAMS", is_ws=True, **kwargs) + + ws_app = websocket.WebSocketApp( + url=url, + on_open=self._on_open_with_ping(on_open), + on_message=on_message, + on_error=on_error, + on_close=on_close, + ) + self.logger.info("StreamSubscription @ %s", url) + self._invoke( + lambda: ws_app.run_forever(ping_interval=600, ping_timeout=180), + run_in_background, + ) + + +def _main(): + load_env() + arg_parser = _get_arg_parser() + args = arg_parser.parse_args() + if args.list_streams: + stream_descs = [ + "{symbol}@aggTrade", + "{symbol}@markPrice", + "{symbol}@markPrice@{interval} (intervals: 1s)", + "!markPrice@arr", + "!markPrice@arr@1s", + "{symbol}@kline_{interval} (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)", + "{pair}_{contractType}@continuousKline_{interval} (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)" + "{symbol}@miniTicker", + "!ticker@arr", + "{symbol}@ticker", + "!miniTicker@arr", + "{symbol}@bookTicker", + "!bookTicker", + "{symbol}@forceOrder", + "!forceOrder@arr", + "{symbol}@depth{levels} (levels: 5, 10, 20)", + "{symbol}@depth{levels}@{interval} (levels: 5, 10, 20)", + " (intervals: 100ms, 500ms)", + "{symbol}@depth", + "{symbol}@depth@{interval} (intervals: 100ms, 500ms)", + "{symbol}@compositeIndex", + "!contractInfo", + "!assetIndex@arr", + "{assetSymbol}@assetIndex", + ] + print("\n".join(stream_descs)) + return + logger = logging.getLogger() + cli = BinanceClient(args.venue, args.mode, logger=logger) + params = {kv[0]: kv[1] for kv in map(lambda x: x.split("="), args.param or [])} + if args.op: + res = cli.request(args.op, **params) + if res and res.ok: + print(res.text) + elif args.list_symbols: + # Get symbols + res = cli.request("EXCHANGE_INFO") + if not res or not res.ok: + return 1 + syms = {} + res_j = json.loads(res.text) + for sym in res_j["symbols"]: + syms[sym["symbol"]] = sym + sym_list = list(syms) + sym_list.sort() + for sym in sym_list: + print(sym) + elif args.user_data: + # Subscribe user data + writer = CircularBufferWriter(buffer_line_count=int(args.display_lines or -1)) + + def on_message(ws, msg): + logger.debug("on_message: %s", msg) + writer.print(msg) + + def on_error(ws, err): + logger.error("on_error: %s", err) + + def on_close(ws, code, msg): + logger.info("on_close (%d): %s", code, msg) + + cli.subscribe_user_data(on_message, on_error, on_close) + elif args.streams: + # Subscribe streams + writer = CircularBufferWriter(buffer_line_count=int(args.display_lines or -1)) + + def on_message(ws, msg): + logger.debug("Recv: %s", msg) + writer.print(msg) + + def on_error(ws, err): + logger.error("Error: %s", err) + + def on_close(ws, code, msg): + logger.info("Closed (%d): %s", code, msg) + + cli.subscribe_streams( + streams=args.streams if isinstance(args.streams, list) else [args.streams], + on_message=on_message, + on_error=on_error, + on_close=on_close, + ) + else: + sys.stderr.write( + "No data requested (run with --streams ... or --exch-info or --list-symbols)" + ) + return 1 + return 0 + + +if __name__ == "__main__": + code = _main() + exit(code) diff --git a/src/lib_python_execution/python_execution_gateways/binance_env_helper.py b/src/lib_python_execution/python_execution_gateways/binance_env_helper.py new file mode 100644 index 000000000..04aac3cc8 --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/binance_env_helper.py @@ -0,0 +1,100 @@ +from typing import Any, Mapping, Optional +import dotenv +import os + + +def required_env_var(key): + val = os.environ.get(key) + if val is None: + raise ValueError(f"{key} env var not defined") + return val + + +def expand_env(s: str, vars=os.environ): + if not s: + return "" + beg = 0 + while True: + beg = s.find("${", beg) + if beg == -1 or beg > len(s) - 4: + break + end = s.find("}", beg + 2) + if end == -1: + break + k = s[beg:end] + v = vars.get(k) or "" + s = s[:beg] + v + s[end + 1 :] + beg += len(v) + 1 + return s + + +def expand_var(req_params: str, k: str, v: Any): + ku = str(k).upper() + substitution = f"${{{ku}}}" + pos = req_params.find(substitution) + end_pos = -1 + if pos == -1: + substitution = f"${{{ku}:" + pos = req_params.find(substitution) + if pos == -1: + return req_params + end_pos = req_params.find("}", pos + len(substitution)) + if end_pos == -1: + return req_params + end_pos += 1 + else: + end_pos = pos + len(substitution) + if end_pos == -1: + raise ValueError(f"Invalid request params template '{req_params}'") + req_params = req_params[:pos] + str(v) + req_params[end_pos:] + return req_params + + +def expand_vars(req_params: str, key_vals: Mapping): + for k, v in key_vals.items(): + req_params = expand_var(req_params, k, v) + return req_params + + +def expand_defaults(req_params: str): + i = 0 + prefix = ":-" + while i < len(req_params): + start = req_params.find("${", i) + if start == -1: + break + stop = req_params.find("}", start) + if stop == -1: + raise ValueError(f"Invalid param str {req_params}") + prefix_pos = req_params.find(prefix, start, stop) + if prefix_pos < start: + req_params = req_params[:start] + req_params[stop + 1 :] + i = start + continue + default_val = req_params[prefix_pos + len(prefix) : stop] + if default_val == "OMIT": + i = req_params.rfind("&", 0, prefix_pos - 1) + if i == -1: + i = 0 + req_params = req_params[:i] + req_params[stop + 1 :] + else: + req_params = req_params[:start] + default_val + req_params[stop + 1 :] + i = start + len(default_val) + 1 + if req_params.startswith("&"): + req_params = req_params[1:] + return req_params + + +def load_env(env_path: Optional[str] = None): + if not env_path: + env_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "binance.env" + ) + dotenv.load_dotenv(env_path, interpolate=False) + + +if __name__ == "__main__": + req_params = required_env_var("BINANCE_CREATE_ORDER_PARAMS") + res = expand_var(req_params, "SYMBOL", "BTCUSDT") + res = expand_defaults(res) + print(res) diff --git a/src/lib_python_execution/python_execution_gateways/binance_execution_gateway.py b/src/lib_python_execution/python_execution_gateways/binance_execution_gateway.py new file mode 100644 index 000000000..d06f7ac55 --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/binance_execution_gateway.py @@ -0,0 +1,242 @@ +import dotenv +import json +import logging +import math +import sys +import traceback +from typing import Any, Optional +import uuid +import websocket + +from binance_client import BinanceClient +import python_execution_module as pyexe + + +BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc" +BINANCE_USDS_FUTURES_API_KEY = ( + "b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0" +) +BINANCE_USDS_FUTURES_SECRET_KEY = ( + "a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492" +) + + +def to_bts_exec_type(exec_type: str, ord_status: str): + match exec_type: + case "TRADE_PREVENTION": + return "REJECTED" + case "NONE": + return "UNDEFINED" + case "TRADE": + return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL" + case _: + return exec_type + + +def to_bts_order_status(ord_status: str): + match ord_status: + case "EXPIRED_IN_MATCH": + return "EXPIRED" + case _: + return ord_status + + +class DummyExecutionGateway(pyexe.ExecutionGateway): + def __init__(self): + super(DummyExecutionGateway, self).__init__() + self.bridge = None + self.client = None + self.start_th = None + self.ws = None + self.orders = {} + self.logger = logging.getLogger(__name__) + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.formatter = logging.Formatter( + "%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s" + ) + self.logger.addHandler(stdout_handler) + self.logger.addHandler( + logging.FileHandler( + "/home/bts/sparkdata/data/logging.python_execution/dummy_log" + ) + ) + self.logger.setLevel(logging.INFO) + env_path = "/workspaces/spark/tools/binance/binance.env" + self.logger.info("DummyExecutionGateway ctr. Loading env") + dotenv.load_dotenv(env_path, interpolate=False) + + def _index_transaction(self, bts_key: int): + exch_key = uuid.uuid1().hex + self.orders[exch_key] = bts_key + return exch_key + + def _on_user_data_msg_core(self, ws: websocket.WebSocket, msg: Any): + self.logger.info("Recv usr data: %s", str(msg)) + if not msg: + self.logger.error("Recv empty usr data msg") + return + if not self.bridge: + self.logger.error("Cannot process usr data. Bridge not created") + return + upd = json.loads(str(msg)) + if "e" in upd: + if upd["e"] == "executionReport": + # Binance spots update + bts_ord_id = self.orders.get(upd["c"]) + is_old_ord = False + if not bts_ord_id: + bts_ord_id = self.orders.get(upd["C"]) + if not bts_ord_id: + self.logger.warning( + "Received update with unknown order id: %s", msg + ) + return + is_old_ord = True + er = pyexe.PyExecutionReport() + er.set_key(bts_ord_id) + er.set_venue("BINANCE") + er.set_exchange_security_id(upd["s"]) + er.set_security_type("SPOT") + er.set_exec_type(to_bts_exec_type(upd["x"], upd["X"])) + er.set_is_buy(upd["S"] == "BUY") + er.set_price(float(upd["p"])) + er.set_quantity(float(upd["q"])) + er.set_last_filled_price(upd["L"]) + er.set_last_filled_quantity(upd["l"]) + total_filled_qty = float(upd["z"]) + er.set_filled_quantity(total_filled_qty) + total_filled_notional = float(upd["Z"]) + avg_filled_price = ( + total_filled_notional / total_filled_qty + if total_filled_qty > 0 + else math.nan + ) + er.set_avg_filled_price(avg_filled_price) + er.set_order_status(to_bts_order_status(upd["X"])) + er.set_order_type(upd["o"]) + match upd["X"]: + case "CANCELED": + if not is_old_ord: + del self.orders[bts_ord_id] + case "FILLED": + del self.orders[bts_ord_id] + case "REJECTED": + del self.orders[bts_ord_id] + self.bridge.on_execution_report(er) + elif upd["e"] == "ORDER_TRADE_UPDATE": + data = upd["o"] + # Binance Usds Futures order update + bts_ord_id = self.orders.get(data["c"]) + is_old_ord = False + if not bts_ord_id: + bts_ord_id = self.orders.get(data["C"]) + if not bts_ord_id: + self.logger.warning( + "Received dataate with unknown order id: %s", msg + ) + return + is_old_ord = True + + def parse_float(s: Optional[str], default_val=math.nan): + if s is not None: + try: + return float(s) + except Exception: + pass + return default_val + + er = pyexe.PyExecutionReport() + er.set_key(bts_ord_id) + er.set_venue("BINANCE_USDS_FUTURES") + er.set_security_type("FUTURE") + er.set_time_in_force("GTC") + er.set_exchange_order_id(str(data.get("i") or 0)) + # er.set_exchange_order_id(data["i"]) + er.set_exchange_security_id(data["s"]) + er.set_exec_type(to_bts_exec_type(data["x"], data["X"])) + er.set_is_buy(data["S"] == "BUY") + er.set_price(parse_float(data["p"])) + er.set_quantity(parse_float(data["q"])) + er.set_last_filled_price(parse_float(data.get("L"))) + er.set_last_filled_quantity(parse_float(data["l"])) + er.set_filled_quantity(parse_float(data["z"])) + er.set_avg_filled_price(parse_float(data["ap"])) + er.set_order_status(to_bts_order_status(data["X"])) + er.set_order_type(data["o"]) + match data["X"]: + case "CANCELED": + if not is_old_ord: + del self.orders[bts_ord_id] + case "FILLED": + del self.orders[bts_ord_id] + case "REJECTED": + del self.orders[bts_ord_id] + print("Firing this exe report: %s" % str(er), flush=True) + self.bridge.on_execution_report(er) + + def _on_user_data_msg(self, ws: websocket.WebSocket, msg: Any): + try: + self._on_user_data_msg_core(ws, msg) + except Exception: + self.logger.error("on_user_data_msg. %s" % traceback.format_exc()) + + def _on_user_data_open(self, ws: websocket.WebSocket): + self.ws = ws + if self.bridge: + self.bridge.on_is_ready(True) + + def _on_user_data_err(self, ws: websocket.WebSocket, err: str): + self.logger.error("on_user_data_err: %s", err) + + def _on_user_data_close(self, ws: websocket.WebSocket, code: int, msg: str): + self.logger.warning("on_user_data_close: %s %s", str(code), msg) + if self.bridge: + self.bridge.on_is_ready(False) + + def start(self, bridge: pyexe.ExecutionGatewayBridge): + print("DummyExecutionGateway.start") + self.bridge = bridge + self.client = BinanceClient(venue="BINANCE_USDS_FUTURES") + print("DummyExecutionGateway.start. Subscribing to binance user data") + self.client.subscribe_user_data( + on_message=self._on_user_data_msg, + on_open=self._on_user_data_open, + on_close=self._on_user_data_close, + ) + print("DummyExecutionGateway.start. Subscribed to binance user data") + + def cancel_order(self, req: pyexe.PyCancelOrderRequest): + if not self.client: + self.logger.error("Cannot cancel order. BinanceClient not created.") + return + self.logger.info("[cancel_order.json]%s", str(req)) + try: + self.client.request( + "CANCEL_ORDER", + symbol=req.exchange_security_id(), + orig_client_order_id=req.exchange_order_id(), + new_client_order_id=self._index_transaction(req.key()), + ) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) + + def create_order(self, req: pyexe.PyCreateOrderRequest): + if not self.client: + self.logger.error("Cannot create order. BinanceClient not created.") + return + print("hey bud") + self.logger.info("[create_order.json]%s", str(req)) + side = "BUY" if req.is_buy() else "SELL" + try: + self.client.request( + op="CREATE_ORDER", + symbol=req.exchange_security_id(), + price=req.price(), + quantity=f"{req.quantity():.6f}", + side=side, + time_in_force="GTC", + type="LIMIT", + new_client_order_id=self._index_transaction(req.key()), + ) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) diff --git a/src/lib_python_execution/python_execution_gateways/bybit_execution_gateway.py b/src/lib_python_execution/python_execution_gateways/bybit_execution_gateway.py new file mode 100644 index 000000000..a77952703 --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/bybit_execution_gateway.py @@ -0,0 +1,303 @@ +import json +import math +import time +from typing import Optional +import uuid +from pybit.unified_trading import WebSocket, WebSocketTrading +from py_execution_utils import load_gateway_config +from spark_core import ( + as_bool, + configure_logger, + get_price_decimal_places, + get_qty_decimal_places, + parse_float, + StructuredLog as SLog, +) +import logging +from python_core_module import ( + PySecurity, + PySecurityList, +) +from python_execution_module import ( + ExecutionGateway, + ExecutionGatewayBridge, + PyCreateOrderRequest, + PyCancelReplaceOrderRequest, + PyCancelOrderRequest, + PyExecutionReport, +) +import threading + + +class OrderData: + def __init__(self, bts_id: int, exch_id: str, price: float, quantity: float): + self.bts_id = bts_id + self.exch_id = exch_id + self.price = price + self.quantity = quantity + self.filled_quantity: float = 0 + self.last_filled_quantity: float = math.nan + self.avg_filled_price: float = math.nan + self.last_filled_price: float = math.nan + self.exec_type = "PENDING_NEW" + self.securities: PySecurityList = [] + + def on_update( + self, new_filled_quantity: float, new_avg_filled_price: float, status: str + ): + lfq = new_filled_quantity - self.filled_quantity + if lfq > 0: + if self.filled_quantity == 0: + self.last_filled_quantity = new_filled_quantity + self.last_filled_price = new_avg_filled_price + else: + price_diff = new_avg_filled_price - self.avg_filled_price + lfq_weight = new_filled_quantity / ( + self.filled_quantity + new_filled_quantity + ) + lfp = self.avg_filled_price + (price_diff / lfq_weight) + self.last_filled_price = lfp + self.last_filled_quantity = lfq + self.filled_quantity = new_filled_quantity + self.avg_filled_price = new_avg_filled_price + match status: + case "Filled": + self.exec_type = "FILL" + case "Canceled": + self.exec_type = "CANCELED" + case "Rejected": + self.exec_type = "REJECTED" + case _: + self.exec_type = "NEW" if new_filled_quantity == 0 else "PARTIAL_FILL" + + +class BybitExecutionGateway(ExecutionGateway): + def __init__(self, name: str): + super(BybitExecutionGateway, self).__init__() + self.name = name + self.logger = configure_logger(logging.getLogger(name), "OrderMan") + self.logger.info("[bybit_gw_ctr.json]%s" % SLog(name=name)) + cfg = load_gateway_config(name) + self.account: str = cfg["account"] + self.api_key: str = cfg["api_key"] + self.secret_key: str = cfg["secret_key"] + self.use_testnet: bool = cfg.get("use_testnet", True) + self.use_trace_logging: bool = cfg.get("use_trace_logging", False) + self.stop_event = threading.Event() + self.stream_cli: Optional[WebSocket] = None + self.trade_cli: Optional[WebSocketTrading] = None + # bts id -> exch id + self.orders: dict[int, OrderData] = {} + self.securities: dict[str, PySecurity] = {} + + def _get_order_data(self, exch_id: str): + for _, v in self.orders.items(): + if v.exch_id == exch_id: + return v + return None + + def _on_order_ack(self, typ, msg: object): + self.logger.info( + '[bybit_gw_ord_ack.json]{ "typ": "%s", "msg": %s}' % (typ, msg) + ) + + def _on_abort( + self, + key: int, + req_type: str, + rsn: str, + ): + self.logger.error( + '[bybit_gw_abort.json]{ "key": %d, "typ": "%s", "rsn": "%s", "ts": %d }' + % (key, req_type, rsn, time.time_ns()) + ) + + def start_impl(self, bridge: ExecutionGatewayBridge): + def on_order_update(msg: dict): + def on_error(err: str): + self.logger.error( + '[bybit_gw_ord_upd_err.json]{ "err": "%s", "ts": %d }' + % (err, time.time_ns()) + ) + + self.logger.info("[bybit_gw_ord_upd.json]%s" % msg) + try: + upds: list[dict] = msg["data"] + for d in upds: + er = PyExecutionReport() + exch_id: str = d["orderLinkId"] + ord_data: Optional[OrderData] = self._get_order_data(exch_id) + if not ord_data: + on_error("Did not resolve exch order id %s" % exch_id) + return + total_filled_qty = parse_float(d["cumExecQty"]) + avg_filled_price = parse_float(d["avgPrice"]) + status: str = d["orderStatus"] + # brits can't spell + if status == "Cancelled": + status = "Canceled" + ord_data.on_update(total_filled_qty, avg_filled_price, status) + er.set_data( + key=ord_data.bts_id, + exchange_order_id=d["orderLinkId"], + transact_id=d["seq"], + venue="BYBIT", + security_type="FUTURE", + exchange_security_id=d["symbol"], + account=self.account, + order_type=d["orderType"], + is_buy=d["side"] == "Buy", + price=parse_float(d["price"]), + quantity=parse_float(d["qty"]), + time_in_force=d["timeInForce"], + exec_type=ord_data.exec_type, + order_status=status, + last_filled_price=ord_data.last_filled_price, + last_filled_quantity=ord_data.last_filled_quantity, + filled_quantity=total_filled_qty, + avg_filled_price=avg_filled_price, + transact_time=int(d["updatedTime"]) * 1_000_000, + ) + self.logger.info("[bybit_gw_exe_rep_out.json]%s" % er) + bridge.on_execution_report(er) + except Exception as e: + self.logger.error( + '[bybit_gw_ord_upd_err.json]{ "err": %s }' % e, exc_info=True + ) + + def on_exe_report(msg): + self.logger.info("[bybit_gw_exe_rep.json]%s" % msg) + + # Stream client (receives order updates) + params = { + "api_key": self.api_key, + "api_secret": self.secret_key, + "testnet": self.use_testnet, + "channel_type": "private", + "trace_logging": False, + } + self.logger.info("[bybit_gw_stream_sub.json]%s" % json.dumps(params)) + self.stream_cli = WebSocket(**params) + self.stream_cli.order_stream(on_order_update) + self.stream_cli.execution_stream(on_exe_report) + # Trade client (sends orders) + params = { + "api_key": self.api_key, + "api_secret": self.secret_key, + "testnet": True, + } + self.logger.info("[bybit_gw_start_trd_cli.json]%s" % json.dumps(params)) + self.trade_cli = WebSocketTrading(**params) + params = { + "category": "linear", + } + self.bridge.on_is_ready(True) + + def start(self, bridge: ExecutionGatewayBridge): + def start_wrapper(): + try: + self.start_impl(bridge) + except Exception as e: + self.logger.error( + '[bybit_gw_start_err.json]{ "err": "%s" }' % str(e), exc_info=True + ) + + self.logger.info("[bybit_gw_start.json]%s" % json.dumps({"ts": time.time_ns()})) + self.bridge = bridge + threading.Thread( + target=start_wrapper, + name=f"{self.name}_main", + daemon=True, + ).start() + + def stop(self): + self.logger.info("[bybit_gw_stop.json]%s" % json.dumps({"ts": time.time_ns()})) + self.stop_event.set() + + def create_order(self, req: PyCreateOrderRequest): + self.logger.info("[bybit_gw_crt_ord.json]%s" % str(req)) + if not self.stream_cli or not self.trade_cli or not self.bridge: + self._on_abort( + req.key(), + "crt", + "WebSocket not initialized (stream_cli: %s, trade_cli: %s, bridge: %s)" + % as_bool(self.stream_cli, self.trade_cli, self.bridge), + ) + return + exch_ord_id = uuid.uuid1().hex + bts_id = req.key() + px = req.price() + qty = req.quantity() + self.orders[req.key()] = OrderData( + bts_id=bts_id, exch_id=exch_ord_id, price=px, quantity=qty + ) + sec_name = req.exchange_security_id() + sec = self.securities.get(sec_name) + if not sec: + return + price_decimal_places = get_price_decimal_places(sec) + qty_decimal_places = get_qty_decimal_places(sec) + params = { + "orderLinkId": exch_ord_id, + "category": "linear", + "symbol": sec_name, + "side": "Buy" if req.is_buy() else "Sell", + "orderType": req.order_type().title(), + "price": f"{price_decimal_places:.2f}", + "qty": f"{qty_decimal_places:.2f}", + } + self.logger.info("[bybit_gw_create_order_msg.json]%s" % json.dumps(params)) + self.trade_cli.place_order(lambda msg: self._on_order_ack("crt", msg), **params) + + def cancel_replace_order(self, req: PyCancelReplaceOrderRequest): + self.logger.info("[bybit_gw_cxlrep_ord.json]%s" % req) + if not self.stream_cli or not self.trade_cli: + self._on_abort(req.key(), "cxlrep", "WebSocket client not created.") + return + bts_id = req.key() + ord_data = self.orders.get(bts_id) + if not ord_data: + self._on_abort(req.key(), "cxlrep", "Did not resolve exch order id") + return + sec_name = req.exchange_security_id() + sec = self.securities.get(sec_name) + if not sec: + return + price_decimal_places = get_price_decimal_places(sec) + qty_decimal_places = get_qty_decimal_places(sec) + params = { + "orderLinkId": ord_data.exch_id, + "category": "linear", + "symbol": req.exchange_security_id(), + "price": f"{price_decimal_places:.2f}", + "qty": f"{qty_decimal_places:.2f}", + } + self.trade_cli.amend_order( + lambda msg: self._on_order_ack("cxlrep", msg), **params + ) + + def cancel_order(self, req: PyCancelOrderRequest): + self.logger.info("[bybit_gw_cxl_ord.json]%s" % str(req)) + if not self.stream_cli or not self.trade_cli: + self._on_abort(req.key(), "cxl", "WebSocket client not created.") + return + bts_id = req.key() + ord_data = self.orders.get(bts_id) + if not ord_data: + self._on_abort(req.key(), "cxl", "Did not resolve exch order id") + return + params = { + "orderLinkId": ord_data.exch_id, + "category": "linear", + "symbol": req.exchange_security_id(), + } + self.trade_cli.cancel_order( + lambda msg: self._on_order_ack("cxl", msg), **params + ) + + def on_securities(self, securities: PySecurityList): + self.logger.info( + "[bybit_gw_sec.json][%s]" % ", ".join([str(sec) for sec in securities]) + ) + self.securities = {sec.name(): sec for sec in securities} + diff --git a/src/lib_python_execution/python_execution_gateways/dummy_execution_gateway.py b/src/lib_python_execution/python_execution_gateways/dummy_execution_gateway.py new file mode 100644 index 000000000..ea2ede70f --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/dummy_execution_gateway.py @@ -0,0 +1,241 @@ +import dotenv +import json +import logging +import math +import sys +import traceback +from typing import Any, Optional +import uuid +import websocket + +from binance_client import BinanceClient +import python_execution_module as pyexe + + +BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc" +BINANCE_USDS_FUTURES_API_KEY = ( + "b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0" +) +BINANCE_USDS_FUTURES_SECRET_KEY = ( + "a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492" +) + + +def to_bts_exec_type(exec_type: str, ord_status: str): + match exec_type: + case "TRADE_PREVENTION": + return "REJECTED" + case "NONE": + return "UNDEFINED" + case "TRADE": + return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL" + case _: + return exec_type + + +def to_bts_order_status(ord_status: str): + match ord_status: + case "EXPIRED_IN_MATCH": + return "EXPIRED" + case _: + return ord_status + + +class DummyExecutionGateway(pyexe.ExecutionGateway): + def __init__(self): + super(DummyExecutionGateway, self).__init__() + self.bridge = None + self.client = None + self.start_th = None + self.ws = None + self.orders = {} + self.logger = logging.getLogger(__name__) + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.formatter = logging.Formatter( + "%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s" + ) + self.logger.addHandler(stdout_handler) + self.logger.addHandler( + logging.FileHandler( + "/home/bts/sparkdata/data/logging.python_execution/dummy_log" + ) + ) + self.logger.setLevel(logging.INFO) + env_path = "/workspaces/spark/tools/binance/binance.env" + self.logger.info("DummyExecutionGateway ctr. Loading env") + dotenv.load_dotenv(env_path, interpolate=False) + + def _index_transaction(self, bts_key: int): + exch_key = uuid.uuid1().hex + self.orders[exch_key] = bts_key + return exch_key + + def _on_user_data_msg_core(self, ws: websocket.WebSocket, msg: Any): + self.logger.info("Recv usr data: %s", str(msg)) + if not msg: + self.logger.error("Recv empty usr data msg") + return + if not self.bridge: + self.logger.error("Cannot process usr data. Bridge not created") + return + upd = json.loads(str(msg)) + if "e" in upd: + if upd["e"] == "executionReport": + # Binance spots update + bts_ord_id = self.orders.get(upd["c"]) + is_old_ord = False + if not bts_ord_id: + bts_ord_id = self.orders.get(upd["C"]) + if not bts_ord_id: + self.logger.warning( + "Received update with unknown order id: %s", msg + ) + return + is_old_ord = True + er = pyexe.PyExecutionReport() + er.set_key(bts_ord_id) + er.set_exchange_security_id(upd["s"]) + er.set_security_type("SPOT") + er.set_exec_type(to_bts_exec_type(upd["x"], upd["X"])) + er.set_is_buy(upd["S"] == "BUY") + er.set_price(float(upd["p"])) + er.set_quantity(float(upd["q"])) + er.set_last_filled_price(upd["L"]) + er.set_last_filled_quantity(upd["l"]) + total_filled_qty = float(upd["z"]) + er.set_filled_quantity(total_filled_qty) + total_filled_notional = float(upd["Z"]) + avg_filled_price = ( + total_filled_notional / total_filled_qty + if total_filled_qty > 0 + else math.nan + ) + er.set_avg_filled_price(avg_filled_price) + er.set_order_status(to_bts_order_status(upd["X"])) + er.set_order_type(upd["o"]) + match upd["X"]: + case "CANCELED": + if not is_old_ord: + del self.orders[bts_ord_id] + case "FILLED": + del self.orders[bts_ord_id] + case "REJECTED": + del self.orders[bts_ord_id] + self.bridge.on_execution_report(er) + elif upd["e"] == "ORDER_TRADE_UPDATE": + data = upd["o"] + # Binance Usds Futures order update + bts_ord_id = self.orders.get(data["c"]) + is_old_ord = False + if not bts_ord_id: + bts_ord_id = self.orders.get(data["C"]) + if not bts_ord_id: + self.logger.warning( + "Received dataate with unknown order id: %s", msg + ) + return + is_old_ord = True + + def parse_float(s: Optional[str], default_val=math.nan): + if s is not None: + try: + return float(s) + except Exception: + pass + return default_val + + er = pyexe.PyExecutionReport() + er.set_key(bts_ord_id) + er.set_venue("BINANCE_USDS_FUTURES") + er.set_security_type("FUTURE") + er.set_time_in_force("GTC") + er.set_exchange_order_id(str(data.get("i") or 0)) + # er.set_exchange_order_id(data["i"]) + er.set_exchange_security_id(data["s"]) + er.set_exec_type(to_bts_exec_type(data["x"], data["X"])) + er.set_is_buy(data["S"] == "BUY") + er.set_price(parse_float(data["p"])) + er.set_quantity(parse_float(data["q"])) + er.set_last_filled_price(parse_float(data.get("L"))) + er.set_last_filled_quantity(parse_float(data["l"])) + er.set_filled_quantity(parse_float(data["z"])) + er.set_avg_filled_price(parse_float(data["ap"])) + er.set_order_status(to_bts_order_status(data["X"])) + er.set_order_type(data["o"]) + match data["X"]: + case "CANCELED": + if not is_old_ord: + del self.orders[bts_ord_id] + case "FILLED": + del self.orders[bts_ord_id] + case "REJECTED": + del self.orders[bts_ord_id] + print("Firing this exe report: %s" % str(er), flush=True) + self.bridge.on_execution_report(er) + + def _on_user_data_msg(self, ws: websocket.WebSocket, msg: Any): + try: + self._on_user_data_msg_core(ws, msg) + except Exception: + self.logger.error("on_user_data_msg. %s" % traceback.format_exc()) + + def _on_user_data_open(self, ws: websocket.WebSocket): + self.ws = ws + if self.bridge: + self.bridge.on_is_ready(True) + + def _on_user_data_err(self, ws: websocket.WebSocket, err: str): + self.logger.error("on_user_data_err: %s", err) + + def _on_user_data_close(self, ws: websocket.WebSocket, code: int, msg: str): + self.logger.warning("on_user_data_close: %s %s", str(code), msg) + if self.bridge: + self.bridge.on_is_ready(False) + + def start(self, bridge: pyexe.ExecutionGatewayBridge): + print("DummyExecutionGateway.start") + self.bridge = bridge + self.client = BinanceClient(venue="BINANCE_USDS_FUTURES") + print("DummyExecutionGateway.start. Subscribing to binance user data") + self.client.subscribe_user_data( + on_message=self._on_user_data_msg, + on_open=self._on_user_data_open, + on_close=self._on_user_data_close, + ) + print("DummyExecutionGateway.start. Subscribed to binance user data") + + def cancel_order(self, req: pyexe.PyCancelOrderRequest): + if not self.client: + self.logger.error("Cannot cancel order. BinanceClient not created.") + return + self.logger.info("[cancel_order.json]%s", str(req)) + try: + self.client.request( + "CANCEL_ORDER", + symbol=req.exchange_security_id(), + orig_client_order_id=req.exchange_order_id(), + new_client_order_id=self._index_transaction(req.key()), + ) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) + + def create_order(self, req: pyexe.PyCreateOrderRequest): + if not self.client: + self.logger.error("Cannot create order. BinanceClient not created.") + return + print("hey bud") + self.logger.info("[create_order.json]%s", str(req)) + side = "BUY" if req.is_buy() else "SELL" + try: + self.client.request( + op="CREATE_ORDER", + symbol=req.exchange_security_id(), + price=req.price(), + quantity=f"{req.quantity():.6f}", + side=side, + time_in_force="GTC", + type="LIMIT", + new_client_order_id=self._index_transaction(req.key()), + ) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) diff --git a/src/lib_python_execution/python_execution_gateways/py_execution_utils.py b/src/lib_python_execution/python_execution_gateways/py_execution_utils.py new file mode 100644 index 000000000..e6f39af6c --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/py_execution_utils.py @@ -0,0 +1,158 @@ +import json +import math +import string +import logging +import os +import sys +import threading +import time +from typing import Callable, Optional +import websocket + +import python_execution_module as pyexe + + +def as_bool(*args): + (True if arg else False for arg in args) + + +def to_execution_report( + req: pyexe.PyCreateOrderRequest + | pyexe.PyCancelReplaceOrderRequest + | pyexe.PyCancelOrderRequest, + sec_type: Optional[str] = None, + dst: Optional[pyexe.PyExecutionReport] = None, +): + if not dst: + dst = pyexe.PyExecutionReport() + dst.set_key(req.key()) + dst.set_exchange_security_id(req.exchange_security_id()) + dst.set_venue(req.venue()) + dst.set_is_buy(req.is_buy()) + if sec_type: + dst.set_security_type(sec_type) + if isinstance(req, pyexe.PyCreateOrderRequest): + dst.set_order_type(req.order_type()) + elif isinstance(req, pyexe.PyCancelReplaceOrderRequest): + pass + elif isinstance(req, pyexe.PyCancelOrderRequest): + pass + return dst + + +class StructuredLog: + def __init__(self, **kwargs): + self.kwargs = kwargs + + def __str__(self): + return json.dumps(self.kwargs) + + +class LogFormatter(logging.Formatter): + def __init__(self): + pass + + def formatTime(self, record, datefmt=None): + ct = self.converter(record.created) + if datefmt: + return time.strftime(datefmt, ct) + else: + t = time.strftime("%Y-%m-%d %H:%M:%S", ct) + return f"{t}.{int(record.msecs * 1000):06d}" # microseconds + + def format(self, record): + # Simulate a unique numeric ID + timestamp_ns = int(record.created * 1e9) + system = "OrderMan" + env = "dev" + thread_id = threading.get_ident() + filename_line = f"{record.filename}:{record.lineno}" + timestamp = self.formatTime(record) + + return ( + f"{timestamp}|{timestamp_ns}|{system:<7}|{record.levelname:<5}|" + f"{os.getpid():<3}|{record.threadName:<20}|{thread_id}|" + f"{filename_line:<30}|{env}|{record.getMessage()}" + ) + + +def configure_logger(logger: logging.Logger): + stdout_handler = logging.StreamHandler(sys.stdout) + file_handler = logging.FileHandler( + f"/home/bts/sparkdata/data/logging.sparkd/{logger.name}_log" + ) + formatter = LogFormatter() + stdout_handler.formatter = formatter + file_handler.formatter = formatter + logger.handlers.clear() + logger.addHandler(stdout_handler) + logger.addHandler(file_handler) + logger.setLevel(logging.INFO) + return logger + + +def parse_float(s: Optional[str], default_val=math.nan): + if s is not None: + try: + return float(s) + except Exception: + pass + return default_val + + +def load_gateway_config(name: str, expand_vars: bool = True): + s = "" + with open(f"/home/bts/sparkdata/conf/py_{name}.json") as f: + s = f.read() + if expand_vars: + s = string.Template(s).substitute(os.environ) + return json.loads(s) + + +def run_websocket( + url: str, + stop_event: threading.Event, + logger: logging.Logger, + on_message: Callable[[str], None], + send_ping: Optional[Callable[[websocket.WebSocket], None]] = None, + ping_interval_secs: Optional[int] = 25, +): + conn_num = 0 + if send_ping is None: + + def send_empty_ping(ws): + return ws.ping() + + send_ping = send_empty_ping + + while not stop_event.is_set(): + if conn_num > 0: + # Gradually increase sleep time between attempts, capping at 5min. + sleep_secs = min(conn_num * 5, 300) + logger.warning("Reconnecting to %s in %ds." % (url, sleep_secs)) + time.sleep(sleep_secs) + logger.info("Connecting to %s (attempt no %d)" % (url, conn_num)) + ws = websocket.create_connection(url) + ws.settimeout(5) + logger.info("Connected to %s. Listening for data" % url) + if ping_interval_secs: + + def ping_loop(orig_conn_num): + time.sleep(ping_interval_secs) + while not stop_event.is_set() and conn_num == orig_conn_num: + send_ping(ws) + time.sleep(ping_interval_secs) + + threading.Thread(target=ping_loop(conn_num), daemon=True).start() + try: + msg = ws.recv() + if isinstance(msg, bytes): + on_message(msg.decode("utf-8")) + elif isinstance(msg, str): + on_message(msg) + else: + logger.error("Websocket recv unexpected msg type %s" % str(type(msg))) + + except Exception: + logging.error("Websocket recv threw.", exc_info=True) + continue diff --git a/src/lib_python_execution/python_execution_gateways/simple_test.py b/src/lib_python_execution/python_execution_gateways/simple_test.py new file mode 100644 index 000000000..8ea52c7ff --- /dev/null +++ b/src/lib_python_execution/python_execution_gateways/simple_test.py @@ -0,0 +1,241 @@ +import json +import logging +import math +import os +import sys + +import threading +from threading import Thread, Lock +from time import sleep +from typing import Any, Callable, Mapping +import uuid + +import requests + +import python_execution_module as pyexe +import py_execution_utils +import dotenv +from binance_client import BinanceClient +import websocket + + +BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc" +BINANCE_USDS_FUTURES_API_KEY = ( + "b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0" +) +BINANCE_USDS_FUTURES_SECRET_KEY = ( + "a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492" +) + + +def to_bts_exec_type(exec_type: str, ord_status: str): + match exec_type: + case "TRADE_PREVENTION": + return "REJECTED" + case "NONE": + return "UNDEFINED" + case "TRADE": + return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL" + case _: + return exec_type + + +def to_bts_order_status(ord_status: str): + match ord_status: + case "EXPIRED_IN_MATCH": + return "EXPIRED" + case _: + return ord_status + + +def invoke(target: Callable[[], Any]): + t = threading.Thread(target=target) + t.start() + return t + + +class SimpleTest(pyexe.ExecutionGateway): + def __init__(self): + super(SimpleTest, self).__init__() + self.bridge = None + self.client = None + self.create_order_reqs = [] + self.threads = [] + self.ws = None + self.lock = Lock() + self.orders = {} + self.logger = logging.getLogger(__name__) + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.formatter = logging.Formatter( + "%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s" + ) + self.logger.addHandler(stdout_handler) + self.logger.addHandler( + logging.FileHandler( + "/home/bts/sparkdata/data/logging.python_execution/simple_test" + ) + ) + self.logger.setLevel(logging.INFO) + env_path = "/workspaces/spark/tools/binance/binance.env" + self.logger.info("SimpleTest ctr. Loading env") + dotenv.load_dotenv(env_path, interpolate=False) + + def _invoke(self, target: Callable[[], Any], run_in_background: bool): + if run_in_background: + t = threading.Thread(target=target) + self.threads.append(t) + t.start() + else: + target() + + def _index_transaction(self, bts_key: int): + exch_key = uuid.uuid1().hex + self.orders[exch_key] = bts_key + return exch_key + + def _on_user_data_open(self, ws: websocket.WebSocket): + self.ws = ws + if self.bridge: + self.bridge.on_is_ready(True) + + def _on_user_data_close(self, code: int, msg: str): + self.logger.warning("on_user_data_close: %s %s", str(code), msg) + if self.bridge: + self.bridge.on_is_ready(False) + + def start(self, bridge: pyexe.ExecutionGatewayBridge): + print("DummyExecutionGateway.start") + self.bridge = bridge + self.client = BinanceClient(venue="BINANCE_USDS_FUTURES") + print("DummyExecutionGateway.start. Subscribing to binance user data") + print("DummyExecutionGateway.start. Subscribed to binance user data") + + def delayed_ready(): + self.logger.info("SimpleTest.delayed_ready") + sleep(0.5) + if self.bridge: + self.logger.info( + "SimpleTest.delayed_ready. Notifying bridge that we're ready" + ) + self.bridge.on_is_ready(True) + else: + self.logger.info( + "SimpleTest.delayed_ready. Unable to notify bridge that we're ready (bridge is None!)" + ) + + self._invoke(delayed_ready, True) + + def cancel_order(self, req: pyexe.PyCancelOrderRequest): + if not self.client: + self.logger.error("Cannot cancel order. BinanceClient not created.") + return + self.logger.info("[cancel_order.json]%s", str(req)) + try: + self.client.request( + "CANCEL_ORDER", + symbol=req.exchange_security_id(), + orig_client_order_id=req.exchange_order_id(), + new_client_order_id=self._index_transaction(req.key()), + ) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) + + def create_order(self, req: pyexe.PyCreateOrderRequest): + if not self.client: + self.logger.error("Cannot create order. BinanceClient not created.") + return + self.logger.info("create_order (async). %s" % str(req)) + + # local_req = pyexe.PyCreateOrderRequest() + # local_req.set_exchange_security_id(req.exchange_security_id()) + # local_req.set_key(req.key()) + def impl(): + sleep(0.7) + with self.lock: + self.logger.info("create_order. %s" % str(req)) + er = pyexe.PyExecutionReport() + er.set_key(7) + er.set_exchange_security_id("BNBUSDT") + er.set_exec_type("NEW") + er.set_is_buy(True) + er.set_price(650) + er.set_quantity(0.02) + er.set_last_filled_price(649.50) + er.set_last_filled_quantity(0.012) + er.set_filled_quantity(0.012) + er.set_avg_filled_price(649.50) + er.set_order_status("WORKING") + er.set_order_type("LIMIT") + + er.set_key(req.key()) + er.set_exchange_security_id(req.exchange_security_id()) + er.set_venue(req.venue()) + er.set_exec_type("NEW") + er.set_is_buy(req.is_buy()) + er.set_price(req.price()) + er.set_quantity(req.quantity()) + er.set_last_filled_price( + req.price() - 0.5 if req.is_buy() else req.price() + 0.5 + ) + er.set_last_filled_quantity(0.012) + er.set_filled_quantity(0.012) + er.set_avg_filled_price(er.last_filled_price()) + er.set_order_status("WORKING") + er.set_order_type(req.order_type()) + if self.bridge: + self.bridge.on_execution_report(er) + + self._invoke(impl, True) + self.logger.info("[create_order.json]%s", str(req)) + side = "BUY" if req.is_buy() else "SELL" + try: + res = self.client.request( + op="CREATE_ORDER", + symbol=req.exchange_security_id(), + price=req.price(), + quantity=f"{req.quantity():.6f}", + side=side, + time_in_force="GTC", + type="LIMIT", + new_client_order_id=self._index_transaction(req.key()), + ) + print(str(res), flush=True) + except Exception as ex: + self.logger.error("Create order request threw. %s" % str(ex)) + + +# def create_order(client: BinanceClient, price, quantity, side, logger): +# logger.info("[create_order.json]%s %d @ %d", side, quantity, price) +# try: +# res = client.request( +# op="CREATE_ORDER", +# symbol="BNBUSDT", +# price=price, +# quantity=f"{quantity:.5f}", +# side=side, +# time_in_force="GTC", +# type="LIMIT", +# # new_client_order_id=self._index_transaction(req.key()), +# ) +# if res: +# print("%d %s" % (res.status_code, res.text), flush=True) +# except Exception as ex: +# logger.error("Create order request threw. %s" % str(ex)) + + +# if __name__ == "__main__": +# print("DummyExecutionGateway.start") +# logger = logging.getLogger(__name__) +# logger.setLevel(logging.INFO) +# env_path = "/workspaces/spark/tools/binance/binance.env" +# dotenv.load_dotenv(env_path, interpolate=False) +# client = BinanceClient(venue="BINANCE_USDS_FUTURES") +# # req = pyexe.PyCreateOrderRequest() +# # req.set_exchange_security_id("BNBUSDT") +# # req.set_price(650) +# # req.set_quantity(0.015) +# # req.set_is_buy(True) +# # req.set_venue("BINANCE_USDS_FUTURES") +# # req.set_order_type("LIMIT") +# # req.set_key(5) +# create_order(client, 650, 0.02, "BUY", logger)