#include "SniperModel.h" #include "back_testing/sim/ISim.h" #include "back_testing/sim/pandl/PandL.h" #include "back_testing/sim/sim_common.h" #include "domain/SecurityDefinition.h" #include "domain/polygons/polygon_utils.h" #include "feed_handler/utils/book_utils.h" #include "feed_handler/utils/mdp3_utils.h" #include #include #include namespace bts::spartan::mdp3 { enum class SniperModel::State { W_OPPORTUNITY, SHOOTING, PAUSED }; struct SniperModel::Target { constexpr static double Worthless = -1.0; size_t polygon_id; Polygon const polygon; boost::container::small_vector leg_sec_info; std::string const descriptor; api::Side side; double value = Worthless; Quantity quantity = Quantity{0}; void mark_as_worthless() { value = Worthless; } bool has_value(double v) const { return value > v; } }; struct SniperModel::WorkingOrder { SmallOrderChange order; std::vector fills; }; struct SniperModel::Shot { Target ⌖ EventHeader observed; EventHeader concluded; double value_at_observation_ts; Quantity quantity; bool forced_completion; std::unordered_map working; size_t transaction_duration; }; struct SniperModel::DependentTargets { SecurityDefinition definition; SimBookUpdate book; std::vector dependencies; }; struct SniperModel::PImpl { ISim *sim = nullptr; protos::SimRunOptions options; int min_orders_at_top; int max_qty; int min_depth; double min_value; size_t max_transaction_latency_us; bool double_dip; size_t ms_to_work_shot; size_t min_cumm_qty; double min_cumm_edge; size_t pay_up_ticks; size_t throttle_ns; double max_shot_loss; std::set polys; EventHeader current_event; size_t streak_id = 0; State state = State::W_OPPORTUNITY; std::unordered_map books = {}; std::vector> targets = {}; std::optional current_shot{}; }; SniperModel::SniperModel() : me(new PImpl()) {} SniperModel::~SniperModel() {} void SniperModel::init(ISim &s, protos::SimRunOptions const &options) { me->sim = &s; me->options = options; } void SniperModel::on_replay_start( EventHeader const &h, std::vector const &books) { auto parse_poly_filter = [](std::string const &pf) { std::vector polys; boost::split(polys, pf, boost::is_any_of(",")); std::set result; for (std::string &s : polys) { boost::trim(s); if (s.size()) result.insert(s); } return result; }; auto sim = me->sim; auto options = me->options; auto streak_id = me->streak_id; me.reset(new PImpl{ sim, options, get_param(me->options, "min_orders_at_top"), get_param(me->options, "max_qty"), get_param(me->options, "min_depth"), get_param(me->options, "min_value"), get_param(me->options, "max_transaction_latency_us"), get_param(me->options, "double_dip"), get_param(me->options, "ms_to_work_shot"), get_param(me->options, "min_cumm_qty"), get_param(me->options, "min_cumm_edge"), get_param(me->options, "pay_up_ticks"), get_param(me->options, "throttle_ns"), get_param(me->options, "max_shot_loss"), parse_poly_filter(get_param(me->options, "polys")), h, streak_id}); for (auto &p : me->sim->polygons()) { auto desc = polygon_descriptor(p.second, me->sim->securities()); if (me->polys.size() && !me->polys.count(desc)) continue; auto buy_t = std::make_unique( Target{p.first, p.second, {}, desc, api::SIDE_BUY}); auto sell_t = std::make_unique( Target{p.first, flip(p.second), {}, desc, api::SIDE_SELL}); me->targets.emplace_back(std::move(buy_t)); me->targets.emplace_back(std::move(sell_t)); } for (auto &t : me->targets) { for (auto &pp : t->polygon.parts) { auto &dt = me->books[pp.sec_id]; dt.book.security_id = pp.sec_id; dt.definition = me->sim->get_security(pp.sec_id); t->leg_sec_info.push_back(&dt); auto &dependencies = dt.dependencies; dependencies.push_back(t.get()); } } me->sim->log("replay_start"); for (auto const &mbp : books) { auto it = me->books.find(mbp.security_id); if (it != me->books.end()) { me->sim->log( "book_at_replay_start", me->sim->get_security(mbp.security_id).symbol(), mbp.mbp_buy[0].price.to_double(), mbp.mbp_buy[0].quantity.value(), mbp.mbp_sell[0].price.to_double(), mbp.mbp_sell[0].quantity.value()); it->second.book = mbp; } } } void SniperModel::on_mbp(EventHeader const &h, const SimBookUpdate &mbp) { me->current_event = h; auto it = me->books.find(mbp.security_id); if (it == me->books.end()) return; auto &book = it->second; book.book = mbp; eval(book.dependencies); switch (me->state) { case State::W_OPPORTUNITY: { auto best_shot = pick(); if (best_shot) { me->streak_id++; me->sim->start_simulation(); transition(State::SHOOTING); fire(best_shot.value()); } break; } case State::SHOOTING: break; case State::PAUSED: check_if_pause_over(); break; } } void SniperModel::on_order_update( EventHeader const &h, const SimOrderUpdate &update) { me->current_event = h; bts_assert(me->state == State::SHOOTING); bts_assert(me->current_shot); auto &in_flight = me->current_shot.value(); bts_assert(in_flight.working.count(update.key)); in_flight.working[update.key].fills.push_back(update); auto pending_orders = in_flight.working.size(); bool clean_fills = true; for (auto const &p : in_flight.working) { auto &these_fills = p.second.fills; for (auto &f : these_fills) { clean_fills = clean_fills && (f.fill_type == SimOrderUpdate::AGGRESSIVE); if (f.status == SimOrderUpdate::CANCELED || f.status == SimOrderUpdate::FILLED) { pending_orders--; break; } } } if (pending_orders == 0) { std::vector all_fills; for (auto const &p : in_flight.working) { auto &these_fills = p.second.fills; all_fills.insert( all_fills.end(), these_fills.begin(), these_fills.end()); } PandL pandl(me->sim->securities()); auto cash = pandl.net_cash(all_fills); auto commission = pandl.commission_cost( map_commission_model(me->options.commission_model()), all_fills); auto net = cash - commission; in_flight.concluded = h; me->sim->log( "shot_outcome", in_flight.target.descriptor, api::Side_Name(in_flight.target.side), in_flight.observed.event_id.first, in_flight.observed.event_id.second, in_flight.value_at_observation_ts * in_flight.quantity.value(), net, commission, in_flight.quantity.value(), clean_fills && !me->current_shot->forced_completion, me->current_shot->forced_completion, in_flight.transaction_duration); me->sim->log_pandl(); if (!me->double_dip) transition(State::PAUSED); else { auto best_shot = pick(); if (best_shot) { me->sim->log("double_dip", me->streak_id); fire(best_shot.value()); } else transition(State::PAUSED); } } } void SniperModel::on_time() { switch (me->state) { case State::W_OPPORTUNITY: { break; } case State::SHOOTING: { maybe_force_fills(); break; } case State::PAUSED: check_if_pause_over(); break; } } void SniperModel::maybe_force_fills() { bts_assert(me->state == State::SHOOTING); bts_assert(me->current_shot); auto ts = me->sim->time(); auto shot_observed_ts = me->current_shot->observed.observable_time; auto shot_duration = ts.value() - shot_observed_ts.value(); if (me->current_shot->forced_completion) return; if (me->ms_to_work_shot) { if (shot_duration > 1000 * 1000 * me->ms_to_work_shot) { me->sim->log("forcing_fills_timeout", shot_observed_ts.value()); me->current_shot->forced_completion = true; } else if (me->current_shot->target.value < -me->max_shot_loss) { me->sim->log("forcing_fills_maxloss", shot_observed_ts.value()); me->current_shot->forced_completion = true; } } if (!me->current_shot->forced_completion) return; auto &in_flight = me->current_shot.value(); for (auto &p : in_flight.working) { auto &order = p.second.order; auto &these_fills = p.second.fills; auto total_fills = 0; for (auto &f : these_fills) { bts_assert(f.status != SimOrderUpdate::CANCELED); total_fills += f.last_fills.value(); } if (order.order.quantity.value() > total_fills) { Price worst_price = order.order.price; if (order.order.side == Side::Buy) worst_price += me->sim->get_security(order.order.security) .min_price_increment_int_price() * 100; else worst_price -= me->sim->get_security(order.order.security) .min_price_increment_int_price() * 100; order.change = OrderChange::updated_price; order.order.price = worst_price; me->sim->send(order); } } } void SniperModel::eval(std::vector const &targets) { for (auto &t : targets) { t->value = 0; int qty = me->max_qty; size_t p_idx = 0; for (auto &l : t->polygon.parts) { auto mkt_side = other_side(side_from_ratio(l.ratio)); auto &leg_sec_info = t->leg_sec_info[p_idx++]; auto &mkt = leg_sec_info->book.mbp_side(mkt_side); auto this_qty = mkt[0].quantity.value(); auto this_ratio = this_qty / std::abs(l.ratio); if (this_ratio < qty) qty = this_ratio; if (qty == 0 || mkt[0].n_orders < me->min_orders_at_top || mkt.total_depth().value() < me->min_depth) { t->mark_as_worthless(); break; } else { auto cash = leg_sec_info->definition.to_cash(mkt[0].price.to_double()); t->quantity.value() = qty; t->value += -l.ratio * cash; } } } } bool SniperModel::within_safety_margin(Target const &t) const { BookSide synth_book; using LegInfo = std::tuple; std::vector leg_mkts; for (auto &leg : t.polygon.parts) { auto &leg_mkt = leg_mkts.emplace_back(); std::get<0>(leg_mkt) = Quantity{leg.ratio}; std::get<1>(leg_mkt) = {}; auto leg_book_side = other_side(side_from_ratio(leg.ratio)); std::get<2>(leg_mkt) = me->books[leg.sec_id].book.mbp_side(leg_book_side); } book_utils::compute_synthetic_book( synth_book, leg_mkts, BookSide::max_depth()); auto cumm_qty = 0ul; auto min_price = me->min_cumm_edge; // This is not right, exactly, we are assuming all the legs are // expressed in the same terms as the first. auto &first_leg_def = t.leg_sec_info[0]->definition; auto p_value = t.value; // The synth book calculation uses a different convention. if a // polygon has value the synth book will have a < 0 price. auto s_value = -(first_leg_def.to_cash(synth_book[0].price)); // The synth book should match the first level of the polygon value. bts_assert(std::abs(p_value - s_value) < securities::market_epsilon()); for (auto &level : synth_book) { // Again, we need to flip the sign because the convention of the // synth book calculation is to return <0 for polygons with // value. auto level_cash_price = first_leg_def.to_cash(-level.price); // We crossed the threshold that allows us to ignore the quantity. if (level_cash_price >= min_price) return true; else if (level_cash_price >= me->min_value) cumm_qty += level.quantity.value(); else break; } return cumm_qty >= me->min_cumm_qty; } SniperModel::MaybeShot SniperModel::pick() { std::sort( me->targets.begin(), me->targets.end(), [](std::unique_ptr const &ptr1, std::unique_ptr const &ptr2) { auto val1 = ptr1->value * ptr1->quantity.value(); auto val2 = ptr2->value * ptr2->quantity.value(); if (std::abs(val1 - val2) > securities::market_epsilon()) return val1 > val2; else if (ptr1->polygon.parts.size() != ptr2->polygon.parts.size()) return ptr1->polygon.parts.size() < ptr2->polygon.parts.size(); else return ptr1->polygon_id < ptr2->polygon_id; }); auto &best_target = *me->targets[0]; if (best_target.has_value(me->min_value)) { bool has_any_qty = me->max_qty; auto transaction_duration = me->current_event.observable_time.value() - me->current_event.transact_time.value(); bool transaction_is_fresh = transaction_duration < 1000 * me->max_transaction_latency_us; if (has_any_qty && transaction_is_fresh && within_safety_margin(best_target)) return Shot{ best_target, me->current_event, {}, best_target.value, best_target.quantity, false, {}, transaction_duration}; else return {}; } else return {}; } void SniperModel::fire(Shot const &s) { auto &shot = me->current_shot.emplace(s); me->sim->log( "shot_begin", s.target.descriptor, api::Side_Name(s.target.side), s.value_at_observation_ts, s.quantity.value(), me->streak_id); for (auto const &b : me->books) { auto const &mbp = b.second.book; me->sim->log( "book_at_shot_start", me->sim->get_security(mbp.security_id).symbol(), mbp.mbp_buy[0].price.to_double(), mbp.mbp_buy[0].quantity.value(), mbp.mbp_sell[0].price.to_double(), mbp.mbp_sell[0].quantity.value()); } if (me->ms_to_work_shot == 0) { shot.forced_completion = true; for (auto &p : shot.target.polygon.parts) { auto part_side = from_ratio(p.ratio); auto mkt_side = other_side(part_side); auto &book = me->books[p.sec_id].book.mbp_side(mkt_side); Price worst_price; size_t available_qty = 0; for (int i = book.size() - 1; i >= 0; i--) { if (book[i].quantity.value()) { worst_price = book[i].price; for (int n = 0; n <= i; n++) available_qty += book[n].quantity.value(); break; } } if (part_side == Side::Buy) worst_price += me->sim->get_security(p.sec_id) .min_price_increment_int_price() * 100; else worst_price -= me->sim->get_security(p.sec_id) .min_price_increment_int_price() * 100; auto order_change = SmallOrderChange{}; order_change.order.security = p.sec_id; order_change.order.price = worst_price; order_change.order.quantity = Quantity{s.quantity.value() * std::abs(p.ratio)}; order_change.order.side = part_side; order_change.change = OrderChange::added; order_change.order.key = me->sim->send(order_change); shot.working[order_change.order.key].order = order_change; order_change.change = OrderChange::removed; me->sim->send(order_change); } } else { for (auto &p : shot.target.polygon.parts) { auto part_side = from_ratio(p.ratio); auto mkt_side = other_side(part_side); auto &book = me->books[p.sec_id].book.mbp_side(mkt_side); auto limit_price = book[0].price; auto pay_up_adj = me->sim->get_security(p.sec_id).min_price_increment_int_price() * me->pay_up_ticks; if (part_side == Side::Buy) limit_price += pay_up_adj; else limit_price -= pay_up_adj; auto order_change = SmallOrderChange{}; order_change.order.security = p.sec_id; order_change.order.price = limit_price; order_change.order.quantity = Quantity{s.quantity.value() * std::abs(p.ratio)}; order_change.order.side = part_side; order_change.change = OrderChange::added; order_change.order.key = me->sim->send(order_change); me->sim->log( "sent_order", Side_Name(part_side), me->sim->get_security(p.sec_id).symbol(), book[0].price.to_double(), book[0].price.to_double(), book[0].quantity.value()); shot.working[order_change.order.key].order = order_change; } } } void SniperModel::check_if_pause_over() { bts_assert(me->state == State::PAUSED); bts_assert(me->current_shot); bts_assert(me->throttle_ns); auto ns_since_shot_concluded = me->sim->time().value() - me->current_shot->concluded.observable_time.value(); if (ns_since_shot_concluded > me->throttle_ns) me->sim->stop_simulation(); else me->sim->log("paused"); } const char *SniperModel::state_name(State s) { switch (s) { case State::SHOOTING: return "WAIT_FILLS"; case State::W_OPPORTUNITY: return "WAIT_OPPORTUNITY"; case State::PAUSED: return "WAIT_OPPORTUNITY_CLEAR"; } return nullptr; } void SniperModel::transition(State new_state) { me->sim->log("transition", state_name(me->state), state_name(new_state)); me->state = new_state; } protos::SimRunOptions SniperModel::fill_defaults( protos::SimRunOptions const &in) { protos::SimRunOptions result = in; set_param_if_empty(&result, "min_orders_at_top", 1); set_param_if_empty(&result, "max_qty", 1); set_param_if_empty(&result, "min_depth", 0); set_param_if_empty(&result, "min_value", 2.0); set_param_if_empty(&result, "max_transaction_latency_us", 10000); set_param_if_empty(&result, "double_dip", false); set_param_if_empty(&result, "ms_to_work_shot", 0); set_param_if_empty(&result, "min_cumm_edge", 17.5); set_param_if_empty(&result, "min_cumm_qty", 10); set_param_if_empty(&result, "pay_up_ticks", 10); set_param_if_empty(&result, "throttle_ns", 1 * 1000 * 1000 * 1000); set_param_if_empty(&result, "max_shot_loss", 200); set_param_if_empty(&result, "polys", ""); return result; } } // namespace bts::spartan::mdp3