check pt: PingPong algo

This is a work-in-progress; putting a pin in it for now to focus on
other priorities.
This commit is contained in:
John Colvin committed 2025-11-15 12:16:32 -05:00
1 parent 787cf0becd
commit fc702db7fa
22 files changed
+953 -55

No files matched your search

@@ -0,0 +1,122 @@
#pragma once
#include "spark/collections/circular_buffer_const_iterator.h"
#include "spark/collections/circular_buffer_const_reverse_iterator.h"
#include "spark/collections/circular_buffer_iterator.h"
#include "spark/collections/circular_buffer_reverse_iterator.h"
#include <vector>
namespace bts::collections {
template <typename T>
class CircularBuffer {
std::vector<T> data;
std::size_t capacity;
std::size_t origin;
public:
typedef std::vector<T> container;
typedef container::value_type value_type;
typedef container::pointer pointer;
typedef container::const_pointer const_pointer;
typedef container::reference reference;
typedef container::const_reference const_reference;
typedef CircularBuffer_Iterator<T> iterator;
typedef CircularBuffer_ConstIterator<T> const_iterator;
typedef CircularBuffer_ConstReverseIterator<T> const_reverse_iterator;
typedef CircularBuffer_ReverseIterator<T> reverse_iterator;
typedef container::size_type size_type;
typedef container::difference_type difference_type;
typedef container::allocator_type allocator_type;
CircularBuffer() : capacity(4096) {}
explicit CircularBuffer(std::size_t capacity) : capacity(capacity) {}
iterator begin() {
return {&data, origin, 0};
}
const_iterator begin() const {
return {&data, origin, 0};
}
iterator end() {
return {&data, origin, data.size()};
}
const_iterator end() const {
return {&data, origin, data.size()};
}
constexpr bool empty() const { return data.empty(); }
constexpr std::size_t size() const { return data.size(); }
void push_back(T value) {
if (capacity == 0) {
return;
}
data.erase(data.begin());
if (data.size() < capacity) {
data.push_back(std::move(value));
} else {
data[origin] = std::move(value);
origin = origin < capacity ? origin + 1 : 0;
}
}
bool push_back_pop(T value, T &popped) {
if (capacity == 0) {
return false;
}
if (data.size() < capacity) {
data.push_back(std::move(value));
return false;
}
popped = std::move(data[origin]);
data[origin++] = std::move(value);
return true;
}
template <typename... Args>
T &emplace_back(Args... args) {
if (capacity == 0) {
return;
}
if (data.size() < capacity) {
data.emplace_back(std::forward(args)...);
} else {
data.emplace(data.begin() + origin, std::forward(args)...);
origin = origin < capacity ? origin + 1 : 0;
}
}
iterator erase(const_iterator first, const_iterator last) {
data.erase(first, last);
}
constexpr T &front() { return data.at(origin); }
constexpr const T &front() const { return data.at(origin); }
constexpr T &back() {
return origin == 0 ? data.back() : data.at(origin - 1);
}
constexpr const T &back() const {
return origin == 0 ? data.back() : data.at(origin - 1);
}
constexpr T &operator[](std::size_t index) {
const auto rem = data.size() - origin;
return data[index < rem ? origin + index : index - rem];
}
constexpr const T &operator[](std::size_t index) const {
const auto rem = data.size() - origin;
return data[index < rem ? origin + index : index - rem];
}
};
} // namespace bts::collections
@@ -0,0 +1,60 @@
#pragma once
#include <vector>
namespace bts::collections {
template <typename T>
class CircularBuffer_ConstIterator {
public:
std::vector<T> *data;
std::size_t origin;
std::size_t pos;
const T &operator*() const {
if (origin >= data->size()) {
return nullptr;
}
const auto rem = data->size() - origin;
return (*data)[pos > rem ? pos - rem : origin + pos];
}
constexpr CircularBuffer_ConstIterator<T> &operator++() {
pos++;
return *this;
}
constexpr CircularBuffer_ConstIterator<T> operator++(int) {
return {data, origin, pos++};
}
constexpr CircularBuffer_ConstIterator<T> &operator+=(int value) {
pos += value;
return *this;
}
constexpr CircularBuffer_ConstIterator<T> operator+(int value) {
return {data, origin, pos + value};
}
constexpr CircularBuffer_ConstIterator<T> &operator--() {
pos--;
return *this;
}
constexpr CircularBuffer_ConstIterator<T> operator--(int) {
return {data, origin, pos--};
}
constexpr CircularBuffer_ConstIterator<T> &operator-=(int value) {
pos -= value;
return *this;
}
constexpr CircularBuffer_ConstIterator<T> operator-(int value) {
return {data, origin, pos - value};
}
constexpr bool operator==(
const CircularBuffer_ConstIterator<T> &other) const noexcept {
return pos == other.pos && data == other.data && origin == other.origin;
}
constexpr bool operator!=(
const CircularBuffer_ConstIterator<T> &other) const noexcept {
return pos != other.pos || data != other.data || origin != other.origin;
}
};
} // namespace bts::collections
@@ -0,0 +1,60 @@
#pragma once
#include <vector>
namespace bts::collections {
template <typename T>
class CircularBuffer_ConstReverseIterator {
public:
std::vector<T> *data;
std::size_t origin;
std::size_t pos;
const T &operator*() const {
if (origin >= data->size()) {
return nullptr;
}
return (*data)
[pos < origin ? origin - 1 - pos : data->size() - (pos - origin)];
}
constexpr CircularBuffer_ConstReverseIterator<T> &operator++() {
pos++;
return *this;
}
constexpr CircularBuffer_ConstReverseIterator<T> operator++(int) {
return {data, origin, pos++};
}
constexpr CircularBuffer_ConstReverseIterator<T> &operator+=(int value) {
pos += value;
return *this;
}
constexpr CircularBuffer_ConstReverseIterator<T> operator+(int value) {
return {data, origin, pos + value};
}
constexpr CircularBuffer_ConstReverseIterator<T> &operator--() {
pos--;
return *this;
}
constexpr CircularBuffer_ConstReverseIterator<T> operator--(int) {
return {data, origin, pos--};
}
constexpr CircularBuffer_ConstReverseIterator<T> &operator-=(int value) {
pos -= value;
return *this;
}
constexpr CircularBuffer_ConstReverseIterator<T> operator-(int value) {
return {data, origin, pos - value};
}
constexpr bool operator==(
const CircularBuffer_ConstReverseIterator<T> &other) const noexcept {
return pos == other.pos && data == other.data && origin == other.origin;
}
constexpr bool operator!=(
const CircularBuffer_ConstReverseIterator<T> &other) const noexcept {
return pos != other.pos || data != other.data || origin != other.origin;
}
};
} // namespace bts::collections
@@ -0,0 +1,69 @@
#pragma once
#include <stdexcept>
#include <vector>
namespace bts::collections {
template <typename T>
class CircularBuffer_Iterator {
public:
std::vector<T> *data;
std::size_t origin;
std::size_t pos;
const T &operator*() const {
if (origin >= data->size()) {
return nullptr;
}
const auto rem = data->size() - origin;
return (*data)[pos > rem ? pos - rem : origin + pos];
}
T &operator*() {
if (origin >= data->size()) {
throw std::runtime_error("origin exceeds size");
}
const auto rem = data->size() - origin;
return (*data)[pos > rem ? pos - rem : origin + pos];
}
constexpr CircularBuffer_Iterator<T> &operator++() {
pos++;
return *this;
}
constexpr CircularBuffer_Iterator<T> operator++(int) {
return {data, origin, pos++};
}
constexpr CircularBuffer_Iterator<T> &operator+=(int value) {
pos += value;
return *this;
}
constexpr CircularBuffer_Iterator<T> operator+(int value) {
return {data, origin, pos + value};
}
constexpr CircularBuffer_Iterator<T> &operator--() {
pos--;
return *this;
}
constexpr CircularBuffer_Iterator<T> operator--(int) {
return {data, origin, pos--};
}
constexpr CircularBuffer_Iterator<T> &operator-=(int value) {
pos -= value;
return *this;
}
constexpr CircularBuffer_Iterator<T> operator-(int value) {
return {data, origin, pos - value};
}
constexpr bool operator==(
const CircularBuffer_Iterator<T> &other) const noexcept {
return pos == other.pos && data == other.data && origin == other.origin;
}
constexpr bool operator!=(
const CircularBuffer_Iterator<T> &other) const noexcept {
return pos != other.pos || data != other.data || origin != other.origin;
}
};
} // namespace bts::collections
@@ -0,0 +1,68 @@
#pragma once
#include <vector>
namespace bts::collections {
template <typename T>
class CircularBuffer_ReverseIterator {
public:
std::vector<T> *data;
std::size_t origin;
std::size_t pos;
const T &operator*() const {
if (origin >= data->size()) {
return nullptr;
}
return (*data)
[pos < origin ? origin - 1 - pos : data->size() - (pos - origin)];
}
T &operator*() {
if (origin >= data->size()) {
return nullptr;
}
return (*data)
[pos < origin ? origin - 1 - pos : data->size() - (pos - origin)];
}
constexpr CircularBuffer_ReverseIterator<T> &operator++() {
pos++;
return *this;
}
constexpr CircularBuffer_ReverseIterator<T> operator++(int) {
return {data, origin, pos++};
}
constexpr CircularBuffer_ReverseIterator<T> &operator+=(int value) {
pos += value;
return *this;
}
constexpr CircularBuffer_ReverseIterator<T> operator+(int value) {
return {data, origin, pos + value};
}
constexpr CircularBuffer_ReverseIterator<T> &operator--() {
pos--;
return *this;
}
constexpr CircularBuffer_ReverseIterator<T> operator--(int) {
return {data, origin, pos--};
}
constexpr CircularBuffer_ReverseIterator<T> &operator-=(int value) {
pos -= value;
return *this;
}
constexpr CircularBuffer_ReverseIterator<T> operator-(int value) {
return {data, origin, pos - value};
}
constexpr bool operator==(
const CircularBuffer_ReverseIterator<T> &other) const noexcept {
return pos == other.pos && data == other.data && origin == other.origin;
}
constexpr bool operator!=(
const CircularBuffer_ReverseIterator<T> &other) const noexcept {
return pos != other.pos || data != other.data || origin != other.origin;
}
};
} // namespace bts::collections
Whitespace-only changes.
+5
View File
@@ -70,6 +70,7 @@ constexpr TimeSpan operator-(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan &operator-=(TimeSpan &lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan operator+(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan &operator+=(TimeSpan &lhs, TimeSpan rhs) noexcept;
constexpr double operator/(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan operator*(TimeSpan lhs, int rhs) noexcept;
constexpr TimeSpan &operator*=(TimeSpan &lhs, int rhs) noexcept;
@@ -217,6 +218,10 @@ constexpr TimeSpan &operator+=(TimeSpan &lhs, TimeSpan rhs) noexcept {
return lhs;
}
constexpr double operator/(TimeSpan lhs, TimeSpan rhs) noexcept {
return static_cast<double>(lhs.nanos()) / static_cast<double>(rhs.nanos());
}
constexpr TimeSpan operator*(TimeSpan lhs, int rhs) noexcept {
return TimeSpan{lhs.ticks() * rhs};
}
@@ -0,0 +1,66 @@
#pragma once
#include "spark/collections/circular_buffer.h"
#include "spark/core/TimeSpan.h"
#include "spark/core/TimeStamp.h"
#include <cstdint>
namespace bts::core::math {
struct RollingVariance {
std::uint32_t window_sz;
TimeStamp start_time{};
std::int64_t curr_elapsed_units = 0;
double sum = 0;
double sum_avg_diff_sq = 0;
collections::CircularBuffer<double> history{4};
RollingVariance(std::uint32_t window_sz)
: window_sz(window_sz), start_time(TimeStamp::now()),
history(window_sz) {}
double avg() const {
if (history.size() < window_sz) {
return std::numeric_limits<double>::quiet_NaN();
}
return sum / window_sz;
}
double var() const {
if (history.size() < window_sz) {
return std::numeric_limits<double>::quiet_NaN();
}
return sum_avg_diff_sq / window_sz;
}
double dev() const { return std::sqrt(var()); }
void on_value(double value, bool is_replace) {
if (window_sz == 0) {
return;
}
if (history.empty()) {
history.push_back(value);
sum = value;
sum_avg_diff_sq = 0;
return;
}
double popped;
if (is_replace) {
popped = history[history.size() - 1];
history[history.size() - 1] = value;
} else if (!history.push_back_pop(value, popped)) {
popped = 0;
}
sum += value - popped;
sum_avg_diff_sq += value * value - popped * popped;
}
void push_back(double value) { on_value(value, false); }
void replace_back(double value) { on_value(value, true); }
double back() const { return history.back(); }
constexpr bool empty() const { return history.empty(); }
};
} // namespace bts::core::math
@@ -0,0 +1,10 @@
#pragma once
namespace bts::core {
template <typename T>
struct ThreadLocalSingleton {
static inline thread_local T instance;
};
} // namespace bts::core
@@ -1,6 +1,9 @@
#include "common.h"
#include "spark/utils/bts_assert.h"
#include <limits>
#include <nlohmann/json.hpp>
namespace bts {
double CQuantity::round_to_decimal_places(double value, int decimal_places) {
@@ -11,6 +11,8 @@
#include "spark/domain_model/SecurityKey.h"
#include "spark/utils/ValueWrapper.h"
#include <nlohmann/json.hpp>
namespace bts {
struct CQuantity {
double qty = 0;
@@ -102,6 +104,13 @@ struct CQuantity {
void round() { qty = round_to_decimal_places(qty, precision_digits); }
};
inline void from_json(const nlohmann::json &j, CQuantity &qty) {
qty = CQuantity::create_new(
j.is_string() ? std::stod(j.get<std::string>()) : j.get<double>());
}
inline void to_json(nlohmann::json &j, CQuantity &qty) { j = qty.full_value(); }
inline std::ostream &operator<<(std::ostream &out, CQuantity const &qty) {
out << qty.full_value();
return out;
@@ -0,0 +1,18 @@
#pragma once
#include <algorithm>
namespace bts::logging::structured {
template <typename T>
struct TimeStampedLog {
T value;
TimeStampedLog(T &&value) : value(std::move(value)) {}
};
template <typename T>
TimeStampedLog<T> time_stamped_log(T &&value) {
return {std::move(value)};
}
} // namespace bts::logging::structured
@@ -0,0 +1,46 @@
#pragma once
#include <limits>
#include <utility>
namespace bts::orderman {
enum class ExecFeeType { ABSOLUTE, PERCENT };
struct ExecFeeCalculator {
struct AbsoluteFee {
double value;
};
struct PercentFee {
double value;
};
struct Fill {
double quantity;
double price;
double fee;
bool is_fee_percent;
};
ExecFeeCalculator(double total_filled_notional, double total_fee_notional)
: filled_notional(total_filled_notional),
fee_notional(total_fee_notional) {}
ExecFeeCalculator on_fill(const Fill &fill) const {
return ExecFeeCalculator{
fee_notional + (fill.is_fee_percent
? fill.quantity * fill.price * fill.fee
: fill.fee),
filled_notional + fill.quantity * fill.price};
}
double filled_notional = 0;
double fee_notional = 0;
};
// inline ExecFeeCalculator::Fill operator-(
// const ExecFeeCalculator &lhs, const ExecFeeCalculator &rhs) {
// return ExecFeeCalculator::Fill { lhs.filled_notional }
// }
} // namespace bts::orderman
@@ -1,5 +1,10 @@
#pragma once
#include "spark/api/services/OrderService.pb.h"
#include "spark/orderman/OrderBuilder.h"
#include "spark/orderman/order_factory/IOrderFactory.h"
#include "spark/orderman/order_key.h"
namespace bts {
namespace orderman {
@@ -0,0 +1,30 @@
#include "IAlgoOrder.h"
#include "spark/domain_model/common.h"
#include <nlohmann/json.hpp>
namespace bts::orderman {
void to_json(nlohmann::json &j, const ChildState &st) {
j["p"] = *st.price;
j["q"] = st.quantity.full_value();
j["tf"] = st.total_fills.full_value();
j["ap"] = *st.avg_price;
j["lf"] = st.last_fills.full_value();
j["lp"] = *st.last_price;
j["st"] = ChildStatus_Name(st.status);
}
void from_json(const nlohmann::json &j, ChildState &st) {
j.at("p").get_to(*st.price);
j.at("q").get_to(st.quantity);
j.at("tf").get_to(st.total_fills);
j.at("ap").get_to(st.total_fills);
j.at("lf").get_to(st.last_fills);
j.at("lp").get_to(*st.last_price);
std::string str;
j.at("st").get_to(str);
ChildStatus_Parse(str, &st.status);
}
} // namespace bts::orderman
@@ -7,6 +7,7 @@
#include "spark/orderman/orders/OrderOpResult.h"
#include "spark/orderman/orders/algo/PositionUpdate.h"
#include <nlohmann/json_fwd.hpp>
#include <string>
namespace bts::orderman {
@@ -40,13 +41,13 @@ class IAlgoOrder {
// The child order specified by the order key has changed
virtual void on_child_change(
OrderKey child_key, const ChildState& child_state);
OrderKey child_key, const ChildState &child_state);
// The book for the specified security has changed
virtual void on_book(SecurityKey security_key, const Book& book);
virtual void on_book(SecurityKey security_key, const Book &book);
// Trades stream for the specified security
virtual void on_ticker(SecurityKey security_key, const TradeVector& trades);
virtual void on_ticker(SecurityKey security_key, const TradeVector &trades);
// The trading status for the specified security has changed
virtual void on_status(SecurityKey security_key, co2::TradingStatus status);
@@ -55,7 +56,7 @@ class IAlgoOrder {
virtual void on_settlement(SecurityKey security_key, Price price);
// The current position for the security, account combination
virtual void on_position(const PositionUpdate& position);
virtual void on_position(const PositionUpdate &position);
// A signal sent ahead of a book update, indicating that one or
// more trades between the two price levels specified for a buy or
@@ -68,7 +69,7 @@ class IAlgoOrder {
uint num_price_levels);
// The calculator has updated itself, theos need to be recomputed
virtual void on_theos(const analytics::ITheoCalculator* theo_calculator);
virtual void on_theos(const analytics::ITheoCalculator *theo_calculator);
// A periodic timer has fired
virtual void on_timer();
@@ -83,10 +84,10 @@ class IAlgoOrder {
// so it can be used for any expensive initialization
// operations. The implementation should return an error code if it
// detects an invalid parameter in the algo definition.
virtual OrderOpResult do_before_launch(IBeforeLaunchAlgoServices&);
virtual OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &);
// Override this method to activate your algo
virtual void do_launch(IAlgoServices& services) = 0;
virtual void do_launch(IAlgoServices &services) = 0;
// Override this method to activate your algo using an existing
// working order as a child. Attached child orders are
@@ -95,12 +96,12 @@ class IAlgoOrder {
// from this call through IAlgoServices::update_fill_state() will
// be included in the fills_at_attach_time count field.
virtual void do_launch_attached(
IAlgoServices& services, OrderKey child_key, ChildState child_state);
IAlgoServices &services, OrderKey child_key, ChildState child_state);
// Implement this method to respond to updates to your algo. The
// implementation should validate the update and either apply it,
// if valid or terminate with an error otherwise
virtual void do_update(api::orderman::Update const& update);
virtual void do_update(api::orderman::Update const &update);
// Override this method to provide custom handling of a cancel
// request. The default behaviour is to cancel both this order and
@@ -129,14 +130,27 @@ constexpr std::string ChildStatus_Name(ChildStatus child_status) {
}
}
inline bool ChildStatus_Parse(const std::string &str, ChildStatus *res) {
if (str == "WORKING") {
*res = ChildStatus::WORKING;
} else if (str == "COMPLETED") {
*res = ChildStatus::COMPLETED;
} else if (str == "CANCELED") {
*res = ChildStatus::CANCELED;
} else {
return false;
}
return true;
}
inline void IAlgoOrder::on_child_change(
OrderKey /*child_key*/, const ChildState& /*child_state*/) {}
OrderKey /*child_key*/, const ChildState & /*child_state*/) {}
inline void IAlgoOrder::on_book(
SecurityKey /*security_key*/, const Book& /*book*/) {}
SecurityKey /*security_key*/, const Book & /*book*/) {}
inline void IAlgoOrder::on_ticker(
SecurityKey /*security_key*/, const TradeVector& /*trades*/) {}
SecurityKey /*security_key*/, const TradeVector & /*trades*/) {}
inline void IAlgoOrder::on_status(
SecurityKey /*security_key*/, co2::TradingStatus /*status*/) {}
@@ -144,7 +158,7 @@ inline void IAlgoOrder::on_status(
inline void IAlgoOrder::on_settlement(
SecurityKey /*security_key*/, Price /*price*/) {}
inline void IAlgoOrder::on_position(const PositionUpdate& /*position*/) {}
inline void IAlgoOrder::on_position(const PositionUpdate & /*position*/) {}
inline void IAlgoOrder::on_trade_summary_signal(
SecurityKey /*security_key*/,
@@ -154,20 +168,20 @@ inline void IAlgoOrder::on_trade_summary_signal(
uint /*num_price_levels*/) {}
inline void IAlgoOrder::on_theos(
analytics::ITheoCalculator const* /*theo_calculator*/) {}
analytics::ITheoCalculator const * /*theo_calculator*/) {}
inline void IAlgoOrder::on_timer() {}
inline OrderOpResult IAlgoOrder::do_before_launch(IBeforeLaunchAlgoServices&) {
inline OrderOpResult IAlgoOrder::do_before_launch(IBeforeLaunchAlgoServices &) {
return {};
}
inline void IAlgoOrder::do_launch_attached(
IAlgoServices& /*services*/,
IAlgoServices & /*services*/,
OrderKey /*child_key*/,
ChildState /*child_state*/) {}
inline void IAlgoOrder::do_update(api::orderman::Update const& /*update*/) {}
inline void IAlgoOrder::do_update(api::orderman::Update const & /*update*/) {}
inline IAlgoOrder::OnCancelResponse IAlgoOrder::on_cancel() {
return OnCancelResponse::HONOR;
@@ -1,43 +1,184 @@
#include "PingpongAlgo.h"
#include "spark/api/services/OrderService.pb.h"
#include "spark/collections/circular_buffer.h"
#include "spark/core/TimeStamp.h"
#include "spark/core/math/rolling_variance.h"
#include "spark/domain/PriceComp.h"
#include "spark/domain_model/Security.h"
#include "spark/domain_model/Security.pb.h"
#include "spark/domain_model/common.h"
#include "spark/md/PriceSize.h"
#include "spark/orderman/order_factory/IOrderFactory.h"
#include "spark/orderman/order_key.h"
#include "spark/orderman/orderman_utils/Book.h"
#include "spark/orderman/orderman_utils/PriceComp.h"
#include "spark/orderman/orderman_utils/orderman_utils.h"
#include "spark/orderman/orders/algo/ChildTemplate.h"
#include "spark/orderman/orders/algo/IAlgoServices.h"
#include "spark/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
#include "spark/orderman/orders/algo/algo_orders/pingpong_pos_data.h"
#include "spark/orderman/orders/algo/algo_orders/pingpong_stats.h"
#include "spark/orderman/orders/algo/algo_orders/pingpong_status.h"
#include "spark/os/os.h"
#include "spark/utils/PBUtils.h"
#include "spark/utils/datetime.h"
#include "spark/sparkproto/SparkProtos.pb.h"
#include <boost/circular_buffer.hpp>
#include <cmath>
#include <limits>
#include <stdint.h>
#include <tuple>
namespace bts {
namespace orderman {
#define _LOG_TRACE(level, name) \
LOG_TRACE(md, level, std::string("pingpong_algo"), std::string(name))
#define INFO_TRACE(name) _LOG_TRACE(bts::Info, name)
#define WARN_TRACE(name) _LOG_TRACE(bts::Warn, name)
#define ERROR_TRACE(name) _LOG_TRACE(bts::Error, name)
#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__)
#define INFO(...) _LOG(Info, __VA_ARGS__)
#define SINFO(type, ...) _LOG(Info, "[pingpong_algo_" type ".json]" __VA_ARGS__)
#define WARN(...) _LOG(Warn, __VA_ARGS__)
#define ERROR(...) _LOG(Error, __VA_ARGS__)
using bts::api::SIDE_BUY;
using bts::api::SIDE_SELL;
using bts::collections::CircularBuffer;
using bts::core::math::RollingVariance;
using std::int64_t;
using std::size_t;
using std::string;
using std::tuple;
using std::uint32_t;
using namespace api::orderman;
enum class PingpongAlgo::Status { WAITING_FOR_SIGNAL, WORKING, DONE };
struct PingpongAlgo::PImpl {
Status state = Status::WAITING_FOR_SIGNAL;
PingpongStatus state = PingpongStatus::WAITING_FOR_SIGNAL;
IAlgoServices *algo_services = nullptr;
SecurityKey sec_key = SecurityKey(0);
//PingpongAlgo::PingpongAlgoParams algo_params;
// dynamic algo params
std::uint32_t window_secs;
double show_qty;
CustomOrderDefinition child_def;
PingpongStats stats;
PingpongPosData long_pos;
PingpongPosData short_pos;
Book book;
PImpl(std::uint32_t window_secs) : stats(window_secs) {}
OrderKey launch(
double trigger_mult,
api::Side mkt_side,
Quantity quantity,
ChildTemplate *child_template) {
const bool mkt_is_buy = mkt_side == api::SIDE_BUY;
const RollingVariance &rvar =
mkt_is_buy ? stats.rolling_bid : stats.rolling_ask;
double mkt_avg = rvar.avg();
double mkt_dev = rvar.dev();
double trigger = mkt_avg + mkt_dev * trigger_mult;
return algo_services->launch_child(
*child_template, Price{trigger}, quantity);
}
void open() {
const auto q = algo_services->quantity();
short_pos.open_key =
launch(short_pos.open_trigger, SIDE_BUY, q, short_pos.open_template);
long_pos.open_key =
launch(long_pos.open_trigger, SIDE_SELL, q, long_pos.open_template);
}
void close(OrderKey child_key, Quantity qty) {
SINFO("close", R"("k": {}, "q": {})", qty);
if (child_key == long_pos.open_key) {
long_pos.close_keys.push_back(launch(
long_pos.close_trigger, SIDE_BUY, qty, long_pos.close_template));
return;
}
if (child_key == short_pos.open_key) {
SINFO("close", R"("k": {}, "q": {})", qty);
short_pos.close_keys.push_back(launch(
short_pos.close_trigger, SIDE_SELL, qty,
short_pos.close_template));
return;
}
bts_assert_msgf(false, "Unexpected child key {}", child_key);
}
OrderDefinition order_factory(api::Side side) const {
auto &svc = *algo_services;
auto def = svc.definition();
def.set_side(side);
auto &cdef = *def.mutable_custom_def();
cdef.CopyFrom(child_def);
// const auto &sec = svc.security();
// if (sec.has_synthetic()) {
// auto &spd = *cdef.mutable_spreader();
// spd.mutable_security()->CopyFrom(svc.security());
// auto &strategy = *spd.mutable_execution_strategy();
// strategy.set_spreader_type(
// bts::spark::ExecutionStrategy_SpreaderType_REQUOTE);
// auto &leg_params = *strategy.mutable_leg_params_map();
// bool is_first_leg = true;
// for (const auto &leg : sec.synthetic().legs()) {
// bts_assert(leg.has_security());
// auto &lp = leg_params.emplace(leg.security().id()).first->second;
// lp.set_is_active_quoting(is_first_leg);
// is_first_leg = false;
// }
// } else {
// cdef.mutable_limit();
// }
return def;
}
};
PingpongAlgo::PingpongAlgo() : me(new PImpl()) {}
PingpongAlgo::PingpongAlgo() : me(new PImpl(30)) {}
PingpongAlgo::~PingpongAlgo() {}
// initialization /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
OrderOpResult PingpongAlgo::do_before_launch(
IBeforeLaunchAlgoServices & /*serv*/) {
OrderOpResult PingpongAlgo::do_before_launch(IBeforeLaunchAlgoServices &svc) {
auto &def = svc.definition();
bts_assert(def.has_custom_def());
bts_assert(def.custom_def().has_dynamic());
auto &dyn = def.custom_def().dynamic();
auto &params = dyn.order_params();
try {
me->long_pos.open_trigger =
params.find("Open Long Pos")->second.as_double();
me->long_pos.close_trigger =
params.find("Close Long Pos")->second.as_double();
me->short_pos.open_trigger =
params.find("Open Short Pos")->second.as_double();
me->short_pos.close_trigger =
params.find("Close Short Pos")->second.as_double();
me->window_secs =
params.find("Sliding Window Seconds")->second.as_uint32();
me->child_def = params.find("Child")->second.as_order_def();
} catch (const std::exception &ex) {
return {OrderError::ORDER_ERROR_INVALID_PARAMETER, string(ex.what())};
}
auto buy_template = me->order_factory(api::SIDE_BUY);
auto sell_template = me->order_factory(api::SIDE_SELL);
me->long_pos.open_template = &(svc.make_child_template(buy_template));
me->long_pos.close_template = &(svc.make_child_template(sell_template));
me->short_pos.open_template = &(svc.make_child_template(sell_template));
me->short_pos.close_template = &(svc.make_child_template(buy_template));
return {OrderError::ORDER_ERROR_OK, std::string("OK")};
}
void PingpongAlgo::do_launch(IAlgoServices &algo_services) {
me->algo_services = &algo_services;
_algo().subscribe_status(me->sec_key);
//_algo().subscribe_timer();
}
void PingpongAlgo::do_launch_attached(
IAlgoServices &algo_services, OrderKey, ChildState) {
me->algo_services = &algo_services;
@@ -48,11 +189,12 @@ void PingpongAlgo::do_launch_attached(
void PingpongAlgo::do_update(const api::orderman::Update &) {
LOG(OrderMan, Warn,
"PingpongAlgo::do_update order:{} state:{} update not allowed ",
_algo().order_key().value(), static_cast<int>(me->state));
_algo().order_key().value(), me->state);
}
// callbacks //////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void PingpongAlgo::on_book(SecurityKey, const Book &) {
void PingpongAlgo::on_book(SecurityKey, const Book &bk) {
// find the mean and std dev. for std dev, we'll most likely have to keep a sliding window of the
// bids and asks, perhaps a std::vector<std::pair<double, double>> and we recompute it everytime.
@@ -61,32 +203,53 @@ void PingpongAlgo::on_book(SecurityKey, const Book &) {
// when the open long pos order gets filled, we send the close long position order at μ + cl.σ.
// when the buy open pos order gets filled, we send the close long position order at μ + cl.σ.
// similiarly for short.
switch (me->state.value) {
case PingpongStatus::WAITING_FOR_SIGNAL: {
me->book = bk;
double bid = bk.bid()[0].price();
double ask = bk.ask()[0].price();
auto &stats = me->stats;
stats.on_bbo(bid, ask);
if (stats.is_sufficient_sample()) {
me->open();
_switch_state(PingpongStatus::WORKING);
}
break;
}
default:
break;
}
}
void PingpongAlgo::on_child_change(OrderKey, ChildState const &) {}
void PingpongAlgo::on_child_change(OrderKey ck, ChildState const &cst) {
auto &svc = *me->algo_services;
auto k = svc.order_key();
auto sid = svc.security().id();
SINFO(
"child_change",
R"({{ "k": {}, "sid": {}, "ck": {}, "c": {}, "st": "{}", "lng": {}, "sht": {} }})",
k, sid, ck, cst, me->state, me->long_pos.pos, 3.4);
switch (cst.status) {
case ChildStatus::WORKING:
case ChildStatus::COMPLETED:
if (cst.last_fills > 0) {
me->close(ck, cst.last_fills);
}
break;
case ChildStatus::CANCELED:
me->algo_services->terminate_error("Unexpected child cancel");
break;
}
}
void PingpongAlgo::on_status(SecurityKey, co2::TradingStatus) {}
void PingpongAlgo::on_timer() {}
IAlgoServices &PingpongAlgo::_algo() const { return *me->algo_services; }
///////////////////////////////////////////////////////////////////////////////
ChildTemplate *PingpongAlgo::_create_order_template(
IBeforeLaunchAlgoServices &, SecurityKey, api::Side) {
return nullptr;
}
void PingpongAlgo::_switch_state(PingpongAlgo::Status new_state) {
switch (new_state) {
case (PingpongAlgo::Status::WAITING_FOR_SIGNAL):
bts_assert(false);
break;
case (PingpongAlgo::Status::WORKING):
bts_assert(me->state == PingpongAlgo::Status::WAITING_FOR_SIGNAL);
break;
case (PingpongAlgo::Status::DONE):
bts_assert(me->state != PingpongAlgo::Status::DONE);
break;
}
LOG(OrderMan, Info, "PingpongAlgo::_switch_state key:{} {}->{} ",
_algo().order_key(), static_cast<int>(me->state),
static_cast<int>(new_state));
void PingpongAlgo::_switch_state(PingpongStatus new_state) {
auto old_st = me->state;
SINFO("status", R"({{ "old": "{}", "new": "{}" }})", old_st, new_state);
me->state = new_state;
}
@@ -95,8 +258,8 @@ void PingpongAlgo::_cxl_and_end(bool is_error, const std::string &err_msg) {
_algo().terminate_error(err_msg);
else
_algo().complete();
_switch_state(PingpongAlgo::Status::DONE);
_switch_state(PingpongStatus::DONE);
}
} // namespace orderman
} // namespace bts
} // namespace bts
@@ -1,6 +1,7 @@
#pragma once
#include "spark/orderman/orders/algo/IAlgoOrder.h"
#include "spark/orderman/orders/algo/algo_orders/pingpong_status.h"
namespace bts::orderman {
@@ -22,17 +23,15 @@ class PingpongAlgo : public IAlgoOrder {
void on_timer() override;
private:
enum class Status;
struct PImpl;
PImpl *me;
//std::unique_ptr<PImpl> me;
private:
IAlgoServices &_algo() const;
static ChildTemplate *_create_order_template(
IBeforeLaunchAlgoServices &, SecurityKey, api::Side);
// acts on md, cognizant of the state
void _switch_state(Status new_status);
void _switch_state(PingpongStatus new_status);
void _cxl_and_end(bool is_error, const std::string &err_msg);
};
} // namespace bts::orderman
} // namespace bts::orderman
@@ -380,7 +380,9 @@ extern "C" void init_pingpong_plugin(bts::SparkServices &srv) {
*pingpong_algo.add_param_desc() = param_double("Open Short Pos");
// μ + cs.σ
*pingpong_algo.add_param_desc() = param_double("Close Short Pos");
*pingpong_algo.add_param_desc() = param_double("Show Quantity");
*pingpong_algo.add_param_desc() = param_uint32("Sliding Window Seconds");
*pingpong_algo.add_param_desc() = param_order("Child");
srv.register_dynamic_algo_order(
pingpong_algo, []() { return std::make_unique<orderman::VolAlgo>(); });
}
@@ -0,0 +1,33 @@
#pragma once
#include "spark/core/math/rolling_variance.h"
#include "spark/orderman/order_key.h"
#include "spark/orderman/orders/algo/ChildTemplate.h"
#include <boost/container/small_vector.hpp>
namespace bts::orderman {
struct PingpongPosData {
enum Status {
IDLE = 0,
OPENING = 1,
CLOSING = 1 << 1,
};
ChildTemplate *open_template = nullptr;
ChildTemplate *close_template = nullptr;
double pos = 0;
double avg_open_cost;
double avg_close_cost;
OrderKey open_key{0};
boost::container::small_vector<OrderKey, 2> close_keys{0};
double open_wqty;
double close_wqty;
double open_fqty;
double close_fqty;
float open_trigger;
float close_trigger;
bool is_buy;
};
} // namespace bts::orderman
@@ -0,0 +1,89 @@
#pragma once
#include "spark/collections/circular_buffer.h"
#include "spark/core/math/rolling_variance.h"
#include <cstddef>
#include <cstdint>
namespace bts::orderman {
struct PingpongStats {
core::math::RollingVariance rolling_bid;
core::math::RollingVariance rolling_ask;
collections::CircularBuffer<core::TimeStamp> updates;
core::TimeStamp start_time;
std::uint32_t n_intervals;
core::TimeSpan interval;
std::int64_t curr_elapsed_units = 0;
PingpongStats(std::uint32_t window_sz)
: rolling_bid(window_sz), rolling_ask(window_sz), updates(window_sz),
n_intervals(window_sz) {}
void set_window_size(std::uint32_t value) {
collections::CircularBuffer<core::TimeStamp> new_updates(value);
for (auto it = value < updates.size()
? updates.begin() + updates.size() - value
: updates.begin();
it != updates.end(); it++) {
new_updates.push_back(*it);
}
updates = std::move(new_updates);
}
bool is_sufficient_sample() const {
const auto now = core::TimeStamp::now();
return now - updates.front() <=
(interval * static_cast<int>(n_intervals));
}
double get_long_trigger(double dev_mult) {
return rolling_ask.avg() + rolling_ask.dev() * dev_mult;
}
double get_short_trigger(double dev_mult) {
return rolling_bid.avg() + rolling_bid.dev() * dev_mult;
}
void on_bbo(double bid, double ask) {
if (n_intervals == 0) {
return;
}
const auto now = core::TimeStamp::now();
std::int64_t elapsed_units = (now - start_time) / interval;
double prev_bid = rolling_bid.empty() ? std::numeric_limits<double>::min()
: rolling_bid.back();
double prev_ask = rolling_ask.empty() ? std::numeric_limits<double>::max()
: rolling_ask.back();
if (elapsed_units == curr_elapsed_units) {
// The window hasn't changed since the last time this was called (not
// enough time has elapsed).
if (bid > prev_bid) {
// Take highest bid
rolling_bid.replace_back(bid);
}
if (ask < prev_ask) {
// Take lowest ask
rolling_ask.replace_back(ask);
}
return;
}
// We're in a new window. It's possible that more than one window has
// elapsed since the last time this was called. Backfill with bbo from
// right before this update.
std::uint32_t backfill_count = elapsed_units - curr_elapsed_units;
curr_elapsed_units = elapsed_units;
if (backfill_count >= n_intervals) {
backfill_count = n_intervals - 1;
}
for (std::size_t i = 0; i < n_intervals - 1; i++) {
rolling_bid.push_back(prev_bid);
rolling_ask.push_back(prev_ask);
}
rolling_bid.push_back(bid);
rolling_ask.push_back(ask);
}
};
} // namespace bts::orderman
@@ -0,0 +1,27 @@
#pragma once
#include "spark/core/EnumMacros.h"
#include "spark/core/FMT_IMPL.h"
#include <fmt/format.h>
#include <nlohmann/json.hpp>
namespace bts::orderman {
// clang-format off
#define PINGPONG_STATUS(per_value) \
per_value(PingpongStatus, WAITING_FOR_SIGNAL) \
per_value(PingpongStatus, WORKING) \
per_value(PingpongStatus, DONE)
// clang-format on
/**
* @brief Represents the different statuses for the pingpong algo
*/
ENUM_CLASS_DEF(PingpongStatus, PINGPONG_STATUS)
#undef PINGPONG_STATUS
} // namespace binance
FMT_IMPL(bts::orderman::PingpongStatus, s, "{}", s.name());