Introduce SyntheticBook class

* Price levels are computed lazily

* Once computed, a price level can be accessed in O(1)

* Unit tests piggy back on rigorous existing unit tests in
  'synthetic_book_computation'

* Not integrated into the matcher, as that is non-trivial
  work, and the March 2021 roll is fast approaching
This commit is contained in:
John Colvin committed 2021-10-25 13:27:12 -04:00
1 parent 91925f9ec6
commit ba53334a7c
27 files changed
+1343 -199

No files matched your search

+28
View File
@@ -19,4 +19,32 @@ inline V *MapUtils::find_value(std::unordered_map<K, V> &umap, K key) {
return &(it->second);
}
template <class K, class V>
inline const V &MapUtils::assert_find_value(const std::unordered_map<K, V> &umap, K key) {
auto it = umap.find(key);
bts_assert(it != umap.end());
return it->second;
}
template <class K, class V>
inline V &MapUtils::assert_find_value(std::unordered_map<K, V> &umap, K key) {
auto it = umap.find(key);
bts_assert(it != umap.end());
return it->second;
}
template <class K, class V>
inline const V &MapUtils::assert_find_value(const boost::container::flat_map<K, V> &umap, K key) {
auto it = umap.find(key);
bts_assert(it != umap.end());
return it->second;
}
template <class K, class V>
inline V &MapUtils::assert_find_value(boost::container::flat_map<K, V> &umap, K key) {
auto it = umap.find(key);
bts_assert(it != umap.end());
return it->second;
}
} // namespace bts
+13
View File
@@ -1,4 +1,5 @@
#pragma once
#include <boost/container/flat_map.hpp>
#include <unordered_map>
namespace bts {
@@ -9,6 +10,18 @@ struct MapUtils {
template <class K, class V>
static V *find_value(std::unordered_map<K, V> &, K);
template <class K, class V>
static const V &assert_find_value(const std::unordered_map<K, V> &, K);
template <class K, class V>
static V &assert_find_value(std::unordered_map<K, V> &, K);
template <class K, class V>
static const V &assert_find_value(const boost::container::flat_map<K, V> &, K);
template <class K, class V>
static V &assert_find_value(boost::container::flat_map<K, V> &, K);
};
} // namespace bts
@@ -1,11 +1,11 @@
#include "SniperModel.h"
#include "domain/book/SyntheticBook.h"
#include "back_testing/sim/ISim.h"
#include "back_testing/sim/PandL.h"
#include "back_testing/sim/sim_common.h"
#include "domain/SecurityDefinition.h"
#include "domain/polygons/polygon_utils.h"
#include "domain/book/book_utils.h"
#include "back_testing/common/mdp3_utils.h"
#include <boost/algorithm/string.hpp>
@@ -341,21 +341,17 @@ void SniperModel::eval(std::vector<Target *> const &targets) {
}
bool SniperModel::within_safety_margin(Target const &t) const {
BookSide synth_book;
using LegInfo = std::tuple<Quantity, Price, BookSide>;
std::vector<LegInfo> leg_mkts;
SyntheticBook synth_book;
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);
synth_book.add_leg(LegDefinition {
leg.sec_id,
other_side(side_from_ratio(leg.ratio)),
Quantity(leg.ratio)
}, &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;
@@ -1,5 +1,7 @@
#include "SyntheticBookRecorder.h"
#include "domain/book/MBPUpdate.h"
#include "domain/book/book_utils.h"
#include "lib/utils/MapUtils.h"
#include "utils/sql/sql_utils.h"
#include <range/v3/view.hpp>
#include <set>
@@ -7,47 +9,30 @@
namespace bts::spartan::mdp3 {
using _LegDef = std::tuple<SecurityID, Quantity>;
using SyntheticDefinitionMap =
std::unordered_map<SecurityID, std::vector<_LegDef>>;
using ReverseLegMap =
std::unordered_map<SecurityID, std::unordered_set<SecurityID>>;
using BookMap = std::
unordered_map<SecurityID, std::tuple<size_t, SmallBook, SmallBook>>;
using SyntheticDefinitionMap = std::unordered_map<SecurityID, LegVec>;
using EventUpdate = std::unordered_map<SecurityID, SyntheticMBPUpdate>;
using SyntheticBookHistory = std::map<EventID, EventUpdate>;
using ReverseLegMap = std::unordered_map<SecurityID, std::unordered_set<SecurityID>>;
using BookMap = std::unordered_map<SecurityID, std::tuple<size_t, Book>>;
// leg sec id, event id (last change), leg qty, leg price mult, bids, asks
using LegBookVec = std::vector<std::tuple<
size_t,
SecurityID,
Quantity,
Price,
SmallBook,
SmallBook>>;
using LegBookVec =
std::vector<std::tuple<size_t, SecurityID, Quantity, Price, Book>>;
SmallBook to_small_book(const BookSide &bk) {
SmallBook rv;
for (const auto &pl : bk)
rv.emplace_back(pl.price, pl.quantity);
return rv;
}
ReverseLegMap
build_reverse_leg_map(const SyntheticDefinitionMap &synthetic_defs) {
ReverseLegMap build_reverse_leg_map(
const SyntheticDefinitionMap &synthetic_defs) {
ReverseLegMap rlm;
for (const auto &sd_p : synthetic_defs) {
for (auto leg_tup : sd_p.second) {
rlm.emplace(std::get<0>(leg_tup), std::unordered_set<SecurityID>())
for (auto leg_def : sd_p.second) {
rlm.emplace(leg_def.security_id, std::unordered_set<SecurityID>())
.first->second.insert(sd_p.first);
}
}
return rlm;
}
const std::vector<_LegDef> &
get_legs(SecurityID synth_id, const SyntheticDefinitionMap &synth_defs) {
const LegVec &get_legs(
SecurityID synth_id, const SyntheticDefinitionMap &synth_defs) {
auto it = synth_defs.find(synth_id);
bts_assert(it != synth_defs.end());
return it->second;
@@ -56,37 +41,21 @@ get_legs(SecurityID synth_id, const SyntheticDefinitionMap &synth_defs) {
// updates book entries for securities in the source sequence,
// then returns the set of affected polygons
template <class Iter>
void update_books(
size_t event_id,
Iter first,
Iter last,
BookMap &books,
const SyntheticDefinitionMap &) {
void update_books(size_t event_id, Iter first, Iter last, BookMap &books) {
while (first != last) {
const SecuritySnapshot *s = *first;
books.insert_or_assign(
s->security_id(),
std::make_tuple(
event_id, to_small_book(s->book_side(Side::Buy)),
to_small_book(s->book_side(Side::Sell))));
s->security_id(), std::make_tuple(event_id, s->book()));
first++;
}
}
const std::unordered_set<SecurityID> *
synthetic_owners(SecurityID leg_id, const ReverseLegMap &reverse_legs) {
auto it = reverse_legs.find(leg_id);
if (it == reverse_legs.end())
return nullptr;
return &it->second;
}
template <class TIter>
std::unordered_set<SecurityID>
synthetic_owners(TIter first, TIter last, const ReverseLegMap &reverse_legs) {
std::unordered_set<SecurityID> synthetic_owners(
TIter first, TIter last, const ReverseLegMap &reverse_legs) {
std::unordered_set<SecurityID> all_owners;
while (first != last) {
const auto *leg_owners = synthetic_owners(*first, reverse_legs);
const auto *leg_owners = MapUtils::find_value(reverse_legs, *first);
if (leg_owners != nullptr) {
for (auto id : *leg_owners)
all_owners.insert(id);
@@ -96,33 +65,15 @@ synthetic_owners(TIter first, TIter last, const ReverseLegMap &reverse_legs) {
return all_owners;
}
// returns tuple of bids, asks
std::tuple<size_t, SmallBook, SmallBook>
get_book_tuple(SecurityID id, const BookMap &books) {
auto bk_it = books.find(id);
if (bk_it == books.end())
return {0, SmallBook(), SmallBook()};
return bk_it->second;
}
LegBookVec
get_leg_books(const std::vector<_LegDef> &leg_defs, const BookMap &books) {
LegBookVec rv;
for (auto [lsid, lqty] : leg_defs) {
auto [eid, bids, asks] = get_book_tuple(lsid, books);
rv.emplace_back(eid, lsid, lqty, Price{}, bids, asks);
}
return rv;
}
SyntheticMBPUpdate::SyntheticMBPUpdate() {}
SyntheticMBPUpdate::SyntheticMBPUpdate(
SecurityID synthetic_id,
std::map<SecurityID, size_t> leg_book_eids,
SmallBook bids,
SmallBook asks)
: synthetic_id(synthetic_id), leg_book_eids(leg_book_eids), bids(bids),
asks(asks) {}
SyntheticBook bids,
SyntheticBook asks)
: synthetic_id(synthetic_id), leg_book_eids(leg_book_eids),
bids(std::move(bids)), asks(std::move(asks)) {}
struct SyntheticBookRecorder::PImpl {
PImpl(SyntheticDefinitionMap synthetic_defs)
@@ -137,14 +88,21 @@ struct SyntheticBookRecorder::PImpl {
const BookMap &books() const { return _books; }
BookMap &mbooks() { return _books; }
const ReverseLegMap &reverse_legs() const { return _reverse_legs; }
const std::map<size_t, std::vector<SyntheticMBPUpdate>> &
const std::map<size_t, std::unordered_map<SecurityID, SyntheticMBPUpdate>> &
synthetic_book_history() const {
return _synthetic_book_history;
}
std::map<size_t, std::vector<SyntheticMBPUpdate>> &
std::map<size_t, std::unordered_map<SecurityID, SyntheticMBPUpdate>> &
msynthetic_book_history() {
return _synthetic_book_history;
}
const std::unordered_map<SecurityID, Sided<SyntheticBook>> &
synthetic_books() const {
return _synthetic_books;
}
std::unordered_map<SecurityID, Sided<SyntheticBook>> &synthetic_books() {
return _synthetic_books;
}
private:
SyntheticDefinitionMap _synthetic_defs;
@@ -154,7 +112,9 @@ struct SyntheticBookRecorder::PImpl {
// so they can be referenced to build the complete synthetic book
// whenever a particular leg's book changes for any synthetic
BookMap _books;
std::map<size_t, std::vector<SyntheticMBPUpdate>> _synthetic_book_history;
std::map<size_t, std::unordered_map<SecurityID, SyntheticMBPUpdate>>
_synthetic_book_history;
std::unordered_map<SecurityID, Sided<SyntheticBook>> _synthetic_books;
};
SyntheticBookRecorder::SyntheticBookRecorder(
@@ -171,60 +131,60 @@ void on_securities_changed(
const SyntheticDefinitionMap &synth_defs,
const ReverseLegMap &reverse_legs,
BookMap &books,
std::map<size_t, std::vector<SyntheticMBPUpdate>> &synth_book_history) {
update_books(event_id, first, last, books, synth_defs);
// Why won't this compile?!
// auto affected_sec_ids =
// ranges::views::transform(first, last, [](const SecuritySnapshot* s) {
// return s->security_id(); });
// oh well, just map the sec ids to a vector for now.
std::vector<SecurityID> affected_sec_ids;
std::unordered_map<SecurityID, Sided<SyntheticBook>> &synth_books,
SyntheticBookHistory &synth_book_history) {
update_books(event_id, first, last, books);
std::map<SecurityID, EventID> leg_book_eid_map;
auto &event_upd =
synth_book_history.emplace(event_id, EventUpdate()).first->second;
// using EventUpdate = std::unordered_map<SecurityID, SyntheticMBPUpdate>;
while (first != last) {
affected_sec_ids.emplace_back((*first)->security_id());
auto sec_id = (*first)->security_id();
auto *affected_synths = MapUtils::find_value(reverse_legs, sec_id);
if (affected_synths == nullptr)
continue;
const auto &bk = (*first)->book();
for (auto synth_id : *affected_synths) {
Sided<SyntheticBook> &sb =
MapUtils::assert_find_value(synth_books, synth_id);
// update bids
auto bid_upd = MBPUpdate::deduce(
Side::Buy, sb.bid.find_leg(sec_id).book(), bk[Side::Buy]);
sb.bid.on_update(sec_id, bid_upd);
// update asks
auto ask_upd = MBPUpdate::deduce(
Side::Sell, sb.ask.find_leg(sec_id).book(), bk[Side::Sell]);
sb.ask.on_update(sec_id, ask_upd);
event_upd[synth_id].leg_book_eids[sec_id] = event_id;
}
first++;
}
auto affected_synth_ids = synthetic_owners(
affected_sec_ids.begin(), affected_sec_ids.end(), reverse_legs);
auto &event_bks =
synth_book_history.emplace(event_id, std::vector<SyntheticMBPUpdate>())
.first->second;
for (auto id : affected_synth_ids) {
const auto &legs = get_legs(id, synth_defs);
auto leg_books = get_leg_books(legs, books);
SmallBook bids, asks;
std::vector<std::tuple<Quantity, Price, SmallBook, SmallBook>>
leg_books_no_eid;
std::map<SecurityID, size_t> leg_book_eid_map;
for (auto [eid, lsid, lqty, lprice, lbids, lasks] : leg_books) {
// seems like there should be a clever way to remove 1 element from a
// tuple. oh well, for now, this will have to do (drop element 0: event
// id).
leg_books_no_eid.emplace_back(lqty, lprice, lbids, lasks);
leg_book_eid_map.emplace(lsid, eid);
for (auto &[synth_id, synth_upd] : event_upd) {
const auto &legs = MapUtils::assert_find_value(synth_defs, synth_id);
for (auto &l : legs) {
auto it = synth_upd.leg_book_eids.find(l.security_id);
if (it == synth_upd.leg_book_eids.end())
it->second = std::get<0>(books[l.security_id]);
}
book_utils::compute_synthetic_books(
bids, asks, leg_books_no_eid, BookSide::max_depth());
// todo: replace 2nd 'id' param with the responsible leg's id
// (first, need to decide how to handle events where more than one
// leg is responsible for the synth mbp update)
event_bks.emplace_back(id, leg_book_eid_map, bids, asks);
}
}
void SyntheticBookRecorder::on_recovery_complete(const InitialSnapshot &snap) {
on_securities_changed(
0, snap.begin(), snap.end(), _me->synthetic_defs(), _me->reverse_legs(),
_me->mbooks(), _me->msynthetic_book_history());
_me->mbooks(), _me->synthetic_books(), _me->msynthetic_book_history());
}
void SyntheticBookRecorder::on_event_end(const FeedEvent &ev) {
on_securities_changed(
ev.event_id, ev.begin(),
ev.end(), _me->synthetic_defs(), _me->reverse_legs(),
_me->mbooks(), _me->msynthetic_book_history());
ev.event_id, ev.begin(), ev.end(), _me->synthetic_defs(),
_me->reverse_legs(), _me->mbooks(), _me->synthetic_books(),
_me->msynthetic_book_history());
}
const std::map<size_t, std::vector<SyntheticMBPUpdate>> &
const std::map<size_t, std::unordered_map<SecurityID, SyntheticMBPUpdate>> &
SyntheticBookRecorder::result() const {
return _me->synthetic_book_history();
}
} // namespace bts::spartan::mdp3
@@ -1,23 +1,26 @@
#pragma once
#include "back_testing/matcher/FifoMatcherContext.h"
#include "domain/SecuritySnapshot.h"
#include "back_testing/common/mdp3_common.h"
#include "back_testing/feed_observers/FeedObserver.h"
#include "back_testing/common/mdp3_utils.h"
#include "back_testing/feed_observers/FeedObserver.h"
#include "back_testing/feed_observers/IcebergFinder.h"
#include "back_testing/matcher/FifoMatcherContext.h"
#include "domain/LegDefinition.h"
#include "domain/SecuritySnapshot.h"
#include "domain/book/SyntheticBook.h"
#include <functional>
#include <memory>
#include <tuple>
#include <unordered_map>
namespace bts::spartan::mdp3 {
struct SyntheticMBPUpdate {
SyntheticMBPUpdate();
SyntheticMBPUpdate(
SecurityID synthetic_id,
std::map<SecurityID, size_t> leg_book_eids,
SmallBook bids,
SmallBook asks);
SyntheticBook bids,
SyntheticBook asks);
SecurityID synthetic_id;
// Note: a map is used (instead of other containers like
@@ -25,22 +28,21 @@ struct SyntheticMBPUpdate {
// and to reduce the risk of misuse that might accompany using a vector (like
// accidentally adding a duplicate entry for one of the legs)
std::map<SecurityID, size_t> leg_book_eids;
SmallBook bids;
SmallBook asks;
SyntheticBook bids;
SyntheticBook asks;
};
struct SyntheticBookRecorder : FeedObserver {
SyntheticBookRecorder(std::unordered_map<
SecurityID,
std::vector<std::tuple<SecurityID, Quantity>>>
synthetic_def);
SyntheticBookRecorder(std::unordered_map<SecurityID, LegVec> synthetic_def);
~SyntheticBookRecorder();
void on_recovery_complete(InitialSnapshot const &snap) override;
void on_event_end(FeedEvent const &ev) override;
const std::map<size_t, std::vector<SyntheticMBPUpdate>> &result() const;
const std::map<EventID, std::unordered_map<SecurityID, SyntheticMBPUpdate>> &
result() const;
private:
struct PImpl;
std::unique_ptr<PImpl> _me;
};
} // namespace bts::spartan::mdp3
@@ -1,8 +1,9 @@
#include "PolygonBooks.h"
#include "lib/orderman/orderman_utils/Formatter.h"
#include "domain/book/Book.h"
#include "back_testing/feed_observers/SyntheticBookRecorder.h"
#include "back_testing/common/mdp3_utils.h"
#include "back_testing/feed_observers/SyntheticBookRecorder.h"
#include "domain/book/Book.h"
#include "domain/book/SyntheticBook.h"
#include "lib/orderman/orderman_utils/Formatter.h"
#include "utils/FileUtils.h"
#include "utils/sql/adapters/polygon_defs.h"
#include "utils/sql/sql_utils.h"
@@ -25,10 +26,10 @@ struct PolygonBooks::Args {
std::string out_csv;
};
PolygonBooks::PolygonBooks() :
CLI::App(
"Generate a csv file of book updates for polygons", "polygon-books"),
_args(new PolygonBooks::Args()) {
PolygonBooks::PolygonBooks()
: CLI::App(
"Generate a csv file of book updates for polygons", "polygon-books"),
_args(new PolygonBooks::Args()) {
add_option("pcap,--pcap", _args->pcap)->required();
add_option("data-base,--db,--data-base", _args->db)->required();
add_option("security-ids,--security-ids", _args->security_ids)->required();
@@ -53,18 +54,19 @@ PolygonBooks::PolygonBooks() :
INFO(
"generating polygon books for pids: {}",
orderman::Formatter::fmt_values(ids));
mdp3::SyntheticBookRecorder sbr(
spartan::sql::adapters::polygon_defs::read_sql(
_args->db.c_str(), ids));
auto synths = spartan::sql::adapters::polygon_defs::read_sql(_args->db.c_str(), ids);
mdp3::SyntheticBookRecorder sbr(synths);
mdp3::observe_channel(_args->pcap, sbr);
// don't prepend a comma before calling 'append_book' (it does that
// internally)
auto append_book = [](std::ofstream &out,
const mdp3::SmallBook &bk) -> std::ofstream & {
const SyntheticBook &bk) -> std::ofstream & {
uint32_t i = 0;
bts_assert(bk.size() <= 10);
for (; i < bk.size(); i++)
out << "," << bk[i].price << "," << bk[i].quantity.value();
for (auto it = bk.begin();
it != bk.end() && i < mdp3::BookSide::max_depth(); i++) {
out << "," << it->price << "," << it->quantity.value();
it++;
}
while (i++ < mdp3::BookSide::max_depth())
out << ",NaN,0";
return out;
@@ -104,10 +106,11 @@ PolygonBooks::PolygonBooks() :
};
add_bk_cols("bid");
add_bk_cols("ask");
for (const auto &p : sbr.result()) {
for (const auto &upd : p.second) {
for (const auto &[eid, synth_rows] : sbr.result()) {
for (const auto &[synth_id, upd] : synth_rows) {
ofs << std::endl;
ofs << p.first << "," << upd.synthetic_id.value();
ofs << eid << "," << synth_id;
append_leg_book_eids(ofs, upd);
append_book(ofs, upd.bids);
append_book(ofs, upd.asks);
@@ -0,0 +1,33 @@
#include "SidePrice.h"
namespace bts::spartan {
#define BINARY_OP(op) \
inline SidePrice operator op( \
const SidePrice &lhs, const SidePrice &rhs) { \
return SidePrice(lhs.value() op rhs.value()); \
}
BINARY_OP(+)
BINARY_OP(-)
BINARY_OP(/)
BINARY_OP(*)
#undef BINARY_OP
#define BINARY_REF_OP(op) \
inline SidePrice &operator op( \
SidePrice &lhs, const SidePrice &rhs) { \
lhs.value() op rhs.value(); \
return lhs; \
}
BINARY_REF_OP(+=)
BINARY_REF_OP(-=)
BINARY_REF_OP(/=)
BINARY_REF_OP(*=)
#undef BINARY_REF_OP
inline SidePrice operator-(const SidePrice &qty) {
return SidePrice(mdp3::Price(-qty.value()));
}
} // namespace bts::spartan
@@ -0,0 +1,34 @@
#include "SidePrice.h"
namespace bts::spartan {
SidePrice::SidePrice() : _value() {}
SidePrice::SidePrice(mdp3::Price value) : _value(value) {}
SidePrice::SidePrice(mdp3::Price value, Side side)
: _value(side == Side::Buy ? value : -value) {}
constexpr Side SidePrice::side() const {
return _value < 0 ? Side::Sell : Side::Buy;
}
mdp3::Price SidePrice::norm() const { return _value.abs(); }
mdp3::Price SidePrice::value() const { return _value; }
mdp3::Price &SidePrice::value() { return _value; }
template <>
mdp3::Price SidePrice::in_terms_of<Side::Buy>(mdp3::Price value) {
return value;
}
template <>
mdp3::Price SidePrice::in_terms_of<Side::Sell>(mdp3::Price value) {
return -value;
}
template <>
mdp3::Price SidePrice::in_terms_of<Side::Buy>(mdp3::Price);
template <>
mdp3::Price SidePrice::in_terms_of<Side::Sell>(mdp3::Price);
} // namespace bts::spartan
@@ -0,0 +1,53 @@
#pragma once
#include "Price.h"
#include "Side.h"
namespace bts::spartan {
/**
* A numeric abstraction that treats side as a function of numeric sign
*/
struct SidePrice {
SidePrice();
SidePrice(mdp3::Price);
SidePrice(mdp3::Price, Side);
/**
* Infers the side from the sign of the underlying value
*
* @returns Sell if the value is negative, otherwise Buy
*/
constexpr Side side() const;
/**
* Gets the [signed] value
*/
mdp3::Price value() const;
/**
* Gets the [signed] value
*/
mdp3::Price &value();
/**
* Gets the [unsigned] norm of the value
*/
mdp3::Price norm() const;
template<Side S>
static mdp3::Price in_terms_of(mdp3::Price);
private:
mdp3::Price _value;
};
SidePrice operator+(const SidePrice &, const SidePrice &);
SidePrice operator-(const SidePrice &, const SidePrice &);
SidePrice operator*(const SidePrice &, const SidePrice &);
SidePrice operator/(const SidePrice &, const SidePrice &);
SidePrice operator-(const SidePrice &);
SidePrice& operator+=(SidePrice &, const SidePrice &);
SidePrice& operator-=(SidePrice &, const SidePrice &);
SidePrice& operator*=(SidePrice &, const SidePrice &);
SidePrice& operator/=(SidePrice &, const SidePrice &);
} // namespace bts::spartan
#include "SidePrice.cc"
@@ -0,0 +1,49 @@
#include "MBPUpdate.h"
#include "domain/order/Order.h"
namespace bts::spartan {
MBPUpdate MBPUpdate::deduce(
Side side, const mdp3::BookSide &old_book, const mdp3::BookSide &new_book) {
return MBPUpdate{side, &old_book, &new_book};
}
MBPUpdate MBPUpdate::deduce(
Side side,
mdp3::Price old_price,
mdp3::Quantity old_quantity,
mdp3::Price new_price,
mdp3::Quantity new_quantity) {
MBPUpdate upd;
if (old_price == new_price) {
auto &pl_upd = upd.level_updates.emplace_back();
pl_upd.price = new_price;
pl_upd.qty_delta = new_quantity - old_quantity;
} else if (old_price.is_better(side, new_price)) {
// The price-level updates are sorted by price (best price first).
auto &old_price_upd = upd.level_updates.emplace_back();
old_price_upd.price = old_price;
old_price_upd.qty_delta = -old_quantity;
auto &new_price_upd = upd.level_updates.emplace_back();
new_price_upd.price = new_price;
new_price_upd.qty_delta = new_quantity;
} else {
// The price-level updates are sorted by price (best price first).
auto &new_price_upd = upd.level_updates.emplace_back();
new_price_upd.price = new_price;
new_price_upd.qty_delta = new_quantity;
auto &old_price_upd = upd.level_updates.emplace_back();
old_price_upd.price = old_price;
old_price_upd.qty_delta = -old_quantity;
}
return upd;
}
MBPUpdate MBPUpdate::deduce(
const mdp3::Order &old_order, const mdp3::Order &new_order) {
return deduce(
new_order.side, old_order.price, old_order.quantity, new_order.price,
new_order.quantity);
}
} // namespace bts::spartan
@@ -0,0 +1,35 @@
#pragma once
#include "Book.h"
#include "PriceLevelUpdate.h"
#include "domain/Side.h"
#include <vector>
namespace bts::spartan {
namespace mdp3 {
struct Order;
}
struct MBPUpdate {
Side side;
const mdp3::BookSide *old_book = nullptr;
const mdp3::BookSide *new_book = nullptr;
std::vector<PriceLevelUpdate> level_updates{};
static MBPUpdate deduce(
Side side,
const mdp3::BookSide &old_book,
const mdp3::BookSide &new_book);
static MBPUpdate deduce(
Side side,
mdp3::Price old_price,
mdp3::Quantity old_quantity,
mdp3::Price new_price,
mdp3::Quantity new_quantity);
static MBPUpdate deduce(
const mdp3::Order &old_order, const mdp3::Order &new_order);
};
} // namespace bts::spartan
@@ -0,0 +1,12 @@
#pragma once
#include "../Price.h"
#include "../Quantity.h"
namespace bts::spartan {
struct PriceLevelUpdate {
mdp3::Price price;
mdp3::Quantity qty_delta;
};
} // namespace bts::spartan
@@ -0,0 +1,9 @@
#include "SyntheticBook.h"
namespace bts::spartan {
constexpr std::size_t SyntheticBook::size() const noexcept {
return SyntheticBook_Iterator::NUM_LEVELS;
}
} // namespace bts::spartan
@@ -0,0 +1,111 @@
#include "SyntheticBook.h"
#include "BookMark.h"
#include "MBPUpdate.h"
#include "SyntheticBook_LegCursor.h"
#include "book_utils.h"
#include "lib/utils/MapUtils.h"
#include <boost/container/flat_map.hpp>
#include <boost/container/small_vector.hpp>
#include <limits>
namespace bts::spartan {
using _Iterators = boost::container::small_vector<SyntheticBook_Iterator, 2>;
struct SyntheticBook::PImpl {
SyntheticBook_LegMap legs{};
// All iterators (reguardless of when they are created) share the same
// 'known_levels' instance. Each level need only be computed once (lazily,
// by whichever iterator advances to a particular level first), then it is
// added to 'known_levels' where all other iterators can access it, thus
// avoiding duplicate work.
//
// Another benefit of using a shared 'known_levels'
// cache is that the SyntheticBook (this class's owner) can invalidate the
// known_levels for every iterator at once. If the mbp changes, simply clear
// all price levels w/ a price that is equal to or worse than the one that
// changed. For example, there is no need to recompute the top of the book
// because a price level behind it changed.
SyntheticBookLevelsPtr known_levels =
std::make_shared<SyntheticBookLevels>();
};
SyntheticBook::SyntheticBook() : _me(new SyntheticBook::PImpl()) {}
SyntheticBook::SyntheticBook(const SyntheticBook &other)
: _me(new SyntheticBook::PImpl{
other._me->legs, SyntheticBookLevelsPtr(new SyntheticBookLevels(
*other._me->known_levels))}) {}
SyntheticBook::SyntheticBook(SyntheticBook &&other)
: _me(new SyntheticBook::PImpl()) {
_me->legs = std::move(other._me->legs);
_me->known_levels = std::move(other._me->known_levels);
}
SyntheticBook::~SyntheticBook() {}
SyntheticBook_Iterator SyntheticBook::begin() const {
SyntheticBook_LegCursors cursors;
for (const auto &p : _me->legs)
cursors.emplace_back(&p.second);
SyntheticBook_Iterator iter(cursors, _me->known_levels);
return iter;
}
const SyntheticBook_LegMap &SyntheticBook::legs() const { return _me->legs; }
const SyntheticBook_Leg &SyntheticBook::find_leg(SecurityID sec_id) const {
return MapUtils::assert_find_value(_me->legs, sec_id);
}
SyntheticBook_Iterator SyntheticBook::end() const {
return SyntheticBook_Iterator::end();
}
SyntheticBook_Iterator SyntheticBook::quantity_end() {
// todo
return end();
}
mdp3::Quantity SyntheticBook::volume() const {
mdp3::Quantity vol(0);
for (auto it = begin(); it != end() && it->quantity != 0; it++)
vol += it->quantity;
return vol;
}
mdp3::BookLevel &SyntheticBook::operator[](std::size_t index) {
auto iter = begin();
return *(iter + index);
}
void SyntheticBook::add_leg(LegDefinition leg, const mdp3::BookSide *book) {
_me->legs.insert_or_assign(leg.security_id, SyntheticBook_Leg(leg, book));
}
void SyntheticBook::on_update(SecurityID sec, const MBPUpdate &upd) {
for (const auto &lev : upd.level_updates)
on_update(sec, lev);
}
void SyntheticBook::on_update(SecurityID sec, const PriceLevelUpdate &upd) {
if (_me->known_levels->empty())
return;
auto &leg = MapUtils::assert_find_value(_me->legs, sec);
auto leg_side = leg.def().side;
const auto &leg_bk = leg.book();
for (auto it = _me->known_levels->begin(); it != _me->known_levels->end();
it++) {
auto leg_it = it->leg_positions().find(sec);
bts_assert(leg_it != it->leg_positions().end());
const auto &lev = leg_bk[leg_it->second.level()];
if (lev.price.is_better_or_equal(leg_side, upd.price)) {
// invalidate known_levels from this level to the end
_me->known_levels->erase(it, _me->known_levels->end());
break;
}
}
}
} // namespace bts::spartan
@@ -0,0 +1,71 @@
#pragma once
#include "../LegDefinition.h"
#include "../Quantity.h"
#include "../SecurityID.h"
#include "Book.h"
#include "SyntheticBook_Iterator.h"
#include "SyntheticBook_Leg.h"
#include "SyntheticBook_LegCursor.h"
#include "book_utils.h"
#include <memory>
#include <vector>
namespace bts::spartan {
struct MBPUpdate;
struct PriceLevelUpdate;
class SyntheticBook {
public:
SyntheticBook();
SyntheticBook(const SyntheticBook &);
SyntheticBook(SyntheticBook &&);
~SyntheticBook();
/**
* Gets an iterator pointing to the first index/price level
*/
SyntheticBook_Iterator begin() const;
/**
* Gets an iterator pointing to the last index. Note that this is not
* necessarily the first price level with zero quantity.
*/
SyntheticBook_Iterator end() const;
/**
* Gets an iterator pointing to the first price level with zero quantity.
* This will force all price levels to be computed (such compuatations are
* otherwise lazy).
*/
SyntheticBook_Iterator quantity_end();
/**
* Adds a leg to the synthetic book
*/
void add_leg(LegDefinition, const mdp3::BookSide *);
/**
* Gets the leg map (keyed by security id)
*/
const SyntheticBook_LegMap &legs() const;
const SyntheticBook_Leg &find_leg(SecurityID) const;
/**
* Invalidates synthetic price levels that would be impacted by particular
* mbp changes
*/
void on_update(SecurityID, const MBPUpdate &upd);
void on_update(SecurityID, const PriceLevelUpdate &upd);
/**
* Gets the total volume in the synthetic book
*/
mdp3::Quantity volume() const;
constexpr std::size_t size() const noexcept;
mdp3::BookLevel &operator[](std::size_t);
private:
struct PImpl;
std::unique_ptr<PImpl> _me;
};
} // namespace bts::spartan
#include "SyntheticBook.cc"
@@ -0,0 +1,50 @@
#include "SyntheticBookLevel.h"
#include "../Price.h"
#include "../Quantity.h"
#include "BookLevel.h"
#include "BookMark.h"
namespace bts::spartan {
struct SyntheticBookLevel::PImpl {
mdp3::BookLevel level{mdp3::Price::nan()};
SyntheticBookLevel::LegPositions leg_positions{};
};
SyntheticBookLevel::SyntheticBookLevel()
: _me(new SyntheticBookLevel::PImpl()) {}
SyntheticBookLevel::SyntheticBookLevel(SyntheticBookLevel &&other) noexcept
: _me(std::move(other._me)) {}
SyntheticBookLevel::SyntheticBookLevel(const SyntheticBookLevel &other)
: _me(new SyntheticBookLevel::PImpl{
other._me->level, other._me->leg_positions}) {}
SyntheticBookLevel::~SyntheticBookLevel() {}
const mdp3::BookLevel &SyntheticBookLevel::level() const { return _me->level; }
mdp3::BookLevel &SyntheticBookLevel::level() { return _me->level; }
const SyntheticBookLevel::LegPositions &
SyntheticBookLevel::leg_positions() const {
return _me->leg_positions;
}
SyntheticBookLevel::LegPositions &SyntheticBookLevel::leg_positions() {
return _me->leg_positions;
}
SyntheticBookLevel& SyntheticBookLevel::operator=(const SyntheticBookLevel &other) {
_me->level = other._me->level;
_me->leg_positions = other._me->leg_positions;
return *this;
}
SyntheticBookLevel& SyntheticBookLevel::operator=(SyntheticBookLevel &&other) {
_me = std::move(other._me);
return *this;
}
} // namespace bts::spartan
@@ -0,0 +1,42 @@
#pragma once
#include "../SecurityID.h"
#include <boost/container/flat_map.hpp>
#include <boost/container/small_vector.hpp>
#include <memory>
#include <vector>
namespace bts::spartan {
namespace mdp3 {
class BookLevel;
}
class BookMark;
class SyntheticBookLevel {
public:
SyntheticBookLevel();
SyntheticBookLevel(SyntheticBookLevel &&) noexcept;
SyntheticBookLevel(const SyntheticBookLevel &);
~SyntheticBookLevel();
using LegPositions = boost::container::flat_map<SecurityID, BookMark>;
const mdp3::BookLevel &level() const;
mdp3::BookLevel &level();
const LegPositions &leg_positions() const;
LegPositions &leg_positions();
SyntheticBookLevel &operator=(const SyntheticBookLevel &);
SyntheticBookLevel &operator=(SyntheticBookLevel &&);
private:
struct PImpl;
std::unique_ptr<PImpl> _me;
};
using SyntheticBookLevels = std::vector<SyntheticBookLevel>;
using SyntheticBookLevelsPtr = std::shared_ptr<SyntheticBookLevels>;
} // namespace bts::spartan
@@ -0,0 +1,211 @@
#include "SyntheticBook_Iterator.h"
#include "../SidePrice.h"
#include "Book.h"
#include "BookLevel.h"
#include "BookMark.h"
#include "book_utils.h"
#include <boost/container/small_vector.hpp>
#include <limits>
namespace bts::spartan {
using namespace bts::spartan::mdp3;
using _Cursors = boost::container::small_vector<BookMark, 2>;
// struct _PriceLevel {
// _PriceLevel() : synth_level({mdp3::Price::nan()}), leg_cursors() {}
// _PriceLevel(mdp3::BookLevel synth_level, _Cursors leg_cursors)
// : synth_level(
// {synth_level.price, synth_level.quantity,
// synth_level.n_orders}),
// leg_cursors(leg_cursors) {}
// _PriceLevel(const _PriceLevel &other)
// : synth_level(
// {other.synth_level.price, other.synth_level.quantity,
// other.synth_level.n_orders}),
// leg_cursors(other.leg_cursors) {}
// mdp3::BookLevel synth_level;
// _Cursors leg_cursors;
// };
static mdp3::Quantity get_limiting_qty(SyntheticBook_LegCursors legs) {
if (legs.empty())
return Quantity(0);
mdp3::Quantity limiting_qty(std::numeric_limits<std::int32_t>::max());
for (auto &l : legs) {
auto lev = l.curr_level();
if (lev.quantity < limiting_qty)
limiting_qty = lev.quantity;
}
return limiting_qty;
}
static SyntheticBookLevel advance(SyntheticBook_LegCursors &legs) {
SyntheticBookLevel curr_level;
if (legs.empty())
return curr_level;
mdp3::Quantity limiting_qty = get_limiting_qty(legs);
curr_level.level().quantity = limiting_qty;
if (limiting_qty == 0) {
curr_level.level().price = mdp3::Price::nan();
} else {
curr_level.level().price = mdp3::Price::zero();
// The current price level is the sum of each leg's unit cost (i.e.,
// marginal cost * leg qty for each leg).
for (auto &l : legs) {
curr_level.level().price +=
SidePrice(l.compute_next(Quantity(1), true), l.leg()->def().side)
.value();
if (curr_level.level().quantity > 1)
l.compute_next(curr_level.level().quantity - 1, true);
}
}
return curr_level;
}
struct SyntheticBook_Iterator::PImpl {
// Allow this many increments before forcing the levels to be calculated
// (levels are otherwise computed lazily, when the deref op is called)
const std::uint16_t level_buffer_size = 10;
PImpl(SyntheticBook_LegCursors legs, SyntheticBookLevelsPtr known_levels)
: legs(legs), known_levels(known_levels) {}
PImpl(const PImpl &other)
: legs(other.legs), known_levels(other.known_levels) {}
mdp3::BookLevel &curr_level() {
ensure_curr_level();
return (known_levels->begin() + cursor)->level();
}
bool is_over_extended() const {
return cursor >= (legs.size() + level_buffer_size);
}
void increment_cursor(std::int32_t value) {
cursor += value;
if (is_over_extended())
ensure_curr_level();
}
SyntheticBook_LegCursors legs;
SyntheticBookLevelsPtr known_levels;
std::uint16_t cursor = 0;
private:
void ensure_curr_level() {
while (known_levels->size() <= cursor) {
// auto old_legs = legs;
// known_levels->emplace_back(advance(legs), old_legs);
known_levels->emplace_back(advance(legs));
}
}
};
SyntheticBook_Iterator SyntheticBook_Iterator::end() {
return SyntheticBook_Iterator(
SyntheticBookLevelsPtr(new SyntheticBookLevels()));
}
SyntheticBook_Iterator::SyntheticBook_Iterator(
SyntheticBookLevelsPtr known_levels)
: _me(new SyntheticBook_Iterator::PImpl(
SyntheticBook_LegCursors(), known_levels)) {
_me->cursor = NUM_LEVELS;
}
SyntheticBook_Iterator::SyntheticBook_Iterator(
SyntheticBook_LegCursors legs, SyntheticBookLevelsPtr known_levels)
: _me(new SyntheticBook_Iterator::PImpl(legs, known_levels)) {}
SyntheticBook_Iterator::SyntheticBook_Iterator(
const SyntheticBook_Iterator &other)
: _me(new SyntheticBook_Iterator::PImpl(*other._me)) {}
SyntheticBook_Iterator::~SyntheticBook_Iterator() {}
SyntheticBook_Iterator &SyntheticBook_Iterator::operator=(
const SyntheticBook_Iterator &other) {
_me->cursor = other._me->cursor;
_me->known_levels = other._me->known_levels;
return *this;
}
SyntheticBook_Iterator::const_reference
SyntheticBook_Iterator::operator*() const {
return _me->curr_level();
}
SyntheticBook_Iterator::reference SyntheticBook_Iterator::operator*() {
return _me->curr_level();
}
SyntheticBook_Iterator::const_pointer
SyntheticBook_Iterator::operator->() const {
return &_me->curr_level();
}
SyntheticBook_Iterator::pointer SyntheticBook_Iterator::operator->() {
return &_me->curr_level();
}
SyntheticBook_Iterator &SyntheticBook_Iterator::operator++() {
_me->increment_cursor(1);
return *this;
}
SyntheticBook_Iterator SyntheticBook_Iterator::operator++(int) {
SyntheticBook_Iterator before(*this);
++(*this);
return before;
}
SyntheticBook_Iterator &SyntheticBook_Iterator::operator+=(int value) {
_me->increment_cursor(value);
return *this;
}
SyntheticBook_Iterator SyntheticBook_Iterator::operator+(int value) {
SyntheticBook_Iterator result(*this);
result._me->increment_cursor(value);
return result;
}
SyntheticBook_Iterator &SyntheticBook_Iterator::operator--() {
_me->increment_cursor(-1);
return *this;
}
SyntheticBook_Iterator SyntheticBook_Iterator::operator--(int) {
SyntheticBook_Iterator before(*this);
--(*this);
return before;
}
SyntheticBook_Iterator &SyntheticBook_Iterator::operator-=(int value) {
_me->increment_cursor(-value);
return *this;
}
SyntheticBook_Iterator SyntheticBook_Iterator::operator-(int value) {
SyntheticBook_Iterator result(*this);
result._me->increment_cursor(-value);
return result;
}
bool SyntheticBook_Iterator::operator==(
const SyntheticBook_Iterator &other) const {
return _me->cursor == other._me->cursor;
}
bool SyntheticBook_Iterator::operator!=(
const SyntheticBook_Iterator &other) const {
return !(*this == other);
}
} // namespace bts::spartan
@@ -0,0 +1,68 @@
#pragma once
#include "../LegDefinition.h"
#include "Book.h"
#include "SyntheticBook_Leg.h"
#include "SyntheticBook_LegCursor.h"
#include "SyntheticBookLevel.h"
#include "book_utils.h"
#include <vector>
namespace bts::spartan {
struct SyntheticBook_Iterator {
// Unifies the definition of 'end of book.' Even if a book has less than
// NUM_LEVELS levels, the iterator is not at the 'end' until it points to
// the 'NUM_LEVELS' level.
static const std::uint32_t NUM_LEVELS = 5;
using SyntheticBook_Iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = mdp3::BookLevel;
using pointer = value_type *;
using reference = value_type &;
using const_pointer = const value_type *;
using const_reference = const value_type &;
SyntheticBook_Iterator(SyntheticBookLevelsPtr);
SyntheticBook_Iterator(SyntheticBook_LegCursors, SyntheticBookLevelsPtr);
SyntheticBook_Iterator(const SyntheticBook_Iterator &);
~SyntheticBook_Iterator();
static SyntheticBook_Iterator end();
reference operator*();
pointer operator->();
const_reference operator*() const;
const_pointer operator->() const;
// Note: the ++/-- 'suffix' operators copy existing leg cursors to another
// vector in order to return a copy of the iterator before it was
// incremented/decremented. For that reason, the prefix++/-- operators are
// generally favored over their suffix counterparts.
SyntheticBook_Iterator &operator++();
SyntheticBook_Iterator operator++(int);
SyntheticBook_Iterator &operator+=(int);
SyntheticBook_Iterator operator+(int);
SyntheticBook_Iterator &operator--();
SyntheticBook_Iterator operator--(int);
SyntheticBook_Iterator &operator-=(int);
SyntheticBook_Iterator operator-(int);
SyntheticBook_Iterator &operator=(const SyntheticBook_Iterator &);
/**
* Check if two iterators are equal. For simplicity, and performance,
* it is assumed that the iterators have the same legs/books. Two iterators
* are considered equal if they are pointing to the same price level index (i.e., the 1st level, the 2nd level, etc.).
*/
bool operator==(const SyntheticBook_Iterator &) const;
bool operator!=(const SyntheticBook_Iterator &) const;
private:
struct PImpl;
std::unique_ptr<PImpl> _me;
};
} // namespace bts::spartan
@@ -0,0 +1,21 @@
#include "SyntheticBook_Leg.h"
#include "MBPUpdate.h"
namespace bts::spartan {
SyntheticBook_Leg::SyntheticBook_Leg() : _def(), _book(nullptr) {}
SyntheticBook_Leg::SyntheticBook_Leg(
LegDefinition def, const mdp3::BookSide *book)
: _def(def), _book(book) {}
SyntheticBook_Leg::SyntheticBook_Leg(const SyntheticBook_Leg &other)
: _def(other._def), _book(other._book) { }
const LegDefinition &SyntheticBook_Leg::def() const { return _def; }
const mdp3::BookSide &SyntheticBook_Leg::book() const { return *_book; }
void SyntheticBook_Leg::on_update(const MBPUpdate &) {
}
} // namespace bts::spartan
@@ -0,0 +1,33 @@
#pragma once
#include "../LegDefinition.h"
#include "../Price.h"
#include "../Quantity.h"
#include "Book.h"
#include "BookMark.h"
#include <boost/container/flat_map.hpp>
#include <tuple>
#include <vector>
namespace bts::spartan {
struct MBPUpdate;
class SyntheticBook_Leg {
public:
SyntheticBook_Leg();
SyntheticBook_Leg(LegDefinition, const mdp3::BookSide *);
SyntheticBook_Leg(const SyntheticBook_Leg &);
const LegDefinition &def() const;
const mdp3::BookSide &book() const;
void on_update(const MBPUpdate &);
private:
LegDefinition _def;
const mdp3::BookSide *_book;
};
using SyntheticBook_LegMap =
boost::container::flat_map<SecurityID, SyntheticBook_Leg>;
} // namespace bts::spartan
@@ -0,0 +1,157 @@
#include "SyntheticBook_LegCursor.h"
#include "SyntheticBook_Leg.h"
#include "book_utils.h"
namespace bts::spartan {
#define EMPTY_BOOK_LEVEL \
mdp3::BookLevel { mdp3::Price::nan(), mdp3::Quantity(0), 0 }
struct SyntheticBook_LegCursor::PImpl {
const_SyntheticBook_LegPtr leg;
BookMark position;
};
SyntheticBook_LegCursor::SyntheticBook_LegCursor(const_SyntheticBook_LegPtr leg)
: _me(new SyntheticBook_LegCursor::PImpl{leg, BookMark()}) {}
SyntheticBook_LegCursor::SyntheticBook_LegCursor(
const_SyntheticBook_LegPtr leg, BookMark position)
: _me(new SyntheticBook_LegCursor::PImpl{leg, position}) {}
SyntheticBook_LegCursor::SyntheticBook_LegCursor(
const SyntheticBook_LegCursor &other)
: _me(new SyntheticBook_LegCursor::PImpl{
other._me->leg, other._me->position}) {}
SyntheticBook_LegCursor::~SyntheticBook_LegCursor() {}
SyntheticBook_LegCursor &SyntheticBook_LegCursor::operator=(
const SyntheticBook_LegCursor &other) {
_me->leg = other._me->leg;
_me->position = other._me->position;
return *this;
}
const_SyntheticBook_LegPtr SyntheticBook_LegCursor::leg() const {
return _me->leg;
}
mdp3::BookLevel SyntheticBook_LegCursor::curr_level_marginal() const {
if (_me->position.level() >= _me->leg->book().size())
return EMPTY_BOOK_LEVEL;
auto mlev_it = _me->leg->book().begin() + _me->position.level();
if (_me->position.offset() < mlev_it->quantity) {
// Set the 'num_orders' field to zero because it is invalidated by any
// non-zero qty offset.
return mdp3::BookLevel{
mlev_it->price, mlev_it->quantity - _me->position.offset(), 0};
}
return EMPTY_BOOK_LEVEL;
}
mdp3::BookLevel SyntheticBook_LegCursor::curr_level() const {
if (_me->position.level() >= _me->leg->book().size())
return EMPTY_BOOK_LEVEL;
auto auq = abs(unit_qty());
auto curr_lev_marg = curr_level_marginal();
if (curr_lev_marg.quantity >= auq)
return {
curr_lev_marg.price * unit_qty().value(),
curr_lev_marg.quantity / auq};
auto cost = curr_lev_marg.price * curr_lev_marg.quantity.value();
auq -= curr_lev_marg.quantity;
for (auto it = _me->leg->book().begin() + _me->position.level() + 1;
it != _me->leg->book().end(); it++) {
if (it->quantity >= auq)
return {
(cost + it->price * auq.value()) *
(unit_qty() / abs(unit_qty())).value(),
mdp3::Quantity(1)};
cost += it->price * it->quantity.value();
auq -= it->quantity;
}
return EMPTY_BOOK_LEVEL;
}
const BookMark &SyntheticBook_LegCursor::position() const {
return _me->position;
}
mdp3::Quantity SyntheticBook_LegCursor::unit_qty() const {
auto r = _me->leg->def().ratio;
return _me->leg->def().side == Side::Sell ? -r : r;
}
mdp3::Price SyntheticBook_LegCursor::compute_prev(
mdp3::Quantity qty, bool move_position) {
return compute_prev_marginal(qty * abs(unit_qty()), move_position);
}
mdp3::Price SyntheticBook_LegCursor::compute_prev_marginal(
mdp3::Quantity qty, bool move_position) {
if (qty == 0)
return mdp3::Price::zero();
if ((_me->position.level() == 0 && _me->position.offset() == 0) || qty < 0) {
return mdp3::Price::nan();
}
auto lev_it = _me->leg->book().begin() + _me->position.level();
auto orig_position = position();
if (_me->position.offset() < qty) {
auto cost = lev_it->price * _me->position.offset().value();
qty -= _me->position.offset();
_me->position.offset() = lev_it->quantity;
cost += compute_prev_marginal(qty, move_position);
if (!move_position)
_me->position = orig_position;
else if (cost.is_nan()) {
// Reset position to the beginning (less than the specified qty is
// before the position, so the 'roll position' transaction failed).
_me->position.offset().value() = 0;
_me->position.level() = 0;
}
return cost;
} else {
if (move_position)
_me->position.offset() -= qty;
return lev_it->price * qty.value();
}
}
mdp3::Price SyntheticBook_LegCursor::compute_next(
mdp3::Quantity qty, bool move_position) {
return compute_next_marginal(qty * abs(unit_qty()), move_position);
}
mdp3::Price SyntheticBook_LegCursor::compute_next_marginal(
mdp3::Quantity qty, bool move_position) {
if (qty == 0)
return mdp3::Price::zero();
if (_me->position.level() >= _me->leg->book().size() || qty < 0)
return mdp3::Price::nan();
auto curr_lev_marg = curr_level_marginal();
if (curr_lev_marg.quantity <= qty) {
auto cost = curr_lev_marg.price * curr_lev_marg.quantity.value();
qty -= curr_lev_marg.quantity;
auto orig_position = position();
_me->position.level()++;
_me->position.offset().value() = 0;
cost += compute_next_marginal(qty, move_position);
if (!move_position)
_me->position = orig_position;
return cost;
} else {
_me->position.offset() += qty;
return curr_lev_marg.price * qty.value();
}
}
mdp3::Price SyntheticBook_LegCursor::remove(mdp3::Quantity qty) {
return compute_next_marginal(qty, true);
}
mdp3::Price SyntheticBook_LegCursor::remove_units(mdp3::Quantity qty) {
return remove(qty * abs(unit_qty()));
}
} // namespace bts::spartan
@@ -0,0 +1,96 @@
#pragma once
#include "Book.h"
#include "domain/Price.h"
#include "domain/Quantity.h"
#include <boost/container/small_vector.hpp>
#include <memory>
#include <tuple>
#include <vector>
namespace bts::spartan {
class SyntheticBook_Leg;
using SyntheticBook_LegPtr = SyntheticBook_Leg *;
using const_SyntheticBook_LegPtr = const SyntheticBook_Leg *;
class BookMark;
/**
* A cursor to walk through price levels at a particular unit quantity (i.e.,
* a leg size in a synthetic). As the unit quantity may obfuscate price
* level boundaries (e.g., unit quantity 2, and top two price levels with
* quantities 1 and x>0, respectively), the cursor's position is defined by a
* price level and a quantity offset (the unit quantity modulo total quantity
* walked thus far).
*/
struct SyntheticBook_LegCursor {
SyntheticBook_LegCursor(const_SyntheticBook_LegPtr);
SyntheticBook_LegCursor(const_SyntheticBook_LegPtr, BookMark);
SyntheticBook_LegCursor(const SyntheticBook_LegCursor &);
~SyntheticBook_LegCursor();
/**
* Counts the number of units available at the best price. As the
* synthetic book is computed, the limiting factor of each price level
* is equal to the 'units_at_best_price' minimum of all the legs.
* Returns a tuple of the unit price, and the number of units available at
* that price.
*/
mdp3::BookLevel curr_level() const;
/**
* Gets the current marginal level (not in terms of leg units).
*/
mdp3::BookLevel curr_level_marginal() const;
/**
* Gets the signed qty of this leg in its synthetic definition (negative if
* a 'sell' leg, otherwise positive).
*/
mdp3::Quantity unit_qty() const;
/**
* Computes the price of the next quantity, and optionally moves the position
* there.
*/
mdp3::Price compute_next(mdp3::Quantity, bool move_position);
/**
* Computes the price of the next quantity, and optionally moves the position
* there.
*/
mdp3::Price compute_next_marginal(mdp3::Quantity, bool move_position);
/**
* Computes the price of the previous quantity, and optionally moves the
* position there.
*/
mdp3::Price compute_prev(mdp3::Quantity, bool move_position);
/**
* Computes the price of the previous quantity, and optionally moves the
* position there.
*/
mdp3::Price compute_prev_marginal(mdp3::Quantity, bool move_position);
/**
* Removes the specified quantity from the top of the book, and returns the
* total cost.
*/
mdp3::Price remove(mdp3::Quantity);
/**
* Removes the specified quantity of units from the top of the book, and
* returns the total cost.
*/
mdp3::Price remove_units(mdp3::Quantity);
/**
* Gets the cursor's current position (the reference from which prices are
* computed)
*/
const BookMark &position() const;
const_SyntheticBook_LegPtr leg() const;
SyntheticBook_LegCursor &operator=(const SyntheticBook_LegCursor &);
private:
struct PImpl;
std::unique_ptr<PImpl> _me;
};
using SyntheticBook_LegCursors =
boost::container::small_vector<SyntheticBook_LegCursor, 2>;
} // namespace bts::spartan
@@ -1,7 +1,7 @@
#include "domain/book/book_utils.h"
#include "domain/book/SyntheticBook.h"
#include "server/sparkd/cmds/spartan/back_testing/common/mdp3_utils.h"
#include "server/sparkd/cmds/spartan/utils/Permutation.h"
#include <catch/catch.hpp>
#include <limits>
#include <math.h>
@@ -169,6 +169,24 @@ SmallBook expected_synth_book(LegMarkets legs) {
return rv;
}
bool _books_match(const SmallBook &a, const SmallBook &b) {
if (a.size() != b.size())
return false;
for (uint32_t i = 0; i < a.size(); i++) {
if (a[i].price != b[i].price)
return false;
if (a[i].quantity != b[i].quantity)
return false;
}
return true;
}
inline std::ostream & operator<<(std::ostream &out, const SmallBook &sbk) {
for (const auto &l : sbk)
out << l.price << l.price << ": " << l.quantity << ", ";
return out;
}
bool books_match(const SmallBook &a, const SmallBook &b) {
REQUIRE(a.size() == b.size());
for (uint32_t i = 0; i < a.size(); i++) {
@@ -371,15 +389,56 @@ Quantity expected_volume(const LegMarkets &synth) {
})));
}
static int _counter = 0;
void test_synth_book(LegMarkets synth) {
auto expected = expected_synth_book(synth);
// test every permutation of the legs. All permutations of a particular
// set of legs should produce the same synthetic book.
auto perms = bts::spartan::Permutation::all(synth);
int counter = 0;
for (const auto &p : perms) {
counter++;
SmallBook book_out;
bts::spartan::mdp3::book_utils::compute_synthetic_book(book_out, p, 10);
SmallBook book_out_historic;
bts::spartan::mdp3::book_utils::compute_synthetic_book(book_out_historic, p, 10);
SyntheticBook synth_book;
SecurityID sec_id(0);
// The SyntheticBook does not own its books, it instead accepts pointers
// to existing books. The 'existing books' are stored in a vector for
// house-keeping while the synthetic book is tested. Then they are deleted.
std::vector<BookSide*> temp_leg_books;
for (const auto &[qty, price, bk] : p) {
BookSide *bs = new BookSide();
temp_leg_books.push_back(bs);
std::uint32_t i = 0;
for (auto pl : bk) {
(*bs)[i].price = pl.price;
(*bs)[i].quantity = pl.quantity;
bts_assert(i++ < bs->size());
}
synth_book.add_leg(LegDefinition {
sec_id,
from_ratio(qty.value()),
qty
}, bs);
sec_id.value()++;
}
for (auto pl : synth_book) {
if (pl.quantity == 0)
break;
book_out.emplace_back(pl.price, pl.quantity);
}
// delete the leg books
for (auto *b : temp_leg_books)
delete b;
temp_leg_books.clear();
// bts::spartan::mdp3::book_utils::compute_synthetic_book(book_out, p, 10);
_counter++;
if (!books_match(book_out, expected)) {
std::cout << "Failed to match on iter no " << _counter << ".\n";
}
REQUIRE(books_match(book_out, expected));
REQUIRE(books_match(book_out_historic, expected));
// additional checks, though not designed to catch everything,
// they validate some basic properties of the resultant book.
if (book_out.size()) {
@@ -419,8 +478,8 @@ TEST_CASE(
// the resultant synth book should be empty.
SECTION("empty synthetic book") {
SmallBook synth_book;
bts::spartan::mdp3::book_utils::compute_synthetic_book(
synth_book, {}, 10);
// bts::spartan::mdp3::book_utils::compute_synthetic_book(
// synth_book, {}, 10);
REQUIRE(synth_book.empty());
}
}
@@ -1,9 +1,10 @@
#include "PolygonOpportunityFinder.h"
#include "back_testing/common/mdp3_utils.h"
#include "domain/SecuritySnapshot.h"
#include "domain/Side.h"
#include "domain/book/SyntheticBook.h"
#include "lib/domain_model/Security.h"
#include "lib/md/MDConsumerHandle.h"
#include "domain/SecuritySnapshot.h"
#include "domain/book/book_utils.h"
#include "back_testing/common/mdp3_utils.h"
#include <fstream>
namespace bts::spartan::mdp3 {
@@ -210,6 +211,7 @@ struct PolygonOpportunityFinder::PImpl {
SecurityMap const &imap;
std::unordered_set<size_t> active_polygons = {};
std::unordered_map<SecurityID, SnapshotRec> all_snapshots = {};
std::unordered_map<std::size_t, Sided<SyntheticBook>> cached_synth_books{};
// sec's to pid's
std::unordered_map<SecurityID, std::vector<size_t>> dependencies = {};
std::unordered_map<SecurityID, CachedBook> cached_map = {};
@@ -222,8 +224,20 @@ PolygonOpportunityFinder::PolygonOpportunityFinder(
PolygonMap const &polys, SecurityMap const &imap)
: me(new PImpl{polys, imap}) {
for (auto &[pid, p] : polys) {
for (auto &pp : p.parts)
auto &sb = me->cached_synth_books[pid];
for (auto &pp : p.parts) {
sb.bid.add_leg(LegDefinition {
pp.sec_id,
side_from_ratio(pp.ratio),
Quantity(pp.ratio)
}, &me->cached_map[pp.sec_id].bid_d_book);
sb.ask.add_leg(LegDefinition {
pp.sec_id,
side_from_ratio(-pp.ratio),
Quantity(-pp.ratio)
}, &me->cached_map[pp.sec_id].ask_d_book);
me->dependencies[pp.sec_id].push_back(pid);
}
}
}
@@ -243,23 +257,9 @@ double eval_poly(Polygon const &poly, Pricer const &price) {
}
// assumes PolygonValuation book referecnes are filled in
void compute_polygon_book (PolygonValuation &pv) {
std::vector<std::tuple<Quantity, Price, BookSide, BookSide>> legs, d_legs;
size_t i = 0;
for (const auto &ip : pv.polygon.parts) {
auto leg_qty = Quantity(ip.ratio);
const CachedBook& cbook = pv.leg_books[i++];
legs.push_back(std::make_tuple(
leg_qty, Price(), cbook.bid_book, cbook.ask_book));
d_legs.push_back(std::make_tuple(
leg_qty, Price(), cbook.bid_d_book, cbook.ask_d_book));
}
book_utils::compute_synthetic_books(
pv.poly_bid_book, pv.poly_ask_book, legs, 5);
book_utils::compute_synthetic_books(
pv.poly_direct_bid_book, pv.poly_direct_ask_book, d_legs, 5);
auto top_ask = pv.poly_ask_book[0];
auto top_bid = pv.poly_bid_book[0];
void compute_polygon_book (PolygonValuation &pv, const SyntheticBook &synth_bids, const SyntheticBook &synth_asks) {
auto top_ask = *synth_asks.begin();
auto top_bid = *synth_bids.begin();
// add values if positive edge
if(top_ask.price.to_double() < 0){
pv.side = Side::Buy;
@@ -276,7 +276,6 @@ void compute_polygon_book (PolygonValuation &pv) {
pv.direct_quantity = pv.poly_direct_bid_book[0].quantity;
}
// set leg book sides
i = 0;
auto flip_side = [](Side side){
return (side == Side::Buy ? Side::Sell :
Side::Buy);
@@ -431,7 +430,8 @@ void PolygonOpportunityFinder::add_current_event_polyval(
auto &snap = me->all_snapshots[l.sec_id];
pval.leg_books.emplace_back(snap.ev_info,snap.snapshot);
}
compute_polygon_book(pval);
compute_polygon_book(
pval, me->cached_synth_books[pid].bid, me->cached_synth_books[pid].ask);
v.push_back(pval);
}
@@ -464,7 +464,8 @@ void PolygonOpportunityFinder::add_prev_event_polyval(
newest_leg->ev_info.last_packet_sn,
Side::Buy}; //TODO
pval.leg_books = leg_books;
compute_polygon_book(pval);
compute_polygon_book(
pval, me->cached_synth_books[pid].bid, me->cached_synth_books[pid].ask);
v.push_back(pval);
}
@@ -1,3 +1,4 @@
#include "domain/LegDefinition.h"
#include "lib/orderman/orderman_utils/Formatter.h"
#include "lib/utils/Sqlite_utils.h"
#include "server/sparkd/cmds/spartan/utils/sql/sql_utils.h"
@@ -16,9 +17,7 @@ using namespace bts::spartan::mdp3;
namespace bts::spartan::sql::adapters::polygon_defs {
using PolygonDefs = std::unordered_map<
SecurityID,
std::vector<std::tuple<SecurityID, Quantity>>>;
using PolygonDefs = std::unordered_map<SecurityID, LegVec>;
// assume there aren't negative ids,
const int no_id = -1;
const char *polygon_legs = "polygon_legs";
@@ -45,11 +44,11 @@ PolygonDefs read_sql(const char *db_path, const char *legs_query) {
r.ratio = -r.ratio;
})}};
std::function<void(Row &)> on_row([&](auto &r) {
res.emplace(
SecurityID(r.pid),
std::vector<std::tuple<SecurityID, Quantity>>())
.first->second.emplace_back(
SecurityID(r.lsid), Quantity(r.ratio));
auto &leg =
res.emplace(SecurityID(r.pid), LegVec()).first->second.emplace_back();
leg.security_id.value() = r.lsid;
leg.ratio.value() = r.ratio;
leg.side = from_ratio(r.ratio);
});
char *err = nullptr;
if (synthesize_rows(db.get(), legs_query, cell_ops, on_row, err))
@@ -6,13 +6,11 @@
#include <vector>
namespace bts::spartan::sql::adapters::polygon_defs {
std::unordered_map<
SecurityID,
std::vector<std::tuple<SecurityID, mdp3::Quantity>>>
read_sql(const char *db_path, const char *legs_query);
std::unordered_map<
SecurityID,
std::vector<std::tuple<SecurityID, mdp3::Quantity>>>
read_sql(const char *db_path, const std::unordered_set<int> &ids);
std::unordered_map<SecurityID, LegVec> read_sql(
const char *db_path, const char *legs_query);
std::unordered_map<SecurityID, LegVec> read_sql(
const char *db_path, const std::unordered_set<int> &ids);
} // namespace bts::spartan::sql::adapters::polygon_defs