21 if (!is_valid_mark(price)) {
22 LOG_DEBUG(
"PnLCalculator::update_mark_price: rejected invalid mark price {} for {}", price, instrument);
25 bid_prices_[instrument] = {price, timestamp_ns};
26 ask_prices_[instrument] = {price, timestamp_ns};
30 if (!is_valid_mark(bid) || !is_valid_mark(ask)) {
31 LOG_DEBUG(
"PnLCalculator::update_top_of_book: rejected invalid tob for {} bid={} ask={}", instrument, bid, ask);
34 if (bid != bid_prices_[instrument].price || ask != ask_prices_[instrument].price) {
35 bid_prices_[instrument] = {bid, timestamp_ns};
36 ask_prices_[instrument] = {ask, timestamp_ns};
41 auto bid_it = bid_prices_.find(instrument);
42 auto ask_it = ask_prices_.find(instrument);
43 if (bid_it != bid_prices_.end() && ask_it != ask_prices_.end()) {
44 return (bid_it->second.price / 2) + (ask_it->second.price / 2);
46 if (bid_it != bid_prices_.end())
return bid_it->second.price;
47 if (ask_it != ask_prices_.end())
return ask_it->second.price;
61 auto positions = position_tracker_.get_all_positions(strategy_id);
65 price_t total_realized_fees = 0;
68 for (
const auto& [instrument, position] : positions) {
70 total_realized += position.realized_pnl - position.realized_fees;
71 total_realized_fees += position.realized_fees;
72 total_open_fees += position.open_fees;
75 if (!position.is_flat()) {
76 const bool is_long = position.quantity > 0;
77 const auto& price_map = is_long ? bid_prices_ : ask_prices_;
78 auto mark_it = price_map.find(instrument);
79 if (mark_it != price_map.end()) {
80 const price_t mark_price = mark_it->second.price;
81 if (!is_valid_mark(mark_price)) {
82 LOG_WARN(
"PnLCalculator::calculate_pnl: skipping unrealized PnL for {} — invalid mark price {}", instrument, mark_price);
84 total_unrealized +=
to_price_t(position.get_unrealized_pnl(mark_price))
93 snapshot.
total_fees = total_realized_fees + total_open_fees;
94 snapshot.
total_pnl = total_realized + total_unrealized;
101 std::unordered_map<std::string, PnLSnapshot> result;
103 auto all_positions = position_tracker_.get_all_positions();
105 for (
const auto& [strategy_id, positions] : all_positions) {
106 result.emplace(strategy_id,
calculate_pnl(strategy_id, timestamp_ns));