refactor: Consolidate all py interop into single lib
It was just too hard trying to make it work with separate libs. The main issue was getting the python md and execution modules to recognize PySecurityList and other types defined in the core module.
This commit is contained in:
1 parent
7c9330650d
commit
bdd5e08b60
87 files changed
+1093
-2926
No files matched your search
@@ -0,0 +1,7 @@
|
||||
#include "md_bridge.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
MdBridge::~MdBridge() = default;
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/py_book.h"
|
||||
#include "python_interop/md/py_trade.h"
|
||||
#include "python_interop/py_security.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
class MdBridge {
|
||||
public:
|
||||
virtual ~MdBridge();
|
||||
|
||||
// Python interface
|
||||
virtual void on_securities(
|
||||
const std::vector<std::shared_ptr<PySecurity>> &securities) = 0;
|
||||
virtual void on_books(const std::vector<std::shared_ptr<PyBook>> &books) = 0;
|
||||
virtual void on_trades(
|
||||
const std::vector<std::shared_ptr<PyTrade>> &trades) = 0;
|
||||
};
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,128 @@
|
||||
#include "python_interop/md/md_bridge_impl.h"
|
||||
#include "python_interop/md/md_provider.h"
|
||||
#include "python_interop/python_activator.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
#include "spark/logging/logging.h"
|
||||
#include "spark/logging/trace_log.h"
|
||||
#include "spark/utils/Delegate.h"
|
||||
#include "spark/utils/stopwatch.h"
|
||||
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <thread>
|
||||
|
||||
using std::shared_ptr;
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
using bts::core::Delegate;
|
||||
using bts::io::json_formatter;
|
||||
using bts::utils::Stopwatch;
|
||||
using python_interop::PythonActivatorT;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#define ASSERT_FN(test, fn, ...) \
|
||||
bts_assert_msgf(test, "md_bridge::" fn ". " __VA_ARGS__)
|
||||
#define LOG_FN(level, fn, ...) LOG(md, level, "md_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(md, level, std::string("md_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 DIAG_TRACE_PARAMS(name, params) \
|
||||
LOG_TRACE_PARAMS( \
|
||||
md, bts::Diag, std::string("md_bridge"), std::string(name), params)
|
||||
|
||||
#define INFO_TRACE_PARAMS(name, params) \
|
||||
LOG_TRACE_PARAMS( \
|
||||
md, bts::Info, std::string("md_bridge"), std::string(name), params)
|
||||
|
||||
#define WARN_TRACE_PARAMS(name, params) \
|
||||
LOG_TRACE_PARAMS( \
|
||||
md, bts::Warn, std::string("md_bridge"), std::string(name), params)
|
||||
|
||||
MdBridgeImpl::MdBridgeImpl(string target, vector<string> module_paths)
|
||||
: target(std::move(target)), module_paths(std::move(module_paths)) {}
|
||||
|
||||
void MdBridgeImpl::on_securities(
|
||||
const std::vector<std::shared_ptr<PySecurity>> &securities) {
|
||||
INFO_TRACE_PARAMS("on_securities", securities.size());
|
||||
incoming_securities.push_many(securities.begin(), securities.end());
|
||||
}
|
||||
|
||||
void MdBridgeImpl::on_books(const std::vector<std::shared_ptr<PyBook>> &books) {
|
||||
DIAG_TRACE_PARAMS("on_books", json_formatter(books.size()));
|
||||
incoming_books.push_many(books.begin(), books.end());
|
||||
}
|
||||
|
||||
void MdBridgeImpl::on_trades(
|
||||
const std::vector<std::shared_ptr<PyTrade>> &trades) {
|
||||
DIAG_TRACE_PARAMS("on_trades", json_formatter(trades.size()));
|
||||
incoming_trades.push_many(trades.begin(), trades.end());
|
||||
}
|
||||
|
||||
bool MdBridgeImpl::pop_security(shared_ptr<const PySecurity> &result) {
|
||||
auto res = incoming_securities.pop();
|
||||
if (res) {
|
||||
result = std::move(*res);
|
||||
return true;
|
||||
}
|
||||
result = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MdBridgeImpl::pop_book(shared_ptr<const PyBook> &result) {
|
||||
auto res = incoming_books.pop();
|
||||
if (res) {
|
||||
result = std::move(*res);
|
||||
return true;
|
||||
}
|
||||
result = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MdBridgeImpl::pop_trade(shared_ptr<const PyTrade> &result) {
|
||||
auto res = incoming_trades.pop();
|
||||
if (res) {
|
||||
result = std::move(*res);
|
||||
return true;
|
||||
}
|
||||
result = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
int MdBridgeImpl::run_py(volatile bool *keep_going) {
|
||||
bts_assert(keep_going != nullptr);
|
||||
PythonActivatorT<MdProvider> provider_activator{target, module_paths};
|
||||
provider = provider_activator.get_target([&](MdProvider &pro) {
|
||||
// This will start another thread in python, and call back into c++ from there.
|
||||
auto sw = Stopwatch::start_new();
|
||||
pro.start(this);
|
||||
INFO_TRACE_PARAMS(
|
||||
"run_py",
|
||||
json_formatter(fmt::format(
|
||||
"MdProvider.start took {:.2f}ms", sw.elapsed().total_millis())));
|
||||
});
|
||||
// Release gil to let python run
|
||||
py::gil_scoped_release gil_rel;
|
||||
while (*keep_going) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
MdBridgeImpl::~MdBridgeImpl() = default;
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/md_bridge.h"
|
||||
#include "python_interop/md/md_provider.h"
|
||||
#include "spark/collections/concurrent_queue.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
class MdBridgeImpl : public MdBridge {
|
||||
public:
|
||||
MdBridgeImpl(std::string target, std::vector<std::string> module_paths);
|
||||
~MdBridgeImpl();
|
||||
|
||||
// Python interface
|
||||
void on_securities(
|
||||
const std::vector<std::shared_ptr<PySecurity>> &securities) override;
|
||||
void on_books(const std::vector<std::shared_ptr<PyBook>> &books) override;
|
||||
void on_trades(const std::vector<std::shared_ptr<PyTrade>> &trades) override;
|
||||
|
||||
// C++ interface
|
||||
bool pop_security(std::shared_ptr<const PySecurity> &result);
|
||||
bool pop_book(std::shared_ptr<const PyBook> &result);
|
||||
bool pop_trade(std::shared_ptr<const PyTrade> &result);
|
||||
int run_py(volatile bool *keep_going);
|
||||
|
||||
private:
|
||||
std::string target;
|
||||
std::vector<std::string> module_paths;
|
||||
collections::ConcurrentQueue<std::shared_ptr<const PySecurity>>
|
||||
incoming_securities;
|
||||
collections::ConcurrentQueue<std::shared_ptr<const PyBook>> incoming_books;
|
||||
collections::ConcurrentQueue<std::shared_ptr<const PyTrade>> incoming_trades;
|
||||
MdProvider *provider;
|
||||
};
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "python_interop/md/md_provider.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
MdProvider::~MdProvider() = default;
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/md_bridge.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
class MdProvider {
|
||||
public:
|
||||
virtual ~MdProvider();
|
||||
virtual void start(MdBridge *bridge) = 0;
|
||||
virtual void stop() = 0;
|
||||
};
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "py_book.h"
|
||||
#include "python_interop/md/py_book_level.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
static const void validate_depth_array(const pybind11::buffer_info &info) {
|
||||
if (info.ndim != 2 || info.shape[0] < 0 || info.shape[1] != 2) {
|
||||
throw std::runtime_error(fmt::format(
|
||||
"Expected array of shape (10, 2). Actually got ({}, {}, {})",
|
||||
info.ndim, info.shape[0], info.shape[1]));
|
||||
}
|
||||
}
|
||||
|
||||
static void to_book_side(
|
||||
PyBookSide &dest, const PyBook::PyDepthArray &src, std::size_t count) {
|
||||
auto r = src.unchecked<2>();
|
||||
PyBookLevel lvl;
|
||||
for (std::size_t i = 0; i < count; i++) {
|
||||
double px = r(i, 0);
|
||||
double qty = r(i, 1);
|
||||
if (std::isnan(px) || !(qty > 0)) {
|
||||
break;
|
||||
}
|
||||
lvl.set_price(r(i, 0));
|
||||
lvl.set_quantity(r(i, 1));
|
||||
dest.set_level(lvl);
|
||||
}
|
||||
}
|
||||
|
||||
void PyBook::set_data(
|
||||
std::string exchange_security_id,
|
||||
std::string venue,
|
||||
std::string security_type,
|
||||
PyDepthArray bids,
|
||||
PyDepthArray asks) {
|
||||
const auto bids_info = bids.request();
|
||||
const auto asks_info = asks.request();
|
||||
validate_depth_array(bids_info);
|
||||
validate_depth_array(asks_info);
|
||||
exchange_security_id_ = std::move(exchange_security_id);
|
||||
venue_ = std::move(venue);
|
||||
security_type_ = std::move(security_type);
|
||||
bids_.set_is_ascending(false);
|
||||
asks_.set_is_ascending(true);
|
||||
const size_t n_bids = bids_info.size / 2;
|
||||
const size_t n_asks = asks_info.size / 2;
|
||||
to_book_side(bids_, bids, n_bids);
|
||||
to_book_side(asks_, asks, n_asks);
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,160 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/py_book_level.h"
|
||||
#include "python_interop/md/py_book_side.h"
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
#include "spark/utils/bts_assert.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
/**
|
||||
* @brief An L2 Order Book (both sides of the market).
|
||||
*/
|
||||
class PyBook {
|
||||
public:
|
||||
// A more performant alternative to PyBookSide. Populate bid/ask numpy arrays
|
||||
// in python, then init everything in a single call (set_data).
|
||||
using PyDepthArray = pybind11::
|
||||
array_t<double, pybind11::array::c_style | pybind11::array::forcecast>;
|
||||
|
||||
/**
|
||||
* Gets the exchange security id. This is typically the security's name
|
||||
* (e.g., "BTS-PERPETUAL", or "ESH5").
|
||||
*
|
||||
* @note Should be unique for each security at a particular venue (i.e., a single
|
||||
* venue cannot have 2 securities with the same name). MUST be unique for each security
|
||||
* of the same type (e.g., SPOT, FUTURE, OPTION) at a particular venue.
|
||||
*
|
||||
* @note There is no "security_id" member because that is an internal id that
|
||||
* we generate elsewhere in c++ code. The python plugins just need to set the
|
||||
* venue and exchange_security_id.
|
||||
*/
|
||||
const std::string &exchange_security_id() const;
|
||||
/**
|
||||
* @brief Sets the exchange security id.
|
||||
*
|
||||
* @param value The new exchange security id.
|
||||
*/
|
||||
void set_exchange_security_id(std::string value);
|
||||
|
||||
/**
|
||||
* @brief Gets the name of the venue (i.e., exchange).
|
||||
*
|
||||
* @return const std::string& The name of the venue.
|
||||
*/
|
||||
const std::string &venue() const;
|
||||
void set_venue(std::string value);
|
||||
|
||||
/**
|
||||
* @brief Gets the name of the security type (e.g., "SPOT", "FUTURE", "OPTION").
|
||||
*
|
||||
* @return const std::string& The name of the security type.
|
||||
*/
|
||||
const std::string &security_type() const;
|
||||
/**
|
||||
* @brief Sets the security type.
|
||||
*
|
||||
* @param value The new security type (should be "SPOT", "FUTURE", or "OPTION").
|
||||
*/
|
||||
void set_security_type(std::string value);
|
||||
|
||||
PyBookSide &bids();
|
||||
const PyBookSide &bids() const;
|
||||
void set_bids(PyBookSide bids);
|
||||
|
||||
PyBookSide &asks();
|
||||
const PyBookSide &asks() const;
|
||||
void set_asks(PyBookSide asks);
|
||||
|
||||
/**
|
||||
* Sets all data at once (more performant than setting props one at a time
|
||||
* when calling from python).
|
||||
*/
|
||||
void set_data(
|
||||
std::string exchange_security_id,
|
||||
std::string venue,
|
||||
std::string security_type,
|
||||
PyDepthArray bids,
|
||||
PyDepthArray asks);
|
||||
|
||||
/**
|
||||
* @brief Gets the number of levels in the book (i.e., the number of prices
|
||||
* with resting orders).
|
||||
*/
|
||||
constexpr int size() const;
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
std::string venue_;
|
||||
std::string security_type_;
|
||||
std::string exchange_security_id_;
|
||||
PyBookSide bids_;
|
||||
PyBookSide asks_;
|
||||
};
|
||||
|
||||
void to_json(nlohmann::json &j, const PyBook &bk);
|
||||
void from_json(const nlohmann::json &j, PyBook &bk);
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
FMT_IMPL(bts::md::py_interop::PyBook, bs, "{}", bts::io::json_formatter(bs));
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
inline const std::string &PyBook::venue() const { return venue_; }
|
||||
inline void PyBook::set_venue(std::string value) { venue_ = std::move(value); }
|
||||
|
||||
inline const std::string &PyBook::security_type() const {
|
||||
return security_type_;
|
||||
}
|
||||
inline void PyBook::set_security_type(std::string value) {
|
||||
security_type_ = std::move(value);
|
||||
}
|
||||
|
||||
inline const std::string &PyBook::exchange_security_id() const {
|
||||
return exchange_security_id_;
|
||||
}
|
||||
inline void PyBook::set_exchange_security_id(std::string value) {
|
||||
exchange_security_id_ = std::move(value);
|
||||
}
|
||||
|
||||
inline PyBookSide &PyBook::bids() { return bids_; }
|
||||
inline const PyBookSide &PyBook::bids() const { return bids_; }
|
||||
inline void PyBook::set_bids(PyBookSide bids) { bids_ = std::move(bids); }
|
||||
|
||||
inline PyBookSide &PyBook::asks() { return asks_; }
|
||||
inline const PyBookSide &PyBook::asks() const { return asks_; }
|
||||
inline void PyBook::set_asks(PyBookSide asks) { asks_ = std::move(asks); }
|
||||
|
||||
constexpr int PyBook::size() const { return bids_.size() + asks_.size(); }
|
||||
|
||||
inline std::string PyBook::to_string() const {
|
||||
return fmt::format("{}", *this);
|
||||
}
|
||||
|
||||
inline void to_json(nlohmann::json &j, const PyBook &bk) {
|
||||
j["bids"] = bk.bids();
|
||||
j["asks"] = bk.asks();
|
||||
}
|
||||
|
||||
inline void from_json(const nlohmann::json &j, PyBook &bk) {
|
||||
bk.set_exchange_security_id(j.at("sec").get<std::string>());
|
||||
bk.set_venue(j.at("venue").get<std::string>());
|
||||
bk.set_security_type(j.at("typ").get<std::string>());
|
||||
bk.set_bids(j.at("bids").get<PyBookSide>());
|
||||
bk.set_asks(j.at("asks").get<PyBookSide>());
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <limits>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
class PyBookLevel {
|
||||
public:
|
||||
constexpr PyBookLevel() = default;
|
||||
|
||||
constexpr double price() const;
|
||||
void set_price(double value);
|
||||
|
||||
constexpr double quantity() const;
|
||||
void set_quantity(double value);
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
double price_{std::numeric_limits<double>::quiet_NaN()};
|
||||
double quantity_{0};
|
||||
};
|
||||
|
||||
std::ostream &operator<<(std::ostream &out, const PyBookLevel &l) noexcept;
|
||||
|
||||
void to_json(nlohmann::json &j, const PyBookLevel &l);
|
||||
void from_json(const nlohmann::json &j, PyBookLevel &l);
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
FMT_IMPL(bts::md::py_interop::PyBookLevel, l, "{}", bts::io::json_formatter(l));
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
constexpr double PyBookLevel::price() const { return price_; }
|
||||
inline void PyBookLevel::set_price(double value) { price_ = value; }
|
||||
|
||||
constexpr double PyBookLevel::quantity() const { return quantity_; }
|
||||
inline void PyBookLevel::set_quantity(double value) { quantity_ = value; }
|
||||
|
||||
inline std::string PyBookLevel::to_string() const {
|
||||
return fmt::format("{}", *this);
|
||||
}
|
||||
|
||||
inline void to_json(nlohmann::json &j, const PyBookLevel &l) {
|
||||
j["p"] = l.price();
|
||||
j["q"] = l.quantity();
|
||||
}
|
||||
|
||||
inline void from_json(const nlohmann::json &j, PyBookLevel &l) {
|
||||
l.set_price(j.at("p").get<double>());
|
||||
l.set_quantity(j.at("q").get<double>());
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(
|
||||
std::ostream &out, const PyBookLevel &l) noexcept {
|
||||
out << fmt::format("{}", l);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "py_book_side.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
void PyBookSide::set_level(PyBookLevel level) {
|
||||
if (std::isnan(level.price())) {
|
||||
std::cerr << "PyBookLevel invalid price (nan)" << std::endl;
|
||||
return;
|
||||
}
|
||||
if (level.quantity() < 0) {
|
||||
std::cerr << "PyBookLevel invalid quantity (less than 0)" << std::endl;
|
||||
return;
|
||||
}
|
||||
auto it = std::lower_bound(
|
||||
levels_.begin(), levels_.end(), level,
|
||||
[](const auto &lhs, const auto &rhs) {
|
||||
return lhs.price() < rhs.price();
|
||||
});
|
||||
if (it == levels_.end()) {
|
||||
if (level.quantity() == 0) {
|
||||
std::cerr << "PyBookLevel " << to_string()
|
||||
<< " indicates remove op, but the price level does not exist"
|
||||
<< std::endl;
|
||||
return;
|
||||
}
|
||||
levels_.push_back(std::move(level));
|
||||
} else if (it->price() == level.price()) {
|
||||
if (level.quantity() == 0) {
|
||||
levels_.erase(it);
|
||||
} else {
|
||||
*it = std::move(level);
|
||||
}
|
||||
} else {
|
||||
levels_.insert(it, std::move(level));
|
||||
}
|
||||
}
|
||||
|
||||
std::string PyBookSide::to_string_pretty() const {
|
||||
std::string rv;
|
||||
if (is_ascending_) {
|
||||
bool is_first = true;
|
||||
for (const auto &level : levels_) {
|
||||
if (is_first) {
|
||||
is_first = false;
|
||||
} else {
|
||||
rv.append(", ");
|
||||
}
|
||||
rv.append(level.to_string());
|
||||
}
|
||||
} else {
|
||||
bool is_first = true;
|
||||
for (auto it = levels_.rbegin(); it != levels_.rend(); it++) {
|
||||
if (is_first) {
|
||||
is_first = false;
|
||||
} else {
|
||||
rv.append(", ");
|
||||
}
|
||||
rv.append(it->to_string());
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/py_book_level.h"
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
/**
|
||||
* @brief L2 Order Book for one side of the market (i.e., bids or offers).
|
||||
*
|
||||
* @details Bid market levels should be in DESCENDING order by price, while Ask
|
||||
* levels (offers) should be in ASCENDING order. Another way to think about it
|
||||
* is the price levels are sorted by their distance from the opposite market.
|
||||
*/
|
||||
class PyBookSide {
|
||||
public:
|
||||
constexpr bool is_ascending();
|
||||
void set_is_ascending(bool is_ascending);
|
||||
|
||||
constexpr PyBookLevel get_level(int index);
|
||||
constexpr PyBookLevel get_level(int index) const;
|
||||
void set_level(PyBookLevel level);
|
||||
|
||||
constexpr int size() const;
|
||||
|
||||
std::string to_string() const;
|
||||
std::string to_string_pretty() const;
|
||||
|
||||
private:
|
||||
std::vector<PyBookLevel> levels_;
|
||||
bool is_ascending_;
|
||||
|
||||
friend void to_json(nlohmann::json &j, const PyBookSide &bs);
|
||||
friend void from_json(const nlohmann::json &j, PyBookSide &bs);
|
||||
};
|
||||
|
||||
void to_json(nlohmann::json &j, const PyBookSide &bs);
|
||||
void from_json(const nlohmann::json &j, PyBookSide &bs);
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
FMT_IMPL(
|
||||
bts::md::py_interop::PyBookSide, bs, "{}", bts::io::json_formatter(bs));
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
constexpr bool PyBookSide::is_ascending() { return is_ascending_; }
|
||||
|
||||
inline void PyBookSide::set_is_ascending(bool is_ascending) {
|
||||
is_ascending_ = is_ascending;
|
||||
}
|
||||
|
||||
constexpr PyBookLevel PyBookSide::get_level(int index) {
|
||||
if (!is_ascending_) {
|
||||
index = levels_.size() - 1 - index;
|
||||
}
|
||||
return levels_.at(index);
|
||||
}
|
||||
|
||||
constexpr PyBookLevel PyBookSide::get_level(int index) const {
|
||||
if (!is_ascending_) {
|
||||
index = levels_.size() - 1 - index;
|
||||
}
|
||||
return levels_.at(index);
|
||||
}
|
||||
|
||||
constexpr int PyBookSide::size() const { return levels_.size(); }
|
||||
|
||||
inline std::string PyBookSide::to_string() const {
|
||||
return fmt::format("{}", *this);
|
||||
}
|
||||
|
||||
inline void to_json(nlohmann::json &j, const PyBookSide &bs) { j = bs.levels_; }
|
||||
|
||||
inline void from_json(const nlohmann::json &j, PyBookSide &bs) {
|
||||
j.get_to(bs.levels_);
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(
|
||||
std::ostream &out, const PyBookSide &bs) noexcept {
|
||||
out << fmt::format("{}", bs);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "py_md_provider.h"
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
PyMdProvider::~PyMdProvider() = default;
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include "python_interop/md/md_bridge.h"
|
||||
#include "python_interop/md/md_provider.h"
|
||||
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
/**
|
||||
* An implementation of `bts::md::py_interop::MdProvider` that binds to a python object at runtime.
|
||||
*
|
||||
* @note The python object must derive from 'python_md_module.MdProvider', and define methods:
|
||||
* 1. 'start(md_bridge: python_md_module.MdBridge)'
|
||||
* 2. 'stop'
|
||||
* @note 'python_md_module' is a python module defined by us in c++ (see 'py_module.cpp').
|
||||
*/
|
||||
class PyMdProvider : public MdProvider {
|
||||
public:
|
||||
using MdProvider::MdProvider;
|
||||
|
||||
~PyMdProvider() override;
|
||||
|
||||
void start(MdBridge *bridge) override {
|
||||
PYBIND11_OVERLOAD_PURE(void, MdProvider, start, bridge);
|
||||
}
|
||||
|
||||
void stop() override { PYBIND11_OVERLOAD_PURE(void, MdProvider, stop); }
|
||||
};
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "md_provider.h"
|
||||
#include "python_interop/md/py_book_level.h"
|
||||
#include "python_interop/md/py_book_side.h"
|
||||
#include "python_interop/md/py_md_provider.h"
|
||||
#include "python_interop/md/py_trade.h"
|
||||
|
||||
#include <pybind11/detail/common.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl_bind.h>
|
||||
|
||||
using bts::md::py_interop::MdBridge;
|
||||
using bts::md::py_interop::MdProvider;
|
||||
using bts::md::py_interop::PyBook;
|
||||
using bts::md::py_interop::PyBookLevel;
|
||||
using bts::md::py_interop::PyBookSide;
|
||||
using bts::md::py_interop::PyMdProvider;
|
||||
using bts::md::py_interop::PyTrade;
|
||||
using std::shared_ptr;
|
||||
|
||||
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
#define _STR(x) #x
|
||||
// In general, we bind c++ methods to python methods with the same name verbatim.
|
||||
// The DEF macro avoids typos in the python method name for this common case.
|
||||
#define DEF(type, member) def(_STR(member), &type::member)
|
||||
#define 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))
|
||||
|
||||
// Define python module with c++ classes.
|
||||
PYBIND11_MODULE(python_md_module, m) {
|
||||
using BookSideGetter = PyBookSide &(PyBook::*)();
|
||||
using BookLevelGetter = PyBookLevel (PyBookSide::*)(int) const;
|
||||
// book
|
||||
py::class_<PyBookLevel>(m, "PyBookLevel")
|
||||
.def(py::init<>())
|
||||
.PROP(PyBookLevel, price)
|
||||
.PROP(PyBookLevel, quantity);
|
||||
py::class_<PyBookSide>(m, "PyBookSide")
|
||||
.def(py::init<>())
|
||||
.EXPLICIT_DEF(PyBookSide, get_level, BookLevelGetter)
|
||||
.DEF(PyBookSide, set_level)
|
||||
.PROP(PyBookSide, is_ascending)
|
||||
.def("__len__", &PyBookSide::size)
|
||||
.def("__str__", &PyBookSide::to_string);
|
||||
py::class_<PyBook, shared_ptr<PyBook>>(m, "PyBook")
|
||||
.def(py::init<>())
|
||||
.PROP(PyBook, venue)
|
||||
.PROP(PyBook, security_type)
|
||||
.PROP(PyBook, exchange_security_id)
|
||||
.EXPLICIT_DEF(PyBook, bids, BookSideGetter)
|
||||
.DEF(PyBook, set_bids)
|
||||
.EXPLICIT_DEF(PyBook, asks, BookSideGetter)
|
||||
.DEF(PyBook, set_asks)
|
||||
.def(
|
||||
"set_data", &PyBook::set_data, py::arg("exch_sec_id"),
|
||||
py::arg("venue"), py::arg("sec_type"), py::arg("bids"),
|
||||
py::arg("asks"))
|
||||
.def("__len__", &PyBook::size)
|
||||
.def("__str__", &PyBook::to_string);
|
||||
py::bind_vector<std::vector<shared_ptr<PyBook>>>(m, "PyBookList");
|
||||
// trade
|
||||
py::class_<PyTrade, shared_ptr<PyTrade>>(m, "PyTrade")
|
||||
.def(py::init<>())
|
||||
.PROP(PyTrade, venue)
|
||||
.PROP(PyTrade, security_type)
|
||||
.PROP(PyTrade, exchange_security_id)
|
||||
.PROP(PyTrade, price)
|
||||
.PROP(PyTrade, quantity)
|
||||
.PROP(PyTrade, aggressor_side)
|
||||
.PROP(PyTrade, timestamp);
|
||||
py::bind_vector<std::vector<shared_ptr<PyTrade>>>(m, "PyTradeList");
|
||||
// md bridge
|
||||
py::class_<MdBridge>(m, "MdBridge")
|
||||
.DEF_ARGS(MdBridge, on_securities, py::arg("securities"))
|
||||
.DEF_ARGS(MdBridge, on_books, py::arg("books"))
|
||||
.DEF_ARGS(MdBridge, on_trades, py::arg("trades"));
|
||||
// md provider
|
||||
py::class_<MdProvider, PyMdProvider>(m, "MdProvider")
|
||||
.def(py::init<>())
|
||||
.DEF_ARGS(MdProvider, start, py::arg("bridge"))
|
||||
.DEF(MdProvider, stop);
|
||||
}
|
||||
|
||||
#undef PROP
|
||||
#undef EXPLICIT_DEF
|
||||
#undef DEF
|
||||
#undef _STR
|
||||
@@ -0,0 +1,157 @@
|
||||
#pragma once
|
||||
|
||||
#include "spark/core/FMT_IMPL.h"
|
||||
#include "spark/io/json_formatter.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
class PyTrade {
|
||||
public:
|
||||
/**
|
||||
* Gets the exchange security id. This is typically the security's name
|
||||
* (e.g., "BTS-PERPETUAL", or "ESH5").
|
||||
*
|
||||
* @note Should be unique for each security at a particular venue (i.e., a single
|
||||
* venue cannot have 2 securities with the same name). MUST be unique for each security
|
||||
* of the same type (e.g., SPOT, FUTURE, OPTION) at a particular venue.
|
||||
*
|
||||
* @note There is no "security_id" member because that is an internal id that
|
||||
* we generate elsewhere in c++ code. The python plugins just need to set the
|
||||
* venue and exchange_security_id.
|
||||
*/
|
||||
const std::string &exchange_security_id() const;
|
||||
/**
|
||||
* Sets the exchange security id.
|
||||
*
|
||||
* @param value The new exchange security id.
|
||||
*/
|
||||
void set_exchange_security_id(std::string value);
|
||||
|
||||
const std::string &venue() const;
|
||||
void set_venue(std::string value);
|
||||
|
||||
const std::string &security_type() const;
|
||||
void set_security_type(std::string value);
|
||||
|
||||
constexpr double price() const;
|
||||
void set_price(double value);
|
||||
|
||||
constexpr double quantity() const;
|
||||
void set_quantity(double value);
|
||||
|
||||
const std::string &aggressor_side() const;
|
||||
void set_aggressor_side(std::string value);
|
||||
|
||||
/**
|
||||
* @brief The time at which the trade was executed (nanos since unix epoch).
|
||||
*/
|
||||
constexpr std::int64_t timestamp() const;
|
||||
void set_timestamp(std::int64_t value);
|
||||
|
||||
std::string to_string_pretty() const;
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
std::string venue_;
|
||||
std::string security_type_;
|
||||
std::string exchange_security_id_;
|
||||
double price_;
|
||||
double quantity_;
|
||||
std::string aggressor_side_;
|
||||
std::int64_t timestamp_;
|
||||
};
|
||||
|
||||
void to_json(nlohmann::json &j, const PyTrade &t);
|
||||
void from_json(const nlohmann::json &j, PyTrade &t);
|
||||
|
||||
std::ostream &operator<<(std::ostream &out, const PyTrade &t) noexcept;
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Definition
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
FMT_IMPL(bts::md::py_interop::PyTrade, t, "{}", bts::io::json_formatter(t));
|
||||
|
||||
namespace bts::md::py_interop {
|
||||
|
||||
inline const std::string &PyTrade::venue() const { return venue_; }
|
||||
inline void PyTrade::set_venue(std::string value) { venue_ = std::move(value); }
|
||||
|
||||
inline const std::string &PyTrade::security_type() const {
|
||||
return security_type_;
|
||||
}
|
||||
inline void PyTrade::set_security_type(std::string value) {
|
||||
security_type_ = std::move(value);
|
||||
}
|
||||
|
||||
inline const std::string &PyTrade::exchange_security_id() const {
|
||||
return exchange_security_id_;
|
||||
}
|
||||
inline void PyTrade::set_exchange_security_id(std::string value) {
|
||||
exchange_security_id_ = std::move(value);
|
||||
}
|
||||
|
||||
constexpr double PyTrade::price() const { return price_; }
|
||||
inline void PyTrade::set_price(double value) { price_ = value; }
|
||||
|
||||
constexpr double PyTrade::quantity() const { return quantity_; }
|
||||
inline void PyTrade::set_quantity(double value) { quantity_ = value; }
|
||||
|
||||
inline const std::string &PyTrade::aggressor_side() const {
|
||||
return aggressor_side_;
|
||||
}
|
||||
inline void PyTrade::set_aggressor_side(std::string value) {
|
||||
aggressor_side_ = std::move(value);
|
||||
}
|
||||
|
||||
constexpr std::int64_t PyTrade::timestamp() const { return timestamp_; }
|
||||
inline void PyTrade::set_timestamp(std::int64_t value) { timestamp_ = value; }
|
||||
|
||||
inline std::string PyTrade::to_string() const {
|
||||
return fmt::format("{}", *this);
|
||||
}
|
||||
|
||||
inline std::string PyTrade::to_string_pretty() const {
|
||||
std::stringstream str;
|
||||
if (!aggressor_side_.empty()) {
|
||||
str << aggressor_side_ << " ";
|
||||
}
|
||||
str << quantity_ << exchange_security_id_ << " @ " << price_ << " ("
|
||||
<< venue_ << " ts " << timestamp_ << ")";
|
||||
return str.str();
|
||||
}
|
||||
|
||||
inline void to_json(nlohmann::json &j, const PyTrade &t) {
|
||||
j["sec"] = t.exchange_security_id();
|
||||
j["venue"] = t.venue();
|
||||
j["typ"] = t.security_type();
|
||||
j["agg"] = t.aggressor_side();
|
||||
j["p"] = t.price();
|
||||
j["q"] = t.quantity();
|
||||
j["ts"] = t.timestamp();
|
||||
}
|
||||
|
||||
inline void from_json(const nlohmann::json &j, PyTrade &t) {
|
||||
t.set_exchange_security_id(j.at("sec").get<std::string>());
|
||||
t.set_venue(j.at("venue").get<std::string>());
|
||||
t.set_security_type(j.at("typ").get<std::string>());
|
||||
t.set_aggressor_side(j.at("agg").get<std::string>());
|
||||
t.set_price(j.at("p").get<double>());
|
||||
t.set_quantity(j.at("q").get<double>());
|
||||
t.set_timestamp(j.at("ts").get<std::int64_t>());
|
||||
}
|
||||
|
||||
inline std::ostream &operator<<(std::ostream &out, const PyTrade &t) noexcept {
|
||||
out << fmt::format("{}", t);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace bts::md::py_interop
|
||||
Reference in new issue
Block a user