refactor into TimeSlicer and VolumeSlicer

This commit is contained in:
Kevin Darby committed 2019-08-12 18:07:07 -04:00
1 parent 9be591c634
commit 4b18d15421
12 files changed
+755 -511

No files matched your search

@@ -1,4 +1,5 @@
#include "lib/orderman/orders/algo/algo_orders/bluex/POVAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/bluex/VolumeEstimator.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include "lib/orderman/orders/algo/DynamicHelpers.h"
#include "lib/api/services/OrderService.pb.h"
@@ -16,7 +17,7 @@ using namespace api::orderman;
struct POVAlgo::PImpl
{
VolumeDistribution volume_dist;
VolumeEstimator volume_est;
};
POVAlgo::POVAlgo() : me(new PImpl()) {}
@@ -87,21 +88,14 @@ void POVAlgo::update_params()
algo().terminate_error("Algo needs volume mean and variance overrides temporarily, terminating");
return;
}
me->volume_dist = algo().definition().custom_def().vwap().volume_distribution();
if(algo().definition().custom_def().pov().min_participation_pct() <= 0)
if(!me->volume_est.update_params(algo().definition().custom_def().pov().volume_distribution()))
{
algo().terminate_error("Can't be zero percent of the market, terminating");
algo().terminate_error("Algo needs volume mean and variance overrides temporarily, terminating");
return;
}
}
Quantity POVAlgo::day_volume()
{
//TODO estimator
return Quantity( me->volume_dist.volume_mean_override() );
}
void TimeSlicer::on_ticker(SecurityKey k, const TradeVector& vec)
void POVAlgo::on_ticker(SecurityKey k, const TradeVector& vec)
{
TimeSlicer::on_ticker(k, vec);
@@ -119,21 +113,13 @@ void TimeSlicer::on_ticker(SecurityKey k, const TradeVector& vec)
//double ratio =
}
void POVAlgo::compute_first_generation(Price&, Quantity& size)
void POVAlgo::compute_first_generation(Price&, Quantity& )
{
double ratio = running_volume().value() / me->volume_dist.volume_mean_override();
ratio = std::min(1.0, ratio);
ratio = std::max(0.0, ratio);
size = Quantity( ratio * size.value() );
}
void POVAlgo::compute_next_generation(Price&, Quantity& size)
void POVAlgo::compute_next_generation(Price&, Quantity& )
{
//TODO predict this period based on prior
double ratio = running_volume().value() / me->volume_dist.volume_mean_override();
ratio = std::min(1.0, ratio);
ratio = std::max(0.0, ratio);
size = Quantity( ratio * size.value() );
}
} // namespace orderman
@@ -19,10 +19,7 @@ protected:
void update_params() override;
void compute_first_generation(Price& price, Quantity& size) override;
void compute_next_generation(Price& price, Quantity& size) override;
protected:
Quantity day_volume();
protected:
struct PImpl;
std::unique_ptr<PImpl> me;
@@ -0,0 +1,434 @@
#include "lib/orderman/orders/algo/algo_orders/bluex/Slicer.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include "lib/orderman/orders/algo/DynamicHelpers.h"
#include "lib/api/services/OrderService.pb.h"
#include "lib/orderman/order_factory/IOrderFactory.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
#include "lib/os/os.h"
#include "lib/utils/PBUtils.h"
#include <fmt/format.h>
#include <google/protobuf/util/time_util.h>
#include <random>
namespace bts {
namespace orderman {
using namespace api::orderman;
struct OrderDef
{
OrderKey child_key = null_order_key();
uint32_t generation = 0u;
Slicer::Channel channel = Slicer::Channel::Tactical;
};
struct Slicer::PImpl
{
IAlgoServices* algo;
OrderAggression aggression;
Status status = Status::WAITING_FOR_MD;
uint32_t generation = 0; uint32_t expected_generations = 0;
ChildTemplate* tactical_template = nullptr;
ChildTemplate* aggressive_template = nullptr;
ChildTemplate* market_template = nullptr;
std::map<OrderKey, OrderDef> child_orders;
std::map<OrderKey, ChildState> child_state;
Quantity total_filled = Quantity(0);
Book last_book;
TradeVector last_trades;
Quantity running_volume = Quantity(0);
};
OrderAggression& Slicer::aggression()
{
return me->aggression;
}
Slicer::Status& Slicer::status()
{
return me->status;
}
uint32_t& Slicer::generation()
{
return me->generation;
}
uint32_t& Slicer::expected_generations()
{
return me->expected_generations;
}
ChildTemplate*& Slicer::tactical_template()
{
return me->tactical_template;
}
ChildTemplate*& Slicer::aggressive_template()
{
return me->aggressive_template;
}
ChildTemplate*& Slicer::market_template()
{
return me->market_template;
}
void Slicer::add_child(OrderKey k, Channel chan)
{
me->child_orders[k] = OrderDef{ k, me->generation, chan };
}
Quantity& Slicer::total_filled()
{
return me->total_filled;
}
Book& Slicer::last_book()
{
return me->last_book;
}
TradeVector& Slicer::last_trades()
{
return me->last_trades;
}
Quantity& Slicer::running_volume()
{
return me->running_volume;
}
Slicer::Slicer() : me(new PImpl()) {}
Slicer::~Slicer() {}
IAlgoServices& Slicer::algo() const { return *me->algo; }
void Slicer::do_launch(IAlgoServices &algo)
{
me->algo = &algo;
update_params();
bts_assert(tactical_template());
bts_assert(aggressive_template());
bts_assert(market_template());
algo.subscribe_book(SecurityKey(algo.security().id()));
algo.subscribe_ticker(SecurityKey(algo.security().id()));
algo.subscribe_timer();
}
void Slicer::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st)
{
me->algo = &algo;
update_params();
bts_assert(tactical_template());
bts_assert(aggressive_template());
bts_assert(market_template());
add_child(k, Slicer::Channel::Tactical);
on_child_change(k, st);
algo.subscribe_book(SecurityKey(algo.security().id()));
algo.subscribe_ticker(SecurityKey(algo.security().id()));
algo.subscribe_timer();
}
void Slicer::on_child_change(OrderKey key, const ChildState& st)
{
me->child_state[key] = st;
report_status();
}
void Slicer::report_status()
{
uint32_t fills = 0u; bool all_complete = true; double price = 0.0; int idx = 0;
for(const auto& ch : me->child_state)
{
fills += ch.second.total_fills.value();
if(ch.second.status == ChildStatus::COMPLETED )
{
price += ch.second.avg_price.value();
idx++;
}
bool complete = (ch.second.status == ChildStatus::COMPLETED || ch.second.status == ChildStatus::CANCELED);
if(complete)
remove_child(ch.first);
all_complete = all_complete && complete;
}
algo().update_fill_state(Quantity(fills), Price(price / idx));
me->total_filled = Quantity(fills);
if(me->status == Status::DONE)
{
LOG(OrderMan, Info, "Slicer order done and all complete {} ", algo().order_key().value());
if(all_complete)
algo().complete();
}
}
void Slicer::check_i_would(const Book& b)
{
auto iwp = aggression().i_would_price();
if(iwp == 0.0)
return;
auto side = algo().definition().side();
auto other_side = securities::other_side(side);
if(side == api::SIDE_BUY)
{
if(b.side(side)[0].price() <= iwp)
{
auto sz = std::min(b.side(other_side)[0].size(), algo().quantity().value());
send_child(Price(iwp), Quantity(sz), Channel::Aggressive);
}
}
else
{
if(b.side(side)[0].price() >= iwp)
{
auto sz = std::min(b.side(side)[0].size(), algo().quantity().value());
send_child(Price(iwp), Quantity(sz), Channel::Aggressive);
}
}
}
void Slicer::on_book(SecurityKey, const Book& b)
{
me->last_book = b;
LOG(OrderMan, Diag, "Slicer order {} on book. BID: {}@{} ASK: {}@{}",
algo().order_key().value(), b.side(api::SIDE_BUY)[0].size(),
b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(),
b.side(api::SIDE_SELL)[0].price());
switch (me->status)
{
case Status::WAITING_FOR_MD:
{
me->status = Status::WAITING_FOR_START;
if(algo().definition().side() == api::SIDE_BUY)
{
if(me->aggression.i_would_price() >= me->last_book.side( api::SIDE_SELL )[0].price())
algo().terminate_error("Invalid IWould");
}
else
{
if(me->aggression.i_would_price() <= me->last_book.side( api::SIDE_BUY )[0].price())
algo().terminate_error("Invalid IWould");
}
}
break;
case Status::WAITING_FOR_START:
break;
case Status::WORKING:
{
check_i_would(b);
}
case Status::DONE:
break;
}
}
void Slicer::get_done()
{
me->status = Status::DONE;
for(const auto& ch : me->child_orders)
cancel_and_remove_child(ch.first);
if(me->total_filled.value() < algo().quantity().value())
{
int32_t make_up = algo().quantity().value() - me->total_filled.value();
if(make_up > 0)
send_child(Price(0.0), Quantity(make_up), Channel::Market);
}
else
report_status();
}
bool Slicer::validate_price_size(Price price, Quantity size)
{
if(os::is_nan(price.value()) || size.value() <= 0)
return false;
if(size.value() > algo().quantity().value() || os::is_nan(price.value()) )
{
algo().terminate_error("Invalid size of gen " + std::to_string(me->generation) + " order, bigger than initial quantity " +
std::to_string(price.value()) + " " + std::to_string(size.value()));
return false;
}
return true;
}
OrderKey Slicer::send_child(Price price, Quantity size, Channel chan)
{
OrderKey child_key = null_order_key();
if(validate_price_size(price, size))
{
if(aggression().quantity_variance() > 0)
{
//this isn't really variance, but take a look at std::normal_distribution....it's kinda unusable and probably slow
uint32_t var = (rand() % 2*aggression().quantity_variance()) - aggression().quantity_variance();
double new_size = size.value() * (1.0 + var / 100.0);
if(new_size >= 1)
size = Quantity( (uint32_t)new_size );
if(!validate_price_size(price, size))
return child_key;
}
if(aggression().max_participation_pct() > 0)
{
double pct = (double)size.value() / (double)me->running_volume.value();
if(pct*100.0 > aggression().max_participation_pct())
{
double new_size = me->running_volume.value() * (aggression().max_participation_pct() / 100.0);
if(new_size >= 1)
size = Quantity( (uint32_t)new_size );
}
if(!validate_price_size(price, size))
return child_key;
}
LOG(OrderMan, Info, "Slicer launch child {} gen {} p {} s {} c {}", algo().order_key().value(), me->generation,
price.value(), size.value(), (int)chan);
if(chan == Channel::Tactical)
child_key = algo().launch_child(*me->tactical_template, Price(price), Quantity(size));
else if(chan == Channel::Aggressive)
child_key = algo().launch_child(*me->aggressive_template, Price(price), Quantity(size));
else if(chan == Channel::Market)
child_key = algo().launch_child(*me->market_template, Price(price), Quantity(size));
me->child_orders[child_key] = OrderDef{ child_key, me->generation, chan };
}
else
{
LOG(OrderMan, Warn, "Invalid price or size of order {} gen {} p {} s {}", algo().order_key().value(), me->generation,
price.value(), size.value());
}
return child_key;
}
void Slicer::cancel_and_remove_child(OrderKey k)
{
algo().cancel_child(k);
remove_child(k);
}
void Slicer::remove_child(OrderKey k)
{
me->child_orders.erase(k);
}
OrderKey Slicer::upgrade_child(OrderKey key, Channel chan)
{
auto cs = me->child_state.find(key);
if(cs == me->child_state.end())
{
algo().terminate_error("can't find child state");
return null_order_key();
}
else
{
cancel_and_remove_child(key);
int32_t quan = cs->second.quantity.value() - cs->second.total_fills.value();
if(quan > 0)
return send_child(cs->second.price, Quantity(quan), chan);
else
return null_order_key();
}
}
void Slicer::_do_update(const api::orderman::Update& update,
const bts::api::orderman::CustomOrderDefinition& tactical_update,
const bts::api::orderman::CustomOrderDefinition& aggressive_update)
{
LOG(OrderMan, Diag, "Slicer order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update));
if (update.has_custom() && !update.custom().has_twap())
{
algo().terminate_error("Invalid update");
return;
}
Update child_update;
child_update.set_price(update.price());
child_update.set_quantity(update.quantity());
for(auto& i : me->child_orders)
{
if (update.has_custom())
{
update_params();
if(i.second.channel == Channel::Tactical)
*child_update.mutable_custom() = tactical_update;
else if(i.second.channel == Channel::Aggressive)
*child_update.mutable_custom() = aggressive_update;
else if(i.second.channel == Channel::Market) {}
else
bts_assert_msg(false, "unknown channel type");
}
algo().update_child(i.first, child_update);
}
}
void Slicer::on_ticker(SecurityKey, const TradeVector& vec)
{
me->last_trades = vec;
for(const auto& t : vec)
me->running_volume = std::max(me->running_volume, t.total_volume);
LOG(OrderMan, Diag, "Slicer order {} on ticker.", algo().order_key().value());
}
void Slicer::on_timer() {}
void Slicer::first_generation()
{
bts_assert_msg(me->generation == 0, "generation 0");
Price price = algo().price();
Quantity size = algo().quantity();
compute_first_generation(price, size);
if(size.value() > 0)
{
if(me->aggression.allowed_schedule_slippage() > 0)
send_child(price, size, Channel::Tactical);
else
send_child(price, size, Channel::Aggressive);
}
me->generation++;
}
void Slicer::next_generation()
{
LOG(OrderMan, Info, "Slicer next generation order {} gen {} ", algo().order_key().value(), me->generation);
if(me->total_filled.value() >= algo().quantity().value())
{
get_done(); //early
return;
}
for(const auto& ch : me->child_orders)
{
bts_assert_msg(me->generation >= ch.second.generation, fmt::format("incorrect generation {} {}", std::to_string(me->generation), std::to_string(ch.second.generation)) );
uint32_t age = me->generation - ch.second.generation;
if(age > me->aggression.allowed_schedule_slippage())
{
if(ch.second.channel == Channel::Tactical) //move to aggressive
{
LOG(OrderMan, Info, "TimeSlicer upgrade child aggressive {} gen {} child {}", algo().order_key().value(), me->generation, ch.first);
upgrade_child(ch.first, Channel::Aggressive);
}
else if(ch.second.channel == Channel::Aggressive) //move to market
{
LOG(OrderMan, Info, "TimeSlicer upgrade child market {} gen {} child {}", algo().order_key().value(), me->generation, ch.first);
upgrade_child(ch.first, Channel::Market);
}
}
}
//double price = me->last_book.side( algo().definition().side() )[0].price();
Price price = algo().price();
Quantity size = algo().quantity();
compute_next_generation(price, size);
if(size.value() > 0)
{
if(me->aggression.allowed_schedule_slippage() > 0)
send_child(price, size, Channel::Tactical);
else
send_child(price, size, Channel::Aggressive);
}
}
} // namespace orderman
} // namespace bts
@@ -0,0 +1,80 @@
#pragma once
#include "lib/orderman/orders/algo/IAlgoOrder.h"
#include <google/protobuf/timestamp.pb.h>
namespace bts {
namespace api {
namespace orderman {
class OrderDuration;
}
}
namespace orderman {
class ChildTemplate;
struct OrderDef;
class Slicer : public IAlgoOrder
{
public:
Slicer();
~Slicer();
void do_launch(IAlgoServices &) override;
void do_launch_attached(IAlgoServices&, OrderKey, ChildState) override;
void on_child_change(OrderKey, const ChildState&) override;
void on_book(SecurityKey, const Book&) override;
void on_ticker(SecurityKey, const TradeVector&) override;
void on_timer() override;
protected:
enum class Status { WAITING_FOR_MD, WAITING_FOR_START, WORKING, DONE };
enum class Channel { Tactical, Aggressive, Market };
IAlgoServices& algo() const;
void report_status();
void get_done();
bool validate_price_size(Price price, Quantity size);
OrderKey send_child(Price price, Quantity size, Channel chan);
void cancel_and_remove_child(OrderKey k);
void remove_child(OrderKey k);
OrderKey upgrade_child(OrderKey key, Channel chan);
void _do_update(const api::orderman::Update&,
const bts::api::orderman::CustomOrderDefinition& tactical,
const bts::api::orderman::CustomOrderDefinition& aggressive);
protected:
virtual void update_params() = 0;
virtual void compute_first_generation(Price& price, Quantity& size) = 0;
virtual void compute_next_generation(Price& price, Quantity& size) = 0;
virtual void first_generation();
virtual void next_generation();
protected:
struct PImpl;
friend struct OrderDef;
std::unique_ptr<PImpl> me;
protected:
void check_i_would(const Book&);
protected:
api::orderman::OrderAggression& aggression();
Status& status();
uint32_t& generation();
uint32_t& expected_generations();
ChildTemplate*& tactical_template();
ChildTemplate*& aggressive_template();
ChildTemplate*& market_template();
void add_child(OrderKey k, Channel chan);
Quantity& total_filled();
Book& last_book();
TradeVector& last_trades();
Quantity& running_volume();
};
}}
@@ -83,7 +83,11 @@ void TWAPAlgo::compute_first_generation(Price&, Quantity& size)
void TWAPAlgo::compute_next_generation(Price&, Quantity& size)
{
size = Quantity( generation() * algo().quantity().value() / expected_generations() - total_filled().value() );
int32_t sz = generation() * algo().quantity().value() / expected_generations() - total_filled().value();
if(sz > 0)
size = Quantity(sz);
else
size = Quantity(0);
}
@@ -16,50 +16,15 @@ namespace orderman {
using namespace api::orderman;
enum class TimeSlicer::Status { WAITING_FOR_MD, WAITING_FOR_START, WORKING, DONE };
struct OrderDef
{
OrderKey child_key = null_order_key();
uint32_t generation = 0u;
TimeSlicer::Channel channel = TimeSlicer::Channel::Tactical;
};
struct TimeSlicer::PImpl
{
IAlgoServices* algo;
OrderDuration duration;
OrderAggression aggression;
Status status = Status::WAITING_FOR_MD;
google::protobuf::Timestamp start_time, end_time;
uint32_t generation = 0; uint32_t expected_generations = 0;
ChildTemplate* tactical_template = nullptr;
ChildTemplate* aggressive_template = nullptr;
ChildTemplate* market_template = nullptr;
std::map<OrderKey, OrderDef> child_orders;
std::map<OrderKey, ChildState> child_state;
Quantity total_filled = Quantity(0);
Book last_book;
TradeVector last_trades;
Quantity running_volume = Quantity(0);
};
OrderDuration& TimeSlicer::duration()
{
return me->duration;
}
OrderAggression& TimeSlicer::aggression()
{
return me->aggression;
}
TimeSlicer::Status& TimeSlicer::status()
{
return me->status;
}
google::protobuf::Timestamp& TimeSlicer::start_time()
{
return me->start_time;
@@ -68,185 +33,23 @@ google::protobuf::Timestamp& TimeSlicer::end_time()
{
return me->end_time;
}
uint32_t& TimeSlicer::generation()
{
return me->generation;
}
uint32_t& TimeSlicer::expected_generations()
{
return me->expected_generations;
}
ChildTemplate*& TimeSlicer::tactical_template()
{
return me->tactical_template;
}
ChildTemplate*& TimeSlicer::aggressive_template()
{
return me->aggressive_template;
}
ChildTemplate*& TimeSlicer::market_template()
{
return me->market_template;
}
void TimeSlicer::add_child(OrderKey k, Channel chan)
{
me->child_orders[k] = OrderDef{ k, me->generation, chan };
}
Quantity& TimeSlicer::total_filled()
{
return me->total_filled;
}
Book& TimeSlicer::last_book()
{
return me->last_book;
}
TradeVector& TimeSlicer::last_trades()
{
return me->last_trades;
}
Quantity& TimeSlicer::running_volume()
{
return me->running_volume;
}
TimeSlicer::TimeSlicer() : me(new PImpl()) {}
TimeSlicer::~TimeSlicer() {}
IAlgoServices& TimeSlicer::algo() const { return *me->algo; }
void TimeSlicer::do_launch(IAlgoServices &algo)
{
me->algo = &algo;
update_params();
bts_assert(tactical_template());
bts_assert(aggressive_template());
bts_assert(market_template());
algo.subscribe_book(SecurityKey(algo.security().id()));
algo.subscribe_ticker(SecurityKey(algo.security().id()));
algo.subscribe_timer();
}
void TimeSlicer::do_launch_attached(IAlgoServices &algo, OrderKey k, ChildState st)
{
me->algo = &algo;
update_params();
bts_assert(tactical_template());
bts_assert(aggressive_template());
bts_assert(market_template());
add_child(k, TimeSlicer::Channel::Tactical);
on_child_change(k, st);
algo.subscribe_book(SecurityKey(algo.security().id()));
algo.subscribe_ticker(SecurityKey(algo.security().id()));
algo.subscribe_timer();
}
void TimeSlicer::on_child_change(OrderKey key, const ChildState& st)
{
me->child_state[key] = st;
report_status();
}
void TimeSlicer::report_status()
{
uint32_t fills = 0u; bool all_complete = true; double price = 0.0; int idx = 0;
for(const auto& ch : me->child_state)
{
fills += ch.second.total_fills.value();
if(ch.second.status == ChildStatus::COMPLETED )
{
price += ch.second.avg_price.value();
idx++;
}
bool complete = (ch.second.status == ChildStatus::COMPLETED || ch.second.status == ChildStatus::CANCELED);
if(complete)
remove_child(ch.first);
all_complete = all_complete && complete;
}
algo().update_fill_state(Quantity(fills), Price(price / idx));
me->total_filled = Quantity(fills);
if(me->status == Status::DONE)
{
LOG(OrderMan, Info, "TimeSlicer order done and all complete {} ", algo().order_key().value());
if(all_complete)
algo().complete();
}
}
void TimeSlicer::check_i_would(const Book& b)
{
auto iwp = aggression().i_would_price();
if(iwp == 0.0)
return;
auto side = algo().definition().side();
auto other_side = securities::other_side(side);
if(side == api::SIDE_BUY)
{
if(b.side(side)[0].price() <= iwp)
{
auto sz = std::min(b.side(other_side)[0].size(), algo().quantity().value());
send_child(Price(iwp), Quantity(sz), Channel::Aggressive);
}
}
else
{
if(b.side(side)[0].price() >= iwp)
{
auto sz = std::min(b.side(side)[0].size(), algo().quantity().value());
send_child(Price(iwp), Quantity(sz), Channel::Aggressive);
}
}
}
void TimeSlicer::on_book(SecurityKey, const Book& b)
{
me->last_book = b;
LOG(OrderMan, Diag, "TimeSlicer order {} on book. BID: {}@{} ASK: {}@{}",
algo().order_key().value(), b.side(api::SIDE_BUY)[0].size(),
b.side(api::SIDE_BUY)[0].price(), b.side(api::SIDE_SELL)[0].size(),
b.side(api::SIDE_SELL)[0].price());
switch (me->status)
{
case Status::WAITING_FOR_MD:
{
me->status = Status::WAITING_FOR_START;
}
break;
case Status::WAITING_FOR_START:
break;
case Status::WORKING:
{
check_i_would(b);
}
case Status::DONE:
break;
}
}
void TimeSlicer::on_ticker(SecurityKey, const TradeVector& vec)
{
me->last_trades = vec;
for(const auto& t : vec)
me->running_volume = std::max(me->running_volume, t.total_volume);
LOG(OrderMan, Diag, "TimeSlicer order {} on ticker.", algo().order_key().value());
}
void TimeSlicer::on_timer()
{
switch(me->status)
Slicer::on_timer();
switch(status())
{
case Status::WAITING_FOR_MD:
case Slicer::Status::WAITING_FOR_MD:
{
break;
}
case Status::WAITING_FOR_START:
case Slicer::Status::WAITING_FOR_START:
{
if(me->duration.has_start() && me->duration.start().seconds() > 0)
{
@@ -256,18 +59,17 @@ void TimeSlicer::on_timer()
setup_schedule();
return;
}
case Status::WORKING:
case Slicer::Status::WORKING:
{
if (utils::pb::pb_now().seconds() > me->end_time.seconds())
{
get_done();
return;
}
if(me->generation == 0)
if(generation() == 0)
{
LOG(OrderMan, Info, "TimeSlicer First generation order {} ", algo().order_key().value());
first_generation();
me->generation++;
}
else
{
@@ -276,7 +78,7 @@ void TimeSlicer::on_timer()
}
break;
}
case Status::DONE:
case Slicer::Status::DONE:
{
break;
}
@@ -287,7 +89,7 @@ bool TimeSlicer::check_generation_advance()
{
int64_t elapsed = utils::pb::pb_now().seconds() - me->start_time.seconds();
double gen = elapsed / me->duration.interval_in_seconds();
return (gen > me->generation);
return (gen > generation());
}
google::protobuf::Timestamp TimeSlicer::compute_end_time()
@@ -296,14 +98,14 @@ google::protobuf::Timestamp TimeSlicer::compute_end_time()
{
google::protobuf::Timestamp eend;
eend.set_seconds(me->start_time.seconds() + me->duration.duration_in_minutes() * 60);
LOG(OrderMan, Info, "TimeSlicer order {} gen {} end_time {}", algo().order_key().value(), me->generation,
LOG(OrderMan, Info, "TimeSlicer order {} gen {} end_time {}", algo().order_key().value(), generation(),
google::protobuf::util::TimeUtil::ToString(eend));
return eend;
}
else if (me->duration.end_case() == OrderDuration::EndCase::kEndTimestamp)
{
auto ts = me->duration.end_timestamp();
LOG(OrderMan, Info, "TimeSlicer order {} gen {} end_time {}", algo().order_key().value(), me->generation,
LOG(OrderMan, Info, "TimeSlicer order {} gen {} end_time {}", algo().order_key().value(), generation(),
google::protobuf::util::TimeUtil::ToString(ts));
return ts;
}
@@ -316,218 +118,15 @@ google::protobuf::Timestamp TimeSlicer::compute_end_time()
void TimeSlicer::setup_schedule()
{
bts_assert(me->status == Status::WAITING_FOR_START);
me->status = Status::WORKING;
bts_assert(status() == Slicer::Status::WAITING_FOR_START);
status() = Status::WORKING;
me->start_time = utils::pb::pb_now();
me->end_time = compute_end_time();
me->expected_generations = ( me->end_time.seconds() - me->start_time.seconds() ) / me->duration.interval_in_seconds();
if(me->start_time.seconds() > me->end_time.seconds() || me->expected_generations <= 0 || me->expected_generations > 86400)
expected_generations() = ( me->end_time.seconds() - me->start_time.seconds() ) / me->duration.interval_in_seconds();
if(me->start_time.seconds() > me->end_time.seconds() || expected_generations() <= 0 || expected_generations() > 86400)
algo().terminate_error("Invalid scheduling data");
if(algo().definition().side() == api::SIDE_BUY)
{
if(me->aggression.i_would_price() >= me->last_book.side( api::SIDE_SELL )[0].price())
algo().terminate_error("Invalid IWould");
}
else
{
if(me->aggression.i_would_price() <= me->last_book.side( api::SIDE_BUY )[0].price())
algo().terminate_error("Invalid IWould");
}
}
void TimeSlicer::get_done()
{
me->status = Status::DONE;
for(const auto& ch : me->child_orders)
cancel_and_remove_child(ch.first);
if(me->total_filled.value() < algo().quantity().value())
{
int32_t make_up = algo().quantity().value() - me->total_filled.value();
if(make_up > 0)
send_child(Price(0.0), Quantity(make_up), Channel::Market);
}
else
report_status();
}
bool TimeSlicer::validate_price_size(Price price, Quantity size)
{
if(os::is_nan(price.value()) || size.value() <= 0)
return false;
if(size.value() > algo().quantity().value() || os::is_nan(price.value()) )
{
algo().terminate_error("Invalid size of gen " + std::to_string(me->generation) + " order, bigger than initial quantity " +
std::to_string(price.value()) + " " + std::to_string(size.value()));
return false;
}
return true;
}
OrderKey TimeSlicer::send_child(Price price, Quantity size, Channel chan)
{
OrderKey child_key = null_order_key();
if(validate_price_size(price, size))
{
if(aggression().quantity_variance() > 0)
{
//this isn't really variance, but take a look at std::normal_distribution....it's kinda unusable and probably slow
uint32_t var = (rand() % 2*aggression().quantity_variance()) - aggression().quantity_variance();
double new_size = size.value() * (1.0 + var / 100.0);
if(new_size >= 1)
size = Quantity( (uint32_t)new_size );
if(!validate_price_size(price, size))
return child_key;
}
if(aggression().max_participation_pct() > 0)
{
double pct = (double)size.value() / (double)me->running_volume.value();
if(pct*100.0 > aggression().max_participation_pct())
{
double new_size = me->running_volume.value() * (aggression().max_participation_pct() / 100.0);
if(new_size >= 1)
size = Quantity( (uint32_t)new_size );
}
if(!validate_price_size(price, size))
return child_key;
}
LOG(OrderMan, Info, "TimeSlicer launch child {} gen {} p {} s {} c {}", algo().order_key().value(), me->generation,
price.value(), size.value(), (int)chan);
if(chan == Channel::Tactical)
child_key = algo().launch_child(*me->tactical_template, Price(price), Quantity(size));
else if(chan == Channel::Aggressive)
child_key = algo().launch_child(*me->aggressive_template, Price(price), Quantity(size));
else if(chan == Channel::Market)
child_key = algo().launch_child(*me->market_template, Price(price), Quantity(size));
me->child_orders[child_key] = OrderDef{ child_key, me->generation, chan };
}
else
{
LOG(OrderMan, Warn, "Invalid price or size of order {} gen {} p {} s {}", algo().order_key().value(), me->generation,
price.value(), size.value());
}
return child_key;
}
void TimeSlicer::cancel_and_remove_child(OrderKey k)
{
algo().cancel_child(k);
remove_child(k);
}
void TimeSlicer::remove_child(OrderKey k)
{
me->child_orders.erase(k);
}
OrderKey TimeSlicer::upgrade_child(OrderKey key, Channel chan)
{
auto cs = me->child_state.find(key);
if(cs == me->child_state.end())
{
algo().terminate_error("can't find child state");
return null_order_key();
}
else
{
cancel_and_remove_child(key);
int32_t quan = cs->second.quantity.value() - cs->second.total_fills.value();
if(quan > 0)
return send_child(cs->second.price, Quantity(quan), chan);
else
return null_order_key();
}
}
void TimeSlicer::_do_update(const api::orderman::Update& update,
const bts::api::orderman::CustomOrderDefinition& tactical_update,
const bts::api::orderman::CustomOrderDefinition& aggressive_update)
{
LOG(OrderMan, Diag, "TimeSlicer order {} receiving update: {}", algo().order_key().value(), utils::pb::to_string(update));
if (update.has_custom() && !update.custom().has_twap())
{
algo().terminate_error("Invalid update");
return;
}
Update child_update;
child_update.set_price(update.price());
child_update.set_quantity(update.quantity());
for(auto& i : me->child_orders)
{
if (update.has_custom())
{
update_params();
if(i.second.channel == Channel::Tactical)
*child_update.mutable_custom() = tactical_update;
else if(i.second.channel == Channel::Aggressive)
*child_update.mutable_custom() = aggressive_update;
else if(i.second.channel == Channel::Market) {}
else
bts_assert_msg(false, "unknown channel type");
}
algo().update_child(i.first, child_update);
}
}
void TimeSlicer::first_generation()
{
bts_assert_msg(me->generation == 0, "generation 0");
Price price = algo().price();
Quantity size = algo().quantity();
compute_first_generation(price, size);
if(size.value() > 0)
{
if(me->aggression.allowed_schedule_slippage() > 0)
send_child(price, size, Channel::Tactical);
else
send_child(price, size, Channel::Aggressive);
}
}
void TimeSlicer::next_generation()
{
LOG(OrderMan, Info, "TimeSlicer next generation order {} gen {} ", algo().order_key().value(), me->generation);
if(me->total_filled.value() >= algo().quantity().value())
{
get_done(); //early
return;
}
for(const auto& ch : me->child_orders)
{
bts_assert_msg(me->generation >= ch.second.generation, fmt::format("incorrect generation {} {}", std::to_string(me->generation), std::to_string(ch.second.generation)) );
uint32_t age = me->generation - ch.second.generation;
if(age > me->aggression.allowed_schedule_slippage())
{
if(ch.second.channel == Channel::Tactical) //move to aggressive
{
LOG(OrderMan, Info, "TimeSlicer upgrade child aggressive {} gen {} child {}", algo().order_key().value(), me->generation, ch.first);
upgrade_child(ch.first, Channel::Aggressive);
}
else if(ch.second.channel == Channel::Aggressive) //move to market
{
LOG(OrderMan, Info, "TimeSlicer upgrade child market {} gen {} child {}", algo().order_key().value(), me->generation, ch.first);
upgrade_child(ch.first, Channel::Market);
}
}
}
//double price = me->last_book.side( algo().definition().side() )[0].price();
Price price = algo().price();
Quantity size = algo().quantity();
compute_next_generation(price, size);
if(size.value() > 0)
{
if(me->aggression.allowed_schedule_slippage() > 0)
send_child(price, size, Channel::Tactical);
else
send_child(price, size, Channel::Aggressive);
}
}
} // namespace orderman
@@ -1,87 +1,31 @@
#pragma once
#include "lib/orderman/orders/algo/IAlgoOrder.h"
#include <google/protobuf/timestamp.pb.h>
#include "lib/orderman/orders/algo/algo_orders/bluex/Slicer.h"
namespace bts {
namespace api {
namespace orderman {
class OrderDuration;
}
}
namespace orderman {
class ChildTemplate;
struct OrderDef;
class TimeSlicer : public IAlgoOrder
class TimeSlicer : public Slicer
{
public:
TimeSlicer();
~TimeSlicer();
void do_launch(IAlgoServices &) override;
void do_launch_attached(IAlgoServices&, OrderKey, ChildState) override;
void on_child_change(OrderKey, const ChildState&) override;
void on_book(SecurityKey, const Book&) override;
void on_ticker(SecurityKey, const TradeVector&) override;
void on_timer() override;
void on_timer() override;
protected:
enum class Status;
enum class Channel { Tactical, Aggressive, Market };
IAlgoServices& algo() const;
void report_status();
google::protobuf::Timestamp compute_end_time();
void setup_schedule();
void get_done();
bool validate_price_size(Price price, Quantity size);
OrderKey send_child(Price price, Quantity size, Channel chan);
void cancel_and_remove_child(OrderKey k);
void remove_child(OrderKey k);
OrderKey upgrade_child(OrderKey key, Channel chan);
void _do_update(const api::orderman::Update&,
const bts::api::orderman::CustomOrderDefinition& tactical,
const bts::api::orderman::CustomOrderDefinition& aggressive);
protected:
virtual void update_params() = 0;
virtual void compute_first_generation(Price& price, Quantity& size) = 0;
virtual void compute_next_generation(Price& price, Quantity& size) = 0;
virtual void first_generation();
virtual void next_generation();
virtual bool check_generation_advance();
bool check_generation_advance();
protected:
struct PImpl;
friend struct OrderDef;
std::unique_ptr<PImpl> me;
protected:
void check_i_would(const Book&);
protected:
api::orderman::OrderDuration& duration();
api::orderman::OrderAggression& aggression();
Status& status();
google::protobuf::Timestamp& start_time();
google::protobuf::Timestamp& end_time();
uint32_t& generation();
uint32_t& expected_generations();
ChildTemplate*& tactical_template();
ChildTemplate*& aggressive_template();
ChildTemplate*& market_template();
void add_child(OrderKey k, Channel chan);
Quantity& total_filled();
Book& last_book();
TradeVector& last_trades();
Quantity& running_volume();
google::protobuf::Timestamp& end_time();
};
}}
@@ -1,4 +1,5 @@
#include "lib/orderman/orders/algo/algo_orders/bluex/VWAPAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/bluex/VolumeEstimator.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include "lib/orderman/orders/algo/DynamicHelpers.h"
#include "lib/api/services/OrderService.pb.h"
@@ -16,7 +17,7 @@ using namespace api::orderman;
struct VWAPAlgo::PImpl
{
VolumeDistribution volume_dist;
VolumeEstimator volume_est;
};
VWAPAlgo::VWAPAlgo() : me(new PImpl()) {}
@@ -81,18 +82,16 @@ void VWAPAlgo::update_params()
algo().terminate_error("Invalid volume dist params, terminating");
return;
}
if (algo().definition().custom_def().vwap().volume_distribution().volume_mean_override() <= 0.0 ||
algo().definition().custom_def().vwap().volume_distribution().volume_variance_override() <= 0.0)
if(!me->volume_est.update_params(algo().definition().custom_def().vwap().volume_distribution()))
{
algo().terminate_error("Algo needs volume mean and variance overrides temporarily, terminating");
return;
}
me->volume_dist = algo().definition().custom_def().vwap().volume_distribution();
}
}
void VWAPAlgo::compute_first_generation(Price&, Quantity& size)
{
double ratio = running_volume().value() / me->volume_dist.volume_mean_override();
double ratio = running_volume().value() / me->volume_est.day_volume().value();
ratio = std::min(1.0, ratio);
ratio = std::max(0.0, ratio);
size = Quantity( ratio * size.value() );
@@ -101,7 +100,7 @@ void VWAPAlgo::compute_first_generation(Price&, Quantity& size)
void VWAPAlgo::compute_next_generation(Price&, Quantity& size)
{
//TODO predict this period based on prior
double ratio = running_volume().value() / me->volume_dist.volume_mean_override();
double ratio = running_volume().value() / me->volume_est.day_volume().value();
ratio = std::min(1.0, ratio);
ratio = std::max(0.0, ratio);
size = Quantity( ratio * size.value() );
@@ -0,0 +1,47 @@
#include "lib/orderman/orders/algo/algo_orders/bluex/VolumeEstimator.h"
#include "lib/api/services/OrderService.pb.h"
namespace bts {
namespace orderman {
using namespace api::orderman;
struct VolumeEstimator::PImpl
{
VolumeDistribution volume_distribution;
};
VolumeEstimator::VolumeEstimator() : me(new PImpl()) {}
VolumeEstimator::~VolumeEstimator() {}
const VolumeDistribution& VolumeEstimator::get_distribution() const
{
return me->volume_distribution;
}
VolumeDistribution& VolumeEstimator::get_distribution()
{
return me->volume_distribution;
}
bool VolumeEstimator::update_params(const api::orderman::VolumeDistribution& vd)
{
me->volume_distribution = vd;
if (me->volume_distribution.volume_mean_override() <= 0.0 ||
me->volume_distribution.volume_variance_override() <= 0.0)
{
return false;
}
return true;
}
Quantity VolumeEstimator::day_volume() const
{
//TODO estimator
return Quantity( me->volume_distribution.volume_mean_override() );
}
}
}
@@ -0,0 +1,32 @@
#pragma once
#include "lib/domain_model/common.h"
#include <memory>
namespace bts {
namespace api {
namespace orderman {
class VolumeDistribution;
}
}
namespace orderman {
class VolumeEstimator
{
public:
VolumeEstimator();
~VolumeEstimator();
bool update_params(const api::orderman::VolumeDistribution&);
Quantity day_volume() const;
const api::orderman::VolumeDistribution& get_distribution() const;
api::orderman::VolumeDistribution& get_distribution();
protected:
struct PImpl;
std::unique_ptr<PImpl> me;
};
}
}
@@ -0,0 +1,92 @@
#include "lib/orderman/orders/algo/algo_orders/bluex/VolumeSlicer.h"
#include "lib/orderman/orders/algo/algo_orders/bluex/VolumeEstimator.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include "lib/orderman/orders/algo/DynamicHelpers.h"
#include "lib/api/services/OrderService.pb.h"
#include "lib/orderman/order_factory/IOrderFactory.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
#include "lib/os/os.h"
#include "lib/utils/PBUtils.h"
#include <fmt/format.h>
#include <google/protobuf/util/time_util.h>
#include <random>
namespace bts {
namespace orderman {
using namespace api::orderman;
struct VolumeSlicer::PImpl
{
VolumeEstimator estimator;
};
VolumeEstimator& VolumeSlicer::volume_estimator()
{
return me->estimator;
}
VolumeSlicer::VolumeSlicer() : me(new PImpl()) {}
VolumeSlicer::~VolumeSlicer() {}
void VolumeSlicer::on_ticker(SecurityKey k, const TradeVector& vec)
{
Slicer::on_ticker(k, vec);
switch(status())
{
case Slicer::Status::WAITING_FOR_MD:
{
break;
}
case Slicer::Status::WAITING_FOR_START:
{
setup_schedule();
return;
}
case Slicer::Status::WORKING:
{
// if (utils::pb::pb_now().seconds() > me->end_time.seconds())
// {
// get_done();
// return;
// }
if(generation() == 0)
{
LOG(OrderMan, Info, "TimeSlicer First generation order {} ", algo().order_key().value());
first_generation();
}
else
{
if(check_generation_advance())
next_generation();
}
break;
}
case Slicer::Status::DONE:
{
break;
}
}
}
bool VolumeSlicer::check_generation_advance()
{
return true;
}
void VolumeSlicer::setup_schedule()
{
bts_assert(status() == Slicer::Status::WAITING_FOR_START);
status() = Status::WORKING;
expected_generations() = (uint32_t) me->estimator.day_volume().value() / algo().quantity().value();
if(expected_generations() <= 0 || expected_generations() > 86400)
algo().terminate_error("Invalid scheduling data");
}
} // namespace orderman
} // namespace bts
@@ -0,0 +1,30 @@
#pragma once
#include "lib/orderman/orders/algo/algo_orders/bluex/Slicer.h"
namespace bts {
namespace orderman {
class VolumeEstimator;
class VolumeSlicer : public Slicer
{
public:
VolumeSlicer();
~VolumeSlicer();
void on_ticker(SecurityKey, const TradeVector&) override;
protected:
bool check_generation_advance();
void setup_schedule();
protected:
struct PImpl;
friend struct OrderDef;
std::unique_ptr<PImpl> me;
protected:
VolumeEstimator& volume_estimator();
};
}}