feat: Support python execution plugins
This commit is contained in:
1 parent
ca82042669
commit
b227fc6254
46 files changed
+4898
-33
No files matched your search
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,112 @@
|
||||
<!-- Links -->
|
||||
|
||||
[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/<name>_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
|
||||
|
||||
```
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "execution_gateway.h"
|
||||
|
||||
namespace python_execution {
|
||||
|
||||
ExecutionGateway::~ExecutionGateway() = default;
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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<PyCreateOrderRequest> req) = 0;
|
||||
virtual void cancel_order(std::shared_ptr<PyCancelOrderRequest> req) = 0;
|
||||
virtual void cancel_replace_order(
|
||||
std::shared_ptr<PyCancelReplaceOrderRequest> req) = 0;
|
||||
virtual void on_securities(
|
||||
const std::vector<std::shared_ptr<bts::md::py_interop::PySecurity>>
|
||||
&securities) = 0;
|
||||
virtual void stop() = 0;
|
||||
};
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "execution_gateway_bridge.h"
|
||||
|
||||
namespace python_execution {
|
||||
|
||||
ExecutionGatewayBridge::~ExecutionGatewayBridge() = default;
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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<PyExecutionReport>) {}
|
||||
virtual void on_position_info(std::shared_ptr<PyPositionInfo>) {}
|
||||
virtual void on_is_ready(bool) {}
|
||||
};
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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 <pybind11/pybind11.h>
|
||||
|
||||
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<string> 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<PyExecutionReport> 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<PyPositionInfo> 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<const PyExecutionReport> &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<std::shared_ptr<bts::md::py_interop::PySecurity>> 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<const PyExecutionReport>
|
||||
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<ExecutionGateway> 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<PyCreateOrderRequest> req) {
|
||||
req_type = ReqType::CREATE;
|
||||
gw->create_order(std::move(req));
|
||||
},
|
||||
[&](std::shared_ptr<PyCancelReplaceOrderRequest> req) {
|
||||
req_type = ReqType::CANCEL_REPLACE;
|
||||
gw->cancel_replace_order(std::move(req));
|
||||
},
|
||||
[&](std::shared_ptr<PyCancelOrderRequest> 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
|
||||
@@ -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<std::string> module_paths);
|
||||
~ExecutionGatewayBridgeImpl() override;
|
||||
|
||||
// Python interface
|
||||
void on_execution_report(std::shared_ptr<PyExecutionReport>) override;
|
||||
void on_position_info(std::shared_ptr<PyPositionInfo>) override;
|
||||
void on_is_ready(bool) override;
|
||||
|
||||
// C++ interface
|
||||
bts::core::Delegate<void(std::shared_ptr<const PyExecutionReport>)> &
|
||||
exe_report_callback();
|
||||
void on_order_msg(PyOrderRequest msg);
|
||||
void on_securities(
|
||||
std::vector<std::shared_ptr<bts::md::py_interop::PySecurity>>
|
||||
securities);
|
||||
bool wait_for_ready(bts::core::TimeSpan timeout);
|
||||
bool pop_exe_report(std::shared_ptr<const PyExecutionReport> &result);
|
||||
std::shared_ptr<const PyExecutionReport> pop_exe_report();
|
||||
int run_py(volatile bool *keep_going);
|
||||
|
||||
private:
|
||||
std::string name;
|
||||
std::string target;
|
||||
std::vector<std::string> module_paths;
|
||||
bts::utils::ConcurrentValueStore<bool> is_ready;
|
||||
bts::collections::ConcurrentQueue<std::shared_ptr<PyExecutionReport>>
|
||||
incoming_exe_reports;
|
||||
bts::collections::ConcurrentQueue<std::shared_ptr<PyPositionInfo>>
|
||||
incoming_pos_infos;
|
||||
bts::collections::ConcurrentQueue<PyOrderRequest> outgoing_reqs;
|
||||
std::vector<std::shared_ptr<bts::md::py_interop::PySecurity>> securities;
|
||||
volatile bool is_securities_dirty = false;
|
||||
ExecutionGateway *gw;
|
||||
};
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -0,0 +1,68 @@
|
||||
#include "py_cancel_order_request.h"
|
||||
#include "spark/domain_model/Venue.h"
|
||||
#include "spark/orderman/CancelOrderMsg.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
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<string>();
|
||||
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
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
#include <cstdint>
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,80 @@
|
||||
#include "py_cancel_replace_order_request.h"
|
||||
#include "spark/domain_model/Venue.h"
|
||||
#include "spark/orderman/CancelReplaceOrderMsg.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
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<string>();
|
||||
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
|
||||
@@ -0,0 +1,110 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -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 <nlohmann/json.hpp>
|
||||
|
||||
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<string>();
|
||||
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
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "py_execution_gateway.h"
|
||||
|
||||
namespace python_execution {
|
||||
|
||||
PyExecutionGateway::~PyExecutionGateway() = default;
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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 <pybind11/pybind11.h>
|
||||
|
||||
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<PyCreateOrderRequest> req) override {
|
||||
PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, create_order, req);
|
||||
}
|
||||
void cancel_order(std::shared_ptr<PyCancelOrderRequest> req) override {
|
||||
PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, cancel_order, req);
|
||||
}
|
||||
void cancel_replace_order(
|
||||
std::shared_ptr<PyCancelReplaceOrderRequest> req) override {
|
||||
PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, cancel_replace_order, req);
|
||||
}
|
||||
|
||||
// cpp calls into py
|
||||
void on_securities(
|
||||
const std::vector<std::shared_ptr<bts::md::py_interop::PySecurity>>
|
||||
&securities) override {
|
||||
PYBIND11_OVERLOAD_PURE(
|
||||
void, ExecutionGateway, on_securities, std::move(securities));
|
||||
}
|
||||
void stop() override {
|
||||
PYBIND11_OVERLOAD_PURE(void, ExecutionGateway, stop);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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 <variant>
|
||||
|
||||
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<const bts::api::Security *(
|
||||
bts::api::Venue, bts::api::SecurityType, const std::string &)>
|
||||
find_sec) {
|
||||
*er.order_key = key_;
|
||||
er.account_name->copy_from(account_);
|
||||
if (std::holds_alternative<ExchangeOrderID>(er.exchange_order_id)) {
|
||||
std::get<ExchangeOrderID>(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<double>::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<uint64_t>(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
|
||||
@@ -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 <cstdint>
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
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<const bts::api::Security *(
|
||||
bts::api::Venue, bts::api::SecurityType, const std::string &)>
|
||||
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
|
||||
@@ -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 <memory>
|
||||
#include <pybind11/detail/common.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl_bind.h>
|
||||
|
||||
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<T>)
|
||||
|
||||
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 <name>
|
||||
// Binds a pseudo property with getter/setter methods.
|
||||
// Binds getter -> <name>, and setter -> set_<name>.
|
||||
#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_<PyCreateOrderRequest, shared_ptr<PyCreateOrderRequest>>(
|
||||
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_<PyCancelOrderRequest, shared_ptr<PyCancelOrderRequest>>(
|
||||
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<PyCancelReplaceOrderRequest>>(
|
||||
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_<PyExecutionReport, shared_ptr<PyExecutionReport>>(
|
||||
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_<PyPositionInfo, shared_ptr<PyPositionInfo>>(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_<ExecutionGatewayBridge>(m, "ExecutionGatewayBridge")
|
||||
.def(py::init<>())
|
||||
.DEF(ExecutionGatewayBridge, on_execution_report)
|
||||
.DEF(ExecutionGatewayBridge, on_position_info)
|
||||
.DEF(ExecutionGatewayBridge, on_is_ready);
|
||||
py::class_<ExecutionGateway, PyExecutionGateway>(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);
|
||||
}
|
||||
@@ -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 <variant>
|
||||
|
||||
namespace python_execution {
|
||||
|
||||
using PyOrderRequest = std::variant<
|
||||
std::shared_ptr<PyCreateOrderRequest>,
|
||||
std::shared_ptr<PyCancelReplaceOrderRequest>,
|
||||
std::shared_ptr<PyCancelOrderRequest>>;
|
||||
|
||||
} // namespace python_execution
|
||||
@@ -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
|
||||
@@ -0,0 +1,134 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -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
|
||||
@@ -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 <stream1> <stream2> ... or --exch-info or --list-symbols)"
|
||||
)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
code = _main()
|
||||
exit(code)
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
@@ -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}
|
||||
|
||||
@@ -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))
|
||||
@@ -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
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user