Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
position_store.cpp
Go to the documentation of this file.
2#include <slick/logger.hpp>
3#include <algorithm>
4#include <atomic>
5#include <cstring>
6#include <stdexcept>
7
8namespace slick::trader {
9
10namespace {
11
12constexpr char MAGIC[8] = {'S', 'L', 'K', 'P', 'O', 'S', 'N', '1'};
13constexpr uint32_t VERSION = 1;
14
15// Slot::state. The two record states name the record that is current.
16constexpr uint8_t SLOT_EMPTY = 0;
17constexpr uint8_t SLOT_RECORD_0 = 1;
18constexpr uint8_t SLOT_RECORD_1 = 2;
19
20// Every field below sits at its natural alignment with no padding between them, which the
21// static_asserts pin: the layout is the file format.
22struct Record {
23 qty_t quantity;
24 price_t avg_price;
25 price_t realized_pnl;
26 price_t realized_fees;
27 price_t open_fees;
28 double multiplier;
29 uint64_t last_update_time;
30 uint32_t lot_count;
31 uint8_t journal_broker; // a BrokerId: whose journal journal_seq is in
32 uint8_t reserved[3];
33 uint64_t journal_seq; // the fill the position was last booked from; 0 for none
34 PositionLot lots[PositionStore::MAX_LOTS];
35};
36
37static_assert(sizeof(PositionLot) == 24);
38static_assert(sizeof(Record) == 72 + PositionStore::MAX_LOTS * sizeof(PositionLot));
39
40bool store_key(char* field, std::string_view key) noexcept {
41 if (key.size() > PositionStore::MAX_KEY_LENGTH) {
42 return false;
43 }
44 std::memset(field, 0, PositionStore::MAX_KEY_LENGTH + 1);
45 std::memcpy(field, key.data(), key.size());
46 return true;
47}
48
49std::string_view load_key(const char* field) noexcept {
50 return {field, strnlen(field, PositionStore::MAX_KEY_LENGTH)};
51}
52
53} // namespace
54
56 char magic[8];
57 uint32_t version;
58 uint32_t slot_size;
59 uint32_t max_lots;
60 uint8_t reserved[44];
61 uint64_t journaled[MAX_BROKERS]; // by BrokerId: see mark_journaled()
62};
63
65 uint8_t state;
66 uint8_t reserved[7];
69 Record records[2];
70};
71
72PositionStore::FileHeader& PositionStore::header() noexcept {
73 return *reinterpret_cast<FileHeader*>(file_.data());
74}
75
76PositionStore::PositionStore(const std::string& path, std::size_t capacity)
77 : path_(path)
78 , file_(path, sizeof(FileHeader) + std::max<std::size_t>(capacity, 1) * sizeof(Slot))
79{
80 static_assert(sizeof(FileHeader) == 64 + 8 * MAX_BROKERS);
81 static_assert(sizeof(Slot) == 8 + 2 * (MAX_KEY_LENGTH + 1) + 2 * sizeof(Record));
82 static_assert(sizeof(Slot) % alignof(Slot) == 0 && sizeof(FileHeader) % alignof(Slot) == 0);
83
84 auto* header = reinterpret_cast<FileHeader*>(file_.data());
85 const FileHeader blank{};
86 if (std::memcmp(header, &blank, sizeof(FileHeader)) == 0) {
87 // New, or never written: this is the first run with it.
88 FileHeader fresh{};
89 std::memcpy(fresh.magic, MAGIC, sizeof(MAGIC));
90 fresh.version = VERSION;
91 fresh.slot_size = static_cast<uint32_t>(sizeof(Slot));
92 fresh.max_lots = static_cast<uint32_t>(MAX_LOTS);
93 std::memcpy(header, &fresh, sizeof(FileHeader));
94 } else if (std::memcmp(header->magic, MAGIC, sizeof(MAGIC)) != 0) {
95 throw std::runtime_error("PositionStore: " + path + " is not a position store");
96 } else if (header->version != VERSION || header->slot_size != sizeof(Slot) || header->max_lots != MAX_LOTS) {
97 throw std::runtime_error("PositionStore: " + path + " was written with a different layout (version " +
98 std::to_string(header->version) + ")");
99 }
100
101 capacity_ = (file_.size() - sizeof(FileHeader)) / sizeof(Slot);
102 next_free_ = capacity_;
103 std::copy_n(header->journaled, MAX_BROKERS, journaled_);
104 for (std::size_t i = 0; i < capacity_; ++i) {
105 const Slot& slot = slot_at(i);
106 if (slot.state == SLOT_RECORD_0 || slot.state == SLOT_RECORD_1) {
107 ++size_;
108 // A fill booked after the strategies' place in the journal was last marked:
109 // the process died in between, and the position says how far they had got.
110 const Record& record = slot.records[slot.state - SLOT_RECORD_0];
111 if (record.journal_broker < MAX_BROKERS) {
112 journaled_[record.journal_broker] = std::max(journaled_[record.journal_broker], record.journal_seq);
113 }
114 } else if (slot.state != SLOT_EMPTY) {
115 ++size_;
116 } else if (next_free_ == capacity_) {
117 next_free_ = i;
118 }
119 }
120 // What the positions said is the mark from now on: it stays when they go.
121 std::copy_n(journaled_, MAX_BROKERS, header->journaled);
122 LOG_INFO("PositionStore: {} holds {} position(s), room for {}", path_, size_, capacity_);
123}
124
125uint64_t PositionStore::journaled(BrokerId broker) const noexcept {
126 const auto index = static_cast<std::size_t>(broker);
127 return index < MAX_BROKERS ? journaled_[index] : 0;
128}
129
130void PositionStore::mark_journaled(BrokerId broker, uint64_t journal_seq) noexcept {
131 const auto index = static_cast<std::size_t>(broker);
132 if (index < MAX_BROKERS && journal_seq > journaled_[index]) {
133 journaled_[index] = journal_seq;
134 header().journaled[index] = journal_seq;
135 }
136}
137
138PositionStore::Slot& PositionStore::slot_at(std::size_t index) noexcept {
139 return *reinterpret_cast<Slot*>(file_.data() + sizeof(FileHeader) + index * sizeof(Slot));
140}
141
142const PositionStore::Slot& PositionStore::slot_at(std::size_t index) const noexcept {
143 return *reinterpret_cast<const Slot*>(file_.data() + sizeof(FileHeader) + index * sizeof(Slot));
144}
145
146void PositionStore::for_each(const Visitor& visit) const {
147 for (std::size_t i = 0; i < capacity_; ++i) {
148 const Slot& slot = slot_at(i);
149 if (slot.state != SLOT_RECORD_0 && slot.state != SLOT_RECORD_1) {
150 continue;
151 }
152 // Copied out, so a caller is free to save() from the visit.
153 const Record record = slot.records[slot.state - SLOT_RECORD_0];
154 Position position(load_key(slot.instrument));
155 position.quantity = record.quantity;
156 position.avg_price = record.avg_price;
157 position.realized_pnl = record.realized_pnl;
158 position.realized_fees = record.realized_fees;
159 position.open_fees = record.open_fees;
160 position.multiplier = record.multiplier;
161 position.last_update_time = record.last_update_time;
162 const std::size_t lot_count = std::min<std::size_t>(record.lot_count, MAX_LOTS);
163 visit(static_cast<uint32_t>(i), load_key(slot.strategy_id), position, {record.lots, lot_count});
164 }
165}
166
167uint32_t PositionStore::save(uint32_t slot_index, std::string_view strategy_id, const Position& position,
168 std::span<const PositionLot> lots, BrokerId broker, uint64_t journal_seq) {
169 if (slot_index == NO_SLOT) {
170 while (next_free_ < capacity_ && slot_at(next_free_).state != SLOT_EMPTY) {
171 ++next_free_;
172 }
173 if (next_free_ >= capacity_) {
174 if (!full_logged_) {
175 full_logged_ = true;
176 LOG_ERROR("PositionStore: {} is full ({} positions) - {} {} and any further new position are NOT "
177 "kept across a restart; raise position_store.capacity",
178 path_, capacity_, strategy_id, position.instrument);
179 }
180 return NO_SLOT;
181 }
182 Slot& fresh = slot_at(next_free_);
183 if (!store_key(fresh.strategy_id, strategy_id) || !store_key(fresh.instrument, position.instrument)) {
184 LOG_ERROR("PositionStore: {} {} cannot be kept across a restart - a name is longer than {} characters",
185 strategy_id, position.instrument, MAX_KEY_LENGTH);
186 return NO_SLOT;
187 }
188 slot_index = static_cast<uint32_t>(next_free_++);
189 ++size_;
190 }
191 if (slot_index >= capacity_) {
192 return NO_SLOT;
193 }
194
195 Slot& slot = slot_at(slot_index);
196 // The record that is not current is written whole, then made current by one byte.
197 const uint8_t next_state = slot.state == SLOT_RECORD_0 ? SLOT_RECORD_1 : SLOT_RECORD_0;
198 Record record{};
199 record.quantity = position.quantity;
200 record.avg_price = position.avg_price;
201 record.realized_pnl = position.realized_pnl;
202 record.realized_fees = position.realized_fees;
203 record.open_fees = position.open_fees;
204 record.multiplier = position.multiplier;
205 record.last_update_time = position.last_update_time;
206 if (journal_seq != 0) {
207 record.journal_broker = static_cast<uint8_t>(broker);
208 record.journal_seq = journal_seq;
209 } else if (slot.state == SLOT_RECORD_0 || slot.state == SLOT_RECORD_1) {
210 const Record& current = slot.records[slot.state - SLOT_RECORD_0];
211 record.journal_broker = current.journal_broker;
212 record.journal_seq = current.journal_seq;
213 }
214
215 const std::size_t kept = std::min(lots.size(), MAX_LOTS);
216 std::copy_n(lots.begin(), kept, record.lots);
217 if (lots.size() > MAX_LOTS) {
218 // More lots than a slot holds: the newest are kept as one, at their average price.
219 // FIFO closes the oldest first, so this only matters once those are gone.
220 double quantity = 0.0;
221 double cost = 0.0;
222 for (std::size_t i = MAX_LOTS - 1; i < lots.size(); ++i) {
223 quantity += from_qty_t(lots[i].quantity);
224 cost += from_qty_t(lots[i].quantity) * from_price_t(lots[i].price);
225 }
226 PositionLot& merged = record.lots[MAX_LOTS - 1];
227 merged.quantity = to_qty_t(quantity);
228 merged.price = quantity > 0.0 ? to_price_t(cost / quantity) : lots[MAX_LOTS - 1].price;
229 merged.timestamp = lots[MAX_LOTS - 1].timestamp;
230 if (!lots_logged_) {
231 lots_logged_ = true;
232 LOG_WARN("PositionStore: {} {} has {} open lots; the newest {} are kept as one at their average price",
233 strategy_id, position.instrument, lots.size(), lots.size() - (MAX_LOTS - 1));
234 }
235 }
236 record.lot_count = static_cast<uint32_t>(kept);
237
238 std::memcpy(&slot.records[next_state - SLOT_RECORD_0], &record, sizeof(Record));
239 std::atomic_signal_fence(std::memory_order_seq_cst); // the compiler keeps that order too
240 slot.state = next_state;
241 return slot_index;
242}
243
244void PositionStore::erase_strategy(std::string_view strategy_id) {
245 for (std::size_t i = 0; i < capacity_; ++i) {
246 Slot& slot = slot_at(i);
247 if (slot.state != SLOT_EMPTY && load_key(slot.strategy_id) == strategy_id) {
248 slot.state = SLOT_EMPTY;
249 --size_;
250 next_free_ = std::min(next_free_, i);
251 }
252 }
253}
254
256 for (std::size_t i = 0; i < capacity_; ++i) {
257 slot_at(i).state = SLOT_EMPTY;
258 }
259 size_ = 0;
260 next_free_ = 0;
261}
262
263} // namespace slick::trader
static constexpr uint32_t NO_SLOT
void for_each(const Visitor &visit) const
std::function< void(uint32_t slot, std::string_view strategy_id, const Position &position, std::span< const PositionLot > lots)> Visitor
PositionStore(const std::string &path, std::size_t capacity=DEFAULT_CAPACITY)
void erase_strategy(std::string_view strategy_id)
void mark_journaled(BrokerId broker, uint64_t journal_seq) noexcept
static constexpr std::size_t MAX_BROKERS
static constexpr std::size_t MAX_LOTS
std::size_t capacity() const noexcept
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)
static constexpr std::size_t MAX_KEY_LENGTH
const std::string & path() const noexcept
uint64_t journaled(BrokerId broker) const noexcept
double from_price_t(price_t value)
Definition types.hpp:36
price_t to_price_t(double value)
Definition types.hpp:24
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
qty_t to_qty_t(double value)
Definition types.hpp:32