Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
position_tracker.hpp
Go to the documentation of this file.
1#pragma once
2
7#include <slick/logger.hpp>
8#include <array>
9#include <unordered_map>
10#include <string>
11#include <vector>
12#include <string_view>
13
14namespace slick::trader {
15
16// Single-writer position tracking with FIFO accounting
17// Tracks positions per strategy and instrument
18// NOTE: Single-writer only (called from StrategyManager thread)
19// Readers use lock-free position_update_queue for consumption
21public:
22 PositionTracker() = default;
23 ~PositionTracker() = default;
24
25 // Keeps every position in `store` from now on, and first takes up the positions it
26 // holds - those of a previous run, with their open lots, so FIFO accounting carries on
27 // where it stopped. Call it once, before any fill is booked and before any other thread
28 // reads positions. Without a store positions live in memory only, and a restart starts
29 // flat. The store must outlive the tracker.
30 void attach_store(PositionStore& store);
31
32 // Update position from a fill event
33 // Uses FIFO accounting to calculate realized PnL
34 void on_fill(const std::string& strategy_id, const OrderFillEvent& fill);
35
36 // Whether the strategies have had this fill already. A broker that journals its fills
37 // (OrderFillEvent::journal_seq) replays them after a restart, and those up to where the
38 // strategies had got are to be dropped - every replayed one without a store, whose
39 // positions started flat. False for a fill that was not journaled.
40 bool fill_handled(const OrderFillEvent& fill) const noexcept {
41 const auto broker = static_cast<std::size_t>(fill.broker_id);
42 if (fill.journal_seq == 0) {
43 return false;
44 }
45 if (fill.replayed && !store_) {
46 return true;
47 }
48 return broker < journaled_.size() && fill.journal_seq <= journaled_[broker];
49 }
50 // The strategies have had the fill - every one that books it has booked it - so a
51 // replay of it is dropped from now on, after a restart too when there is a store.
52 void fill_dispatched(const OrderFillEvent& fill) noexcept;
53
54 // Get current position for strategy/instrument (single-reader safe)
55 Position get_position(const std::string& strategy_id, std::string_view instrument) const;
56
57 // Get all positions for a strategy (single-reader safe)
58 std::unordered_map<std::string, Position> get_all_positions(const std::string& strategy_id) const;
59
60 // Get all positions across all strategies (single-reader safe)
61 std::unordered_map<std::string, std::unordered_map<std::string, Position>> get_all_positions() const;
62
63 // Clear positions for a strategy
64 void clear_strategy_positions(const std::string& strategy_id);
65
66 // Clear all positions
67 void clear_all();
68
69 // Set fallback fee structure for brokers that don't report fees in fill events
70 // Contract multiplier for an instrument - the currency value of a one-unit price move
71 // on one unit of quantity (futures: ES = 50; spot instruments keep the default of 1).
72 // Applies to later fills and to positions already held; PnL realized before it was set
73 // stays as booked. Returns false, and changes nothing, for a non-finite or non-positive value.
74 bool set_contract_multiplier(std::string_view instrument, double multiplier);
75 double get_contract_multiplier(std::string_view instrument) const;
76
77 void set_fee_structure(FeeStructure fee_structure) { fee_structure_ = fee_structure; }
78 const FeeStructure& get_fee_structure() const { return fee_structure_; }
79
80private:
81 // FIFO lot for position tracking
82 using Lot = PositionLot;
83
84 // Position with FIFO lots for realized PnL calculation
85 struct PositionWithLots {
86 Position position;
87 std::vector<Lot> lots; // FIFO queue of entry lots
88 uint32_t store_slot{PositionStore::NO_SLOT}; // where the store keeps it
89
90 PositionWithLots() = default;
91 explicit PositionWithLots(const std::string& inst) : position(inst) {}
92 };
93
94 // Records the position in the store, when there is one - with the fill it was booked
95 // from, for that fill's journal number.
96 void persist(const std::string& strategy_id, PositionWithLots& pos, const OrderFillEvent* fill = nullptr);
97
98 // Apply fill to position using FIFO accounting
99 void apply_fill(PositionWithLots& pos, bool is_buy, qty_t fill_qty, price_t fill_price, uint64_t timestamp, price_t fee_amount);
100
101 // Calculate new average price when adding to position
102 price_t calculate_new_avg_price(price_t current_avg, qty_t current_qty,
103 price_t fill_price, qty_t fill_qty) const;
104
105 FeeStructure fee_structure_; // fallback for brokers without per-fill fee data
106
107 PositionStore* store_{nullptr}; // non-owning; null keeps positions in memory only
108 // By BrokerId: the journal number of the last fill the strategies have had.
109 std::array<uint64_t, PositionStore::MAX_BROKERS> journaled_{};
110
111 std::unordered_map<std::string, double> contract_multipliers_; // instrument -> multiplier (absent = 1)
112
113 // Positions: strategy_id -> instrument -> PositionWithLots
114 std::unordered_map<std::string, std::unordered_map<std::string, PositionWithLots>> positions_;
115};
116
117} // namespace slick::trader
static constexpr uint32_t NO_SLOT
void clear_strategy_positions(const std::string &strategy_id)
bool set_contract_multiplier(std::string_view instrument, double multiplier)
bool fill_handled(const OrderFillEvent &fill) const noexcept
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 set_fee_structure(FeeStructure fee_structure)
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
const FeeStructure & get_fee_structure() const
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16