Files
spark/src/server/sparkd/cmds/spartan/back_testing/matcher/FifoPriceLevelMatcher.cpp
T
2020-12-29 20:01:48 -05:00

320 lines
12 KiB
C++

#include "FifoPriceLevelMatcher.h"
#include "server/sparkd/cmds/spartan/md/mdp3/common/InstrumentSnapshot.h"
#include "server/sparkd/cmds/spartan/util/action_summarizer_macros.h"
#include "server/sparkd/cmds/spartan/md/mdp3/common/mdp3_quantity_operators.h"
namespace bts::spartan::mdp3 {
// private helpers ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// orders can cease to be part of this level if there is
// a null slot (ex when the order is physcially moved to another
// price level or at the end of the queue) or the order is cxl'ed
// with the is_active marker
inline bool in_this_level(MatcherOrder const* o_ptr){
return o_ptr!=nullptr && o_ptr->is_active;
}
api::Side _opp_side(api::Side side){
return side == api::Side::SIDE_BUY ? api::Side::SIDE_SELL :
api::Side::SIDE_BUY;
}
// O(n) linear search
MatcherOrder *FifoPriceLevelMatcher::_find(MDP3OrderKey key) {
for (MatcherOrder* op : _orders)
if (in_this_level(op) && op->key == key)
return op;
return nullptr;
}
void FifoPriceLevelMatcher::_logically_delete(MatcherOrder &o) {
_log_order(o,"FifoPriceLevelMatcher::_logically_delete");
o.is_active = false;
}
void FifoPriceLevelMatcher::_add_order(const MDP3Order &ord) {
MatcherOrder new_ord (ord.key,ord.side,ord.price,ord.quantity,
_priority++,ord.iceberg_quantity);
auto[p,res] = _master_order_map->try_emplace(new_ord.key,new_ord);
MatcherOrder* new_ord_ptr = &p->second;
_orders.push_back(new_ord_ptr);
if(!res)
// it exists, so this order is moved from another price level
// to this price level
*new_ord_ptr = new_ord;
}
// O(n) iteration through all orders to detect loadable ib's
void FifoPriceLevelMatcher::_reload_icebergs() {
_aux_usage.clear();
for (auto it=_orders.begin();it!=_orders.end();it++){
MatcherOrder* o_ptr = *it;
if(in_this_level(o_ptr) && o_ptr->ready_to_load_ib()){
_aux_usage.push_back(o_ptr);
*it = nullptr;
}
}
// add it back
for (auto o : _aux_usage) {
o->reload_ib();
o->priority = _priority++;
_orders.push_back(o);
}
}
std::tuple<MDP3Quantity, MDP3Quantity>
FifoPriceLevelMatcher::_one_pass_cross_order(MDP3OrderKey cross_ord_key,
MDP3Quantity cross_ord_qty,
bool add_agg_side_to_match_effect,
std::vector<MatchEffect>* res) {
// go through all the orders and see which ones get filled
// (orders are sorted by priority)
for (MatcherOrder* op : _orders) {
if (in_this_level(op)) {
auto& o = *op;
auto [o_rem, cross_rem, filled] = o.cross(cross_ord_qty.value());
cross_ord_qty = MDP3Quantity(cross_rem);
if(res != nullptr){
OrderUpdate passive_upd =
{
o.key,
o.total_qty().value() > 0 ?
OrderUpdate::Status::PARTIALLY_FILLED :
OrderUpdate::Status::FILLED,
_sec,
_side,
MDP3Quantity(filled),
_price,
OrderUpdate::FillType::PASSIVE
};
MatcherUtils::validate_outgoing_update(passive_upd);
res->push_back(passive_upd);
if(add_agg_side_to_match_effect){
OrderUpdate agg_upd =
{
cross_ord_key,
cross_ord_qty.value() > 0 ?
OrderUpdate::Status::PARTIALLY_FILLED :
OrderUpdate::Status::FILLED,
_sec,
_opp_side(_side),
MDP3Quantity(filled),
_price,
OrderUpdate::FillType::AGGRESSIVE
};
MatcherUtils::validate_outgoing_update(agg_upd);
res->push_back(agg_upd);
}
}
if(_trace.log(o.key) || _trace.log(cross_ord_key))
LOG(OrderMan, Diag,
"FifoPriceLevelMatcher::_one_pass_cross_order "
"{} (new_qty:{}) crossed by {} (new_qty:{})",
o.key, o_rem, cross_ord_key, cross_rem);
if (cross_rem > 0)
bts_assert(o_rem == 0); // visible qty should be completely crossed
else
break; // crossed order is completely filled
}
}
if (cross_ord_qty.value() > 0)
bts_assert(quantity().value() == 0);
// reload the filled ib's and put them at the back
_reload_icebergs();
return std::make_tuple(total_quantity(), cross_ord_qty);
}
void FifoPriceLevelMatcher::_log_order(const MatcherOrder& ord,
const std::string& msg){
if(_trace.log(ord.key))
LOG(OrderMan, Diag,
"{} key:{} side:{} qty:{} ib_qty:{} price:{}",
msg, ord.key, static_cast<int>(side()), ord.quantity,
ord.ib.has_value() ? ord.ib.value().total : MDP3Quantity(0),
price());
}
void FifoPriceLevelMatcher::_log_order(const MDP3Order& ord,
const std::string& msg){
if(_trace.log(ord.key))
LOG(OrderMan, Diag,
"{} key:{} side:{} qty:{} ib_qty:{} price:{}",
msg, ord.key, static_cast<int>(ord.side), ord.quantity,
ord.iceberg_quantity.has_value() ? FMT(ord.iceberg_quantity.value())
: FMT(MDP3Quantity(0)),
ord.price.price());
}
// constructors ///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FifoPriceLevelMatcher::FifoPriceLevelMatcher(
std::map<MDP3OrderKey,MatcherOrder>& master_order_map,
MDP3SecurityID sec,
md::IntPrice price,
api::Side side,
const Trace& trace)
: _master_order_map(&master_order_map),
_sec(sec), _price(price), _side(side), _orders(), _aux_usage(),
_priority(0), _trace(trace) {}
FifoPriceLevelMatcher::FifoPriceLevelMatcher(const FifoPriceLevelMatcher &o) {
*this = o;
}
FifoPriceLevelMatcher::FifoPriceLevelMatcher(FifoPriceLevelMatcher &&o) {
*this = std::move(o);
}
// operator overloads /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FifoPriceLevelMatcher &
FifoPriceLevelMatcher::operator=(const FifoPriceLevelMatcher &o) {
_master_order_map = o._master_order_map;
_sec = o._sec;
_price = o._price;
_side = o._side;
_orders = o._orders;
_aux_usage = o._aux_usage;
_priority = o._priority;
return *this;
}
FifoPriceLevelMatcher &
FifoPriceLevelMatcher::operator=(FifoPriceLevelMatcher &&o) {
_master_order_map = std::move(o._master_order_map);
_sec = std::move(o._sec);
_price = std::move(o._price);
_side = std::move(o._side);
_orders = std::move(o._orders);
_aux_usage = std::move(o._aux_usage);
_priority = std::move(o._priority);
return *this;
}
bool FifoPriceLevelMatcher::operator<(const FifoPriceLevelMatcher &o) const {
bts_assert(_side == o._side);
// bid book is sorted high to low (since highest is the top of the book)
return _side == api::Side::SIDE_SELL ? _price < o._price : o._price < _price;
}
// simple accessors ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
std::tuple<uint32_t, uint32_t> FifoPriceLevelMatcher::n_orders_qty(
bool visible_only) const{
auto [c, q] = std::make_tuple(0, 0);
for (MatcherOrder* o : _orders)
if(in_this_level(o)){
c++;
q += visible_only ? o->working_qty().value() : o->total_qty().value();
}
return std::make_tuple(c, q);
}
bool FifoPriceLevelMatcher::populated() const {
for (auto* o : _orders)
if (in_this_level(o) && o->working_qty().value() > 0)
return true;
return false;
}
void FifoPriceLevelMatcher::copy_values_to(std::vector<MatcherOrder>& out_v) const{
out_v.clear();
for(MatcherOrder* o : _orders)
if(in_this_level(o))
out_v.push_back(*o);
}
// order interactions /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FifoPriceLevelMatcher::on_new_same_side_order(const MDP3Order &new_ord) {
bts_assert(new_ord.price == _price);
bts_assert(new_ord.side == _side);
_add_order(new_ord);
}
std::tuple<MDP3Quantity,MDP3Quantity> FifoPriceLevelMatcher::on_new_opp_order(
MDP3OrderKey opp_ord_key,
MDP3Quantity cross_qty,
bool add_agg_side_to_match_effect,
std::vector<MatchEffect>* res) {
auto rv = _one_pass_cross_order(opp_ord_key, cross_qty,
add_agg_side_to_match_effect, res);
// continue until either the crossing order is consumed
// or the price level is consumed
while (std::get<0>(rv).value() > 0 && std::get<1>(rv).value() > 0)
rv = _one_pass_cross_order(opp_ord_key, std::get<1>(rv),
add_agg_side_to_match_effect, res);
return rv;
}
void FifoPriceLevelMatcher::on_order_update(
const MDP3Order &upd_ord,
MatcherOrder* ord_ptr_hint) {
// ord_ptr_hint is a hint, if its populated use, else find
bts_assert(upd_ord.side == _side);
bts_assert(upd_ord.price == _price);
if(ord_ptr_hint == nullptr){
auto map_it = _master_order_map->find(upd_ord.key);
bts_assert(map_it != _master_order_map->end());
ord_ptr_hint = &map_it->second;
}
MatcherOrder& ord = *ord_ptr_hint;
if (upd_ord.quantity.value() > ord.quantity.value()) {
// remove it from the current location O(N) and add it to
// the end. unlike qty decreases this is a lot more expensive
remove_from_price_level(ord.key);
_orders.push_back(&ord);
// udpate value
ord.quantity = upd_ord.quantity;
} else {
ord.quantity = upd_ord.quantity;
if (ord.ib.has_value() && upd_ord.iceberg_quantity.has_value() && ord.ib.value() != upd_ord.iceberg_quantity.value())
ord.ib = upd_ord.iceberg_quantity;
}
}
void FifoPriceLevelMatcher::on_order_cancel(MatcherOrder& order,
std::vector<MatchEffect>* res){
_logically_delete(order);
OrderUpdate o = {
order.key,
OrderUpdate::Status::CANCELED,
_sec,
_side,
MDP3Quantity(0),
_price,
std::nullopt
};
if(res != nullptr)
res->push_back(o);
}
void FifoPriceLevelMatcher::on_order_remove(MDP3OrderKey k,
std::vector<MatchEffect>* res) {
MatcherOrder *ord_p = _find(k);
bts_assert(ord_p != nullptr);
on_order_cancel(*ord_p,res);
}
void FifoPriceLevelMatcher::remove_from_price_level(MDP3OrderKey k) {
// puts a nullptr in place of where this order was
// (perioric cleanup will physically delete the slot)
auto it = std::find_if(_orders.begin(), _orders.end(),
[&](MatcherOrder* o) {
return in_this_level(o) && o->key == k;
});
bts_assert(it != _orders.end());
bts_assert(*it != nullptr);
*it = nullptr;
}
void FifoPriceLevelMatcher::cleanup() {
_orders.erase(std::remove_if(_orders.begin(), _orders.end(),
[](const MatcherOrder* o) {
return !in_this_level(o);
}),
_orders.end());
}
std::string FifoPriceLevelMatcher::print_mbo(size_t n_orders) const{
std::ostringstream buff;
auto[n_ords,qty] = n_orders_qty();
buff << (side()==api::Side::SIDE_BUY ? "B" : "S") << "," << price();
buff << "," << qty << "," << n_ords << ":";
size_t i=0;
for (MatcherOrder* o : _orders){
if(in_this_level(o)){
if(++i>n_orders)
break;
buff << o->key << "," << o->quantity << ":";
}
}
return buff.str();
}
} // namespace bts::spartan::mdp3