Files
spark/src/server/sparkd/position/PositionServicePNLHelper.cpp
T
John Colvin 81bafbe68d fix build: Address trivial werrors after upgrading to C++ 20
All werrors were about implicit 'this' captures in lambdas
2023-06-26 15:24:46 +00:00

268 lines
8.9 KiB
C++

#include "PositionServicePNLHelper.h"
#include "lib/api/services/OrderService.client.pb.h"
#include "lib/config/config.h"
#include "lib/config/protos/cme_reference_data.pb.h"
#include "lib/config/protos/toggles.pb.h"
#include "lib/domain_model/Security.h"
#include "lib/logging/logging.h"
#include "lib/md/MDClient.h"
#include "lib/os/os.h"
#include "lib/utils/PBUtils.h"
#include "lib/utils/LockBox.h"
#include <unordered_map>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <map>
#include <optional>
#include <set>
#include <utility>
namespace bts {
namespace position {
using namespace bts::api::position;
using namespace bts::api::orderman;
using namespace bts::md;
class HandleIndex {
public:
enum PNLType { UNRESOLVED = 0, SPREAD, OUTRIGHT };
bts::md::MDClient &_client;
int _sub;
std::optional<bts::md::MDConsumer> _consumer;
public:
utils::LockBox<std::unordered_map<SecurityKey, MDConsumerHandle>> index;
HandleIndex(md::MDClient &client)
: _client(client), _sub(0), _consumer(std::nullopt), index() {
_sub = _client.on_consumer().subscribe(
[=, this](const MDConsumer &c) { on_consumer(c); });
on_consumer(_client.current_consumer());
}
~HandleIndex() { _client.on_consumer().unsubscribe(_sub); }
MDConsumerHandle _get_handle(SecurityKey key) const {
auto handle = index.lock([id = key](const auto &index) {
auto iter = index.find(id);
return iter != index.end() ? iter->second : MDConsumerHandle{};
});
return handle;
}
PNLType get_pnl_type(SecurityKey key) const {
auto h = _get_handle(key);
if (h.is_initialized()) {
const auto &sec = h.get_normalized_security();
if (sec.has_future() || sec.has_option())
return PNLType::OUTRIGHT;
else
return PNLType::SPREAD;
} else
return PNLType::UNRESOLVED;
}
double get_cpp(SecurityKey key) const {
auto h = _get_handle(key);
if (h.is_initialized()) {
const auto &sec = h.get_normalized_security();
return sec.contract_spec().cash_per_point();
}
return os::nan();
}
void get_md(
SecurityKey key,
double &bid,
double &ask,
double &last,
double &settle) {
auto handle = _get_handle(key);
bid = bts::os::nan();
ask = bid;
last = bid;
settle = bid;
if (handle.is_initialized()) {
utils::TimeStamp time;
PriceSize bid_ps, ask_ps;
handle.get_direct_book(time, 1, &bid_ps, &ask_ps);
bid = bid_ps.price();
ask = ask_ps.price();
PriceSize last_ps;
datetime::LLDateTime trade_time;
utils::TimeStamp zero_time;
handle.get_last_trade(zero_time, last_ps, trade_time, nullptr);
last = last_ps.price();
settle = handle.settlement_price().price();
}
}
private:
void on_consumer(const MDConsumer &c) {
MDConsumer temp(c);
if (temp.all_heartbeats_ok()) {
auto existing = _consumer ? _consumer->id() : 0;
LOG(md, Info, "Updating MBOService MDConsumer. Old {} new {}",
existing, temp.id());
// clear the index
index.lock([](auto &index) { index.clear(); });
// Swap to new consumer
if (_consumer) {
_consumer->swap(temp);
} else {
_consumer = temp;
}
// Subscribe to on_security
auto id = _consumer->id();
_consumer->on_security(
[this, id](const SecurityPtr &sec, MDConsumerHandle handle) {
LOG(md, Diag,
"PositionService::HandleIndex::on_security security:{}",
bts::securities::descriptor(*sec));
if (_consumer->id() == id) {
index.lock([handle](auto &index) {
index[SecurityKey(handle.key())] = handle;
});
}
});
}
}
};
struct PositionServicePNLHelper::PImpl {
HandleIndex handle_index;
std::map<SecurityKey, uint16_t> missing_data_log_count;
PImpl(bts::md::MDClient &md_client)
: handle_index(md_client), missing_data_log_count() {}
};
void PositionServicePNLHelper::compute_pnl(
const std::map<int, PositionUnit const *> &in_pos,
const std::map<std::string, uint32_t> &account_map,
const std::map<uint32_t, double> &cpp_override_map,
std::vector<PNLUnit> &out_pnl,
std::vector<AccountPNL> &out_account_pnl) {
out_account_pnl.clear();
for (const auto &p : in_pos) {
const PositionUnit &pu = *(p.second);
uint32_t sec_key = pu.security_id();
double cpp = me->handle_index.get_cpp(SecurityKey(sec_key));
double bid, ask, last, settle;
me->handle_index.get_md(SecurityKey(sec_key), bid, ask, last, settle);
PNLUnit pnlu;
pnlu.set_record_id(pu.record_id());
pnlu.mutable_pos()->CopyFrom(pu);
pnlu.set_cash_value(cpp);
auto it = cpp_override_map.find(sec_key);
if (it != cpp_override_map.end())
pnlu.mutable_cpp_override()->set_value(it->second);
pnlu.set_bid_price(bid);
pnlu.set_ask_price(ask);
pnlu.set_last_price(last);
pnlu.set_settlement_price(settle);
out_pnl.push_back(pnlu);
_log_missing_data(pnlu);
}
_aggregate_account_pnl(out_pnl, account_map, out_account_pnl);
}
void PositionServicePNLHelper::_aggregate_account_pnl(
const std::vector<api::position::PNLUnit> &in_pnl,
const std::map<std::string, uint32_t> &account_map,
std::vector<api::position::AccountPNL> &out_account_pnl) {
out_account_pnl.clear();
if (account_map.size() == 0)
return;
std::map<uint32_t, AccountPNL> acc_pnl;
for (const auto &pnlu : in_pnl) {
uint32_t acct_id = pnlu.pos().account_id();
const std::string &acct_name = pnlu.pos().account();
auto it = acc_pnl.find(acct_id);
if (it == acc_pnl.end()) {
AccountPNL new_acc;
new_acc.set_account_id(acct_id);
new_acc.set_account_name(acct_name);
new_acc.set_day_pnl(0.0);
acc_pnl[acct_id] = new_acc;
it = acc_pnl.find(acct_id);
}
AccountPNL &acc_pnl = it->second;
double pnl_dollars = _compute_day_pnl(pnlu);
acc_pnl.set_day_pnl(acc_pnl.day_pnl() + pnl_dollars);
}
// for accounts with no positions add 0
for (const auto &p : account_map) {
const std::string &acct_name = p.first;
uint32_t acct_id = p.second;
if (acc_pnl.find(acct_id) == acc_pnl.end()) {
AccountPNL new_acc;
new_acc.set_account_id(acct_id);
new_acc.set_account_name(acct_name);
new_acc.set_day_pnl(0.0);
acc_pnl[acct_id] = new_acc;
}
}
for (auto &u : acc_pnl)
out_account_pnl.push_back(u.second);
}
double PositionServicePNLHelper::_compute_day_pnl(
const bts::api::position::PNLUnit &u) {
// long
double pnl;
auto pnl_type =
me->handle_index.get_pnl_type(SecurityKey(u.pos().security_id()));
switch (pnl_type) {
case HandleIndex::OUTRIGHT: {
double md = (u.bid_price() + u.ask_price()) * 0.5;
md = bts::os::is_nan(md) ? u.bid_price() : md;
md = bts::os::is_nan(md) ? u.ask_price() : md;
md = bts::os::is_nan(md) ? u.settlement_price() : md;
double long_pnl = std::abs(u.pos().day_long_pos()) * u.cash_value() *
(md - u.pos().day_long_avg_price()),
short_pnl = std::abs(u.pos().day_short_pos()) * u.cash_value() *
(u.pos().day_short_avg_price() - md);
if (config::get<config::toggles::IgnoreNansInDayPnL>().enabled()) {
if (bts::os::is_nan(long_pnl))
long_pnl = 0.0;
if (bts::os::is_nan(short_pnl))
short_pnl = 0.0;
}
pnl = long_pnl + short_pnl;
break;
}
case HandleIndex::SPREAD:
pnl = 0.0;
break;
case HandleIndex::UNRESOLVED:
pnl = os::nan();
break;
}
return pnl;
}
void PositionServicePNLHelper::_log_missing_data(const PNLUnit &u) {
auto sec_key = SecurityKey(u.pos().security_id());
bool missing_cpp = os::is_nan(u.cash_value()),
missing_md = os::is_nan(u.bid_price()) && os::is_nan(u.ask_price()) &&
os::is_nan(u.last_price()) &&
os::is_nan(u.settlement_price());
if (missing_cpp || missing_md) {
const auto it = me->missing_data_log_count.find(sec_key);
uint16_t count = it == me->missing_data_log_count.end() ? 0 : it->second;
if (count <= 50)
LOG(md, Warn, "Missing pnl data sec:{} cpp:{} md:{}", sec_key,
missing_cpp, missing_md);
me->missing_data_log_count[sec_key] = count + 1;
} else
me->missing_data_log_count[sec_key] = 0;
}
PositionServicePNLHelper::PositionServicePNLHelper(md::MDClient &md_client)
: me(new PImpl(md_client)) {}
PositionServicePNLHelper::~PositionServicePNLHelper() {}
} // namespace position
} // namespace bts