Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
position_tracker.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
3#include <algorithm>
4#include <cmath>
5#include <span>
6
7namespace slick::trader {
8
10 store_ = &store;
11 for (std::size_t broker = 0; broker < journaled_.size(); ++broker) {
12 journaled_[broker] = store.journaled(static_cast<BrokerId>(broker));
13 }
14 store.for_each([this](uint32_t slot, std::string_view strategy_id, const Position& position,
15 std::span<const PositionLot> lots) {
16 auto& pos = positions_[std::string(strategy_id)][position.instrument];
17 pos.position = position;
18 pos.lots.assign(lots.begin(), lots.end());
19 pos.store_slot = slot;
20 // The multiplier the position was last valued with, until the instrument's
21 // definition says it again.
22 contract_multipliers_[position.instrument] = position.multiplier;
23 LOG_INFO("PositionTracker: restored {} {} pos: {} avg: {} realized_pnl: {} ({} open lot(s))",
24 strategy_id, position.instrument, from_qty_t(position.quantity), from_price_t(position.avg_price),
25 from_price_t(position.realized_pnl), lots.size());
26 });
27}
28
29void PositionTracker::persist(const std::string& strategy_id, PositionWithLots& pos, const OrderFillEvent* fill) {
30 if (store_) {
31 pos.store_slot = store_->save(pos.store_slot, strategy_id, pos.position, pos.lots,
32 fill ? fill->broker_id : BrokerId::UNKNOWN, fill ? fill->journal_seq : 0);
33 }
34}
35
37 const auto broker = static_cast<std::size_t>(fill.broker_id);
38 if (fill.journal_seq == 0 || broker >= journaled_.size() || fill.journal_seq <= journaled_[broker]) {
39 return;
40 }
41 journaled_[broker] = fill.journal_seq;
42 if (store_) {
43 store_->mark_journaled(fill.broker_id, fill.journal_seq);
44 }
45}
46
47void PositionTracker::on_fill(const std::string& strategy_id, const OrderFillEvent& fill) {
48 // Single-writer: called only from StrategyManager thread
49
50 const std::string instrument(fill.instrument);
51 // The fill says what a contract is worth: it may come before the instrument's definition
52 // does - replayed from a broker's journal at startup - and PnL realized now stays booked.
53 if (fill.contract_multiplier > 0.0 && fill.contract_multiplier != get_contract_multiplier(instrument)) {
55 }
56 auto& strategy_positions = positions_[strategy_id];
57 auto& pos_with_lots = strategy_positions[instrument];
58
59 if (pos_with_lots.position.instrument.empty()) {
60 pos_with_lots.position.instrument = instrument;
61 pos_with_lots.position.multiplier = get_contract_multiplier(instrument);
62 }
63
64 const bool is_buy = (fill.side == Side::BUY);
65 const qty_t fill_qty = fill.fill_quantity;
66 const price_t fill_price = fill.fill_price;
67 const uint64_t timestamp = fill.timestamp_ns;
68
69 // Use fee from event if provided (e.g. Coinbase), else compute from fallback FeeStructure
70 const price_t fee = (fill.fee_amount > 0)
71 ? fill.fee_amount
72 : compute_fee(fill_price, fill_qty, fee_structure_);
73
74 apply_fill(pos_with_lots, is_buy, fill_qty, fill_price, timestamp, fee);
75 pos_with_lots.position.last_update_time = timestamp;
76 persist(strategy_id, pos_with_lots, &fill);
77
78 LOG_INFO("PositionTracker: {} {} fill: {} {}@{} fee:{} | pos: {} avg: {} realized_pnl: {} realized_fees: {} open_fees: {}",
79 strategy_id, instrument,
80 is_buy ? "BUY" : "SELL",
81 from_qty_t(fill_qty), from_price_t(fill_price), from_price_t(fee),
82 from_qty_t(pos_with_lots.position.quantity),
83 from_price_t(pos_with_lots.position.avg_price),
84 from_price_t(pos_with_lots.position.realized_pnl),
85 from_price_t(pos_with_lots.position.realized_fees),
86 from_price_t(pos_with_lots.position.open_fees));
87}
88
89void PositionTracker::apply_fill(PositionWithLots& pos, bool is_buy, qty_t fill_qty,
90 price_t fill_price, uint64_t timestamp, price_t fee_amount) {
91 // Zero and negative prices are real: calendar spreads trade through zero, and so have
92 // outright futures. Only the null sentinel is not a price.
93 if (fill_price == NULL_PRICE) {
94 LOG_ERROR("PositionTracker: fill has no fill_price — skipping P&L update");
95 return;
96 }
97 Position& p = pos.position;
98 std::vector<Lot>& lots = pos.lots;
99
100 const bool position_is_long = p.is_long();
101 const bool position_is_short = p.is_short();
102 const bool position_is_flat = p.is_flat();
103
104 // Case 1: Opening new position or adding to existing position in same direction
105 // Entry fee goes into open_fees (deducted from unrealized until the lot is closed)
106 if (position_is_flat || (is_buy && position_is_long) || (!is_buy && position_is_short)) {
107 const qty_t signed_fill = is_buy ? fill_qty : -fill_qty;
108
109 if (!position_is_flat) {
110 p.avg_price = calculate_new_avg_price(p.avg_price, p.quantity, fill_price, signed_fill);
111 } else {
112 p.avg_price = fill_price;
113 }
114
115 p.quantity += signed_fill;
116 p.open_fees += fee_amount; // entry fee reduces unrealized until position is closed
117 lots.push_back(Lot{fill_qty, fill_price, timestamp});
118 return;
119 }
120
121 // Case 2: Reducing or reversing position (FIFO accounting for realized PnL)
122 // For each lot closed: transfer its proportional entry fee + exit fee to realized_fees
123 qty_t remaining_qty = fill_qty;
124
125 while (remaining_qty > 0 && !lots.empty()) {
126 Lot& oldest_lot = lots.front();
127 const qty_t close_qty = std::min(remaining_qty, oldest_lot.quantity);
128
129 // Transfer proportional entry fee from open_fees to realized_fees
130 // (must use p.quantity BEFORE updating it this iteration)
131 const qty_t current_qty = std::abs(p.quantity);
132 const price_t entry_fee_transfer = (current_qty > 0)
133 ? to_price_t(from_price_t(p.open_fees) * from_qty_t(close_qty) / from_qty_t(current_qty))
134 : p.open_fees;
135
136 // Proportional share of exit fee for this lot's portion of the fill
137 const price_t exit_fee_portion = (fill_qty > 0)
138 ? to_price_t(from_price_t(fee_amount) * from_qty_t(close_qty) / from_qty_t(fill_qty))
139 : 0;
140
141 p.realized_fees += entry_fee_transfer + exit_fee_portion;
142 p.open_fees -= entry_fee_transfer;
143
144 // Calculate realized PnL for this lot closure
145 const double pnl_per_unit = is_buy
146 ? from_price_t(oldest_lot.price) - from_price_t(fill_price) // Closing short
147 : from_price_t(fill_price) - from_price_t(oldest_lot.price); // Closing long
148
149 p.realized_pnl += to_price_t(pnl_per_unit * from_qty_t(close_qty) * p.multiplier);
150
151 // Update position quantity
152 const qty_t signed_close = is_buy ? close_qty : -close_qty;
153 p.quantity += signed_close;
154
155 // Deduct from lot
156 oldest_lot.quantity -= close_qty;
157 if (oldest_lot.quantity == 0) {
158 lots.erase(lots.begin());
159 }
160
161 remaining_qty -= close_qty;
162 }
163
164 // If we still have remaining quantity, we're reversing the position
165 // All old lots consumed → old open_fees fully moved to realized; new position starts fresh
166 if (remaining_qty > 0) {
167 const qty_t signed_remaining = is_buy ? remaining_qty : -remaining_qty;
168 p.quantity += signed_remaining;
169 p.avg_price = fill_price;
170 lots.push_back(Lot{remaining_qty, fill_price, timestamp});
171
172 // Entry fee for the reversed position portion
173 p.open_fees = (fill_qty > 0)
174 ? to_price_t(from_price_t(fee_amount) * from_qty_t(remaining_qty) / from_qty_t(fill_qty))
175 : 0;
176 }
177
178 if (p.is_flat()) {
179 p.avg_price = 0;
180 }
181}
182
183price_t PositionTracker::calculate_new_avg_price(price_t current_avg, qty_t current_qty,
184 price_t fill_price, qty_t fill_qty) const {
185 const double total_cost = from_price_t(current_avg) * std::abs(from_qty_t(current_qty))
186 + from_price_t(fill_price) * std::abs(from_qty_t(fill_qty));
187 const double total_qty = std::abs(from_qty_t(current_qty)) + std::abs(from_qty_t(fill_qty));
188
189 return to_price_t(total_cost / total_qty);
190}
191
192bool PositionTracker::set_contract_multiplier(std::string_view instrument, double multiplier) {
193 if (!std::isfinite(multiplier) || multiplier <= 0.0) {
194 LOG_ERROR("PositionTracker: rejecting contract multiplier {} for {}", multiplier, instrument);
195 return false;
196 }
197
198 const std::string key(instrument);
199 contract_multipliers_[key] = multiplier;
200
201 // Positions already held revalue from now on; what they realized before stays as booked.
202 for (auto& [strategy_id, strategy_positions] : positions_) {
203 auto it = strategy_positions.find(key);
204 if (it != strategy_positions.end() && it->second.position.multiplier != multiplier) {
205 it->second.position.multiplier = multiplier;
206 persist(strategy_id, it->second);
207 }
208 }
209 return true;
210}
211
212double PositionTracker::get_contract_multiplier(std::string_view instrument) const {
213 auto it = contract_multipliers_.find(std::string(instrument));
214 return it == contract_multipliers_.end() ? 1.0 : it->second;
215}
216
217Position PositionTracker::get_position(const std::string& strategy_id, std::string_view instrument) const {
218 // Single-reader safe (called from same thread)
219
220 auto strategy_it = positions_.find(strategy_id);
221 if (strategy_it == positions_.end()) {
222 return Position(instrument);
223 }
224
225 auto pos_it = strategy_it->second.find(std::string(instrument));
226 if (pos_it == strategy_it->second.end()) {
227 return Position(instrument);
228 }
229
230 return pos_it->second.position;
231}
232
233std::unordered_map<std::string, Position> PositionTracker::get_all_positions(const std::string& strategy_id) const {
234
235 std::unordered_map<std::string, Position> result;
236
237 auto strategy_it = positions_.find(strategy_id);
238 if (strategy_it == positions_.end()) {
239 return result;
240 }
241
242 for (const auto& [instrument, pos_with_lots] : strategy_it->second) {
243 result.emplace(instrument, pos_with_lots.position);
244 }
245
246 return result;
247}
248
249std::unordered_map<std::string, std::unordered_map<std::string, Position>>
251
252 std::unordered_map<std::string, std::unordered_map<std::string, Position>> result;
253
254 for (const auto& [strategy_id, strategy_positions] : positions_) {
255 auto& strategy_result = result[strategy_id];
256 for (const auto& [instrument, pos_with_lots] : strategy_positions) {
257 strategy_result.emplace(instrument, pos_with_lots.position);
258 }
259 }
260
261 return result;
262}
263
264void PositionTracker::clear_strategy_positions(const std::string& strategy_id) {
265 positions_.erase(strategy_id);
266 if (store_) {
267 store_->erase_strategy(strategy_id);
268 }
269 LOG_INFO("PositionTracker: Cleared positions for strategy {}", strategy_id);
270}
271
273 positions_.clear();
274 if (store_) {
275 store_->clear();
276 }
277 LOG_INFO("PositionTracker: Cleared all positions");
278}
279
280} // namespace slick::trader
void for_each(const Visitor &visit) const
uint32_t save(uint32_t slot, std::string_view strategy_id, const Position &position, std::span< const PositionLot > lots, BrokerId broker=BrokerId::UNKNOWN, uint64_t journal_seq=0)
uint64_t journaled(BrokerId broker) const noexcept
void clear_strategy_positions(const std::string &strategy_id)
bool set_contract_multiplier(std::string_view instrument, double multiplier)
std::unordered_map< std::string, std::unordered_map< std::string, Position > > get_all_positions() const
void attach_store(PositionStore &store)
double get_contract_multiplier(std::string_view instrument) const
void fill_dispatched(const OrderFillEvent &fill) noexcept
void on_fill(const std::string &strategy_id, const OrderFillEvent &fill)
Position get_position(const std::string &strategy_id, std::string_view instrument) const
double from_price_t(price_t value)
Definition types.hpp:36
price_t to_price_t(double value)
Definition types.hpp:24
price_t compute_fee(price_t fill_price, qty_t fill_qty, const FeeStructure &fee)
constexpr price_t NULL_PRICE
Definition types.hpp:19
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
double from_qty_t(qty_t value)
Definition types.hpp:40
char instrument[MAX_INSTRUMENT_LENGTH]
Definition event.hpp:61
uint64_t timestamp_ns
Definition event.hpp:58
BrokerId broker_id
Definition event.hpp:60