PineForge unreleased
Deterministic PineScript v6 backtest runtime — C ABI reference
Loading...
Searching...
No Matches
magnifier_intrabars.cpp
Go to the documentation of this file.
1// TradingView's bar-magnifier intrabars (the TradingView intrabar import): the table
2// that picks the intrabar timeframe for a chart, and the lower-timeframe path
3// the Pine adapter hands the kernel's intrabar path for a magnified run.
5
8
9#include "../native_calendar_memo.hpp"
10
11#include <algorithm>
12#include <cstdint>
13#include <limits>
14#include <optional>
15#include <stdexcept>
16#include <utility>
17
18namespace pineforge::source {
19
20namespace {
21
22namespace cal = native_calendar;
23
24constexpr std::int64_t kSecondMs = 1000;
25constexpr std::int64_t kMinuteMs = 60 * kSecondMs;
26
27// A fixed timeframe's duration, or 0 for a calendar one.
28std::int64_t fixed_ms(const cal::Timeframe& tf) noexcept {
29 switch (tf.unit()) {
30 case cal::TimeframeUnit::Second: return tf.count() * kSecondMs;
31 case cal::TimeframeUnit::Minute: return tf.count() * kMinuteMs;
32 default: return 0;
33 }
34}
35
36Bar one_price(double price, std::int64_t timestamp) noexcept {
37 Bar bar{};
38 bar.open = bar.high = bar.low = bar.close = price;
39 bar.volume = 0.0;
40 bar.timestamp = timestamp;
41 return bar;
42}
43
44} // namespace
45
46std::string tradingview_intrabar_timeframe(std::string_view chart_tf) {
47 const auto chart = cal::parse_timeframe(chart_tf);
48 if (!chart || !chart->valid()) return {};
49 std::int64_t seconds = 0;
50 switch (chart->unit()) {
51 case cal::TimeframeUnit::Second: seconds = chart->count(); break;
52 case cal::TimeframeUnit::Minute: seconds = std::int64_t{chart->count()} * 60; break;
53 case cal::TimeframeUnit::Day: seconds = std::int64_t{chart->count()} * 86400; break;
54 case cal::TimeframeUnit::Week:
55 case cal::TimeframeUnit::Month:
56 return "1D";
57 }
58 constexpr std::int64_t kMinute = 60;
59 constexpr std::int64_t kDay = 1440 * kMinute;
60 if (seconds < 30) return "1S";
61 if (seconds < kMinute) return "5S";
62 if (seconds < 5 * kMinute) return "10S";
63 if (seconds < 10 * kMinute) return "30S";
64 if (seconds < 15 * kMinute) return "1";
65 if (seconds < 30 * kMinute) return "2";
66 if (seconds < 60 * kMinute) return "5";
67 if (seconds < 240 * kMinute) return "10";
68 if (seconds < kDay) return "30";
69 if (seconds < 3 * kDay) return "60";
70 if (seconds < 7 * kDay) return "240";
71 return "1D";
72}
73
74std::vector<Bar> tradingview_magnifier_bars(const Bar* bars, int n,
75 const std::string& input_tf,
76 const std::string& script_tf,
77 const std::string& session,
78 const std::string& timezone) {
79 std::vector<Bar> unchanged;
80 if (!bars || n <= 0) return unchanged;
81 unchanged.assign(bars, bars + n);
82
83 const auto input = cal::parse_timeframe(input_tf);
84 const auto chart = cal::parse_timeframe(script_tf);
85 const auto intrabar = cal::parse_timeframe(tradingview_intrabar_timeframe(script_tf));
86 if (!input || !chart || !intrabar) return unchanged;
87 // The intrabars are aggregated from the input, so the input has to be a
88 // strictly finer fixed grid that tiles them: an intrabar of the input's
89 // own timeframe is the input path already, and a finer one (a 1- or
90 // 5-minute chart walks 10- or 30-second bars) cannot be built from it.
91 const std::int64_t input_ms = fixed_ms(*input);
92 const std::int64_t intrabar_ms = fixed_ms(*intrabar);
93 if (input_ms <= 0) return unchanged;
94 if (intrabar_ms != 0 && (intrabar_ms <= input_ms || intrabar_ms % input_ms != 0))
95 return unchanged;
96 for (int i = 1; i < n; ++i) {
97 if (bars[i].timestamp <= bars[i - 1].timestamp) return unchanged;
98 }
99 const auto calendar = cal::parse_session(session, timezone);
100 if (!calendar) return unchanged;
101 cal::SessionDayMemo memo;
102
103 // Every input bar's chart bar, and its intrabar with the chart bar that
104 // owns it -- the one holding the intrabar's last traded instant. Both are
105 // the calendar's own intervals, the ones the kernel aggregates with.
106 struct Row { std::int64_t chart_open; std::int64_t slot_open; std::int64_t owner_open; };
107 std::vector<Row> rows(static_cast<std::size_t>(n));
108 std::optional<cal::NativeInterval> chart_at, slot_at, owner_at;
109 for (int i = 0; i < n; ++i) {
110 const std::int64_t t = bars[i].timestamp;
111 if (!chart_at || t < chart_at->open_ms || t >= chart_at->next_period_open_ms) {
112 chart_at = cal::interval_containing(*calendar, *chart, t, memo);
113 if (!chart_at) return unchanged;
114 }
115 if (!slot_at || t < slot_at->open_ms || t >= slot_at->next_period_open_ms) {
116 slot_at = cal::interval_containing(*calendar, *intrabar, t, memo);
117 if (!slot_at || slot_at->last_traded_close_ms <= slot_at->open_ms) return unchanged;
118 owner_at = cal::interval_containing(*calendar, *chart,
119 slot_at->last_traded_close_ms - 1, memo);
120 if (!owner_at) return unchanged;
121 }
122 rows[static_cast<std::size_t>(i)] = {chart_at->open_ms, slot_at->open_ms, owner_at->open_ms};
123 }
124
125 // Consecutive runs of the input: chart bars, and intrabars with their
126 // owner. Both partitions are time-ordered, and an owner never precedes
127 // the chart bar of its intrabar's first input.
128 struct Span { std::int64_t key; std::int64_t owner; int first; int last; };
129 std::vector<Span> charts, slots;
130 for (int i = 0; i < n; ++i) {
131 const auto& row = rows[static_cast<std::size_t>(i)];
132 if (charts.empty() || charts.back().key != row.chart_open)
133 charts.push_back({row.chart_open, row.chart_open, i, i});
134 else
135 charts.back().last = i;
136 if (slots.empty() || slots.back().key != row.slot_open)
137 slots.push_back({row.slot_open, row.owner_open, i, i});
138 else
139 slots.back().last = i;
140 }
141
142 std::vector<Bar> path;
143 path.reserve(slots.size() + 2 * charts.size());
144 std::size_t slot = 0;
145 for (const auto& bar : charts) {
146 // An intrabar owned by a chart bar the input never reaches has no
147 // chart bar to walk in; TradingView has none either.
148 while (slot < slots.size() && slots[slot].owner < bar.key) ++slot;
149 const std::size_t owned_begin = slot;
150 while (slot < slots.size() && slots[slot].owner == bar.key) ++slot;
151 if (owned_begin == slot) continue; // the kernel walks the chart bar's own OHLC
152 const Bar& chart_first = bars[bar.first];
153 const Bar& chart_last = bars[bar.last];
154 std::int64_t floor = chart_first.timestamp;
155 if (slots[owned_begin].first < bar.first) {
156 // The straddler reaches back into the previous chart bar, so its
157 // open is not this bar's: the path opens at the chart bar's own
158 // open first (where an order placed at the last close fills).
159 path.push_back(one_price(chart_first.open, floor));
160 ++floor;
161 }
162 for (std::size_t s = owned_begin; s < slot; ++s) {
163 const Span& span = slots[s];
164 Bar intrabar = bars[span.first];
165 for (int i = span.first + 1; i <= span.last; ++i) {
166 intrabar.high = std::max(intrabar.high, bars[i].high);
167 intrabar.low = std::min(intrabar.low, bars[i].low);
168 intrabar.close = bars[i].close;
169 intrabar.volume += bars[i].volume;
170 }
171 intrabar.timestamp = std::max(bars[span.first].timestamp, floor);
172 floor = intrabar.timestamp + 1;
173 path.push_back(intrabar);
174 }
175 if (slots[slot - 1].last < bar.last) {
176 // The chart bar's last inputs open a later bar's straddler: the
177 // path still closes at this chart bar's own close.
178 path.push_back(one_price(chart_last.close, std::max(chart_last.timestamp, floor)));
179 }
180 }
181 return path;
182}
183
184namespace {
185
186[[noreturn]] void path_failure(const char* message) {
188 {{"option", "intrabar_path"}}, message);
189}
190
191[[noreturn]] void path_invariant(const char* message) {
192 throw coded<std::logic_error>(RunFailureCode::engine_invariant, {}, message);
193}
194
195std::int64_t after_stamp(std::int64_t stamp) {
196 if (stamp == std::numeric_limits<std::int64_t>::max())
197 throw coded<std::overflow_error>(RunFailureCode::run_options_rejected,
198 {{"option", "intrabar_path"}},
199 "magnifier timestamp exhausted");
200 return stamp + 1;
201}
202
203// All durable fields below are derived cursor/storage state. Identity is the
204// count-first fold of the complete logical path, taken eagerly at configure;
205// caches, cursor positions and buffer addresses introduce no broker state.
206class MagnifierPathSource final : public NativeLowerPathSource {
207 const Bar* input_;
208 int n_;
209 std::optional<cal::Timeframe> chart_tf_, slot_tf_;
210 std::optional<cal::SessionCalendar> calendar_;
211 bool fallback_ = true;
212 std::size_t count_ = 0;
213
214 struct Row {
215 std::int64_t chart, slot, owner;
216 int index;
217 };
218 struct Rows {
219 const MagnifierPathSource* source;
220 int at = 0;
221 bool failed = false;
222 cal::SessionDayMemo memo;
223 std::optional<cal::NativeInterval> chart, slot, owner;
224
225 explicit Rows(const MagnifierPathSource* value) : source(value) {}
226 // Calendar memos are disposable caches, not part of cursor position.
227 Rows(const Rows& other)
228 : source(other.source), at(other.at), failed(other.failed),
229 chart(other.chart), slot(other.slot), owner(other.owner) {}
230 bool next(Row& row) {
231 if (at == source->n_) return false;
232 const auto t = source->input_[at].timestamp;
233 if (!chart || t < chart->open_ms || t >= chart->next_period_open_ms) {
234 chart = cal::interval_containing(*source->calendar_, *source->chart_tf_, t, memo);
235 if (!chart) { failed = true; return false; }
236 }
237 if (!slot || t < slot->open_ms || t >= slot->next_period_open_ms) {
238 slot = cal::interval_containing(*source->calendar_, *source->slot_tf_, t, memo);
239 if (!slot || slot->last_traded_close_ms <= slot->open_ms) {
240 failed = true; return false;
241 }
242 owner = cal::interval_containing(*source->calendar_, *source->chart_tf_,
243 slot->last_traded_close_ms - 1, memo);
244 if (!owner) { failed = true; return false; }
245 }
246 row = {chart->open_ms, slot->open_ms, owner->open_ms, at++};
247 return true;
248 }
249 };
250 struct Span {
251 std::int64_t key, owner;
252 int first, last;
253 Bar value;
254 };
255 struct Spans {
256 Rows rows;
257 bool slots;
258 std::optional<Row> pending;
259 Spans(const MagnifierPathSource* source, bool is_slot) : rows(source), slots(is_slot) {}
260 std::optional<Span> next() {
261 Row row{};
262 if (pending) { row = *pending; pending.reset(); }
263 else if (!rows.next(row)) {
264 if (rows.failed) path_failure("magnifier calendar lookup changed after pre-scan");
265 return std::nullopt;
266 }
267 Span out{slots ? row.slot : row.chart, slots ? row.owner : row.chart,
268 row.index, row.index, rows.source->input_[row.index]};
269 while (rows.next(row)) {
270 if ((slots ? row.slot : row.chart) != out.key) {
271 pending = row;
272 break;
273 }
274 out.last = row.index;
275 if (slots) {
276 const Bar& bar = rows.source->input_[row.index];
277 out.value.high = std::max(out.value.high, bar.high);
278 out.value.low = std::min(out.value.low, bar.low);
279 out.value.close = bar.close;
280 out.value.volume += bar.volume;
281 }
282 }
283 if (rows.failed) path_failure("magnifier calendar lookup changed after pre-scan");
284 return out;
285 }
286 };
287 struct Cursor {
288 const MagnifierPathSource* source;
289 Spans charts, slots;
290 std::optional<Span> chart, slot;
291 std::int64_t floor = 0;
292 bool active = false, opening = false, closing = false;
293 explicit Cursor(const MagnifierPathSource* value)
294 : source(value), charts(value, false), slots(value, true), slot(slots.next()) {}
295
296 bool next(Bar& out) {
297 while (!active) {
298 chart = charts.next();
299 if (!chart) return false;
300 while (slot && slot->owner < chart->key) slot = slots.next();
301 // No owned slot: the kernel walks this chart bar's own OHLC.
302 if (!slot || slot->owner != chart->key) continue;
303 floor = source->input_[chart->first].timestamp;
304 opening = slot->first < chart->first;
305 closing = false;
306 active = true;
307 }
308 if (opening) {
309 out = one_price(source->input_[chart->first].open, floor);
310 floor = after_stamp(floor);
311 opening = false;
312 } else if (closing) {
313 const Bar& last = source->input_[chart->last];
314 out = one_price(last.close, std::max(last.timestamp, floor));
315 active = false;
316 } else {
317 out = slot->value;
318 out.timestamp = std::max(out.timestamp, floor);
319 floor = after_stamp(out.timestamp);
320 const int last = slot->last;
321 slot = slots.next();
322 if (!slot || slot->owner != chart->key) {
323 closing = last < chart->last;
324 if (!closing) active = false;
325 }
326 }
327 return true;
328 }
329 };
330
331 bool selected_ = false;
332 std::int64_t begin_ = 0, end_ = 0;
333 NativeBarView view_{nullptr, 0};
334 std::vector<Bar> segment_, scratch_;
335 std::unique_ptr<Cursor> cursor_;
336 std::optional<Bar> next_;
337
338public:
339 MagnifierPathSource(const Bar* input, int n, const std::string& input_tf,
340 const std::string& script_tf, const std::string& session,
341 const std::string& timezone)
342 : input_(input), n_(input && n > 0 ? n : 0) {
343 count_ = static_cast<std::size_t>(n_);
344 if (n_ == 0) return;
345 const auto input_grid = cal::parse_timeframe(input_tf);
346 chart_tf_ = cal::parse_timeframe(script_tf);
347 slot_tf_ = cal::parse_timeframe(tradingview_intrabar_timeframe(script_tf));
348 if (!input_grid || !chart_tf_ || !slot_tf_) return;
349 const auto input_ms = fixed_ms(*input_grid);
350 const auto slot_ms = fixed_ms(*slot_tf_);
351 if (input_ms <= 0 || (slot_ms != 0 && (slot_ms <= input_ms || slot_ms % input_ms != 0)))
352 return;
353 for (int i = 1; i < n_; ++i)
354 if (input_[i].timestamp <= input_[i - 1].timestamp) return;
355 calendar_ = cal::parse_session(session, timezone);
356 if (!calendar_) return;
357 // A failure anywhere means today's ENTIRE unchanged input. Decide
358 // before the count/digest can emit even one aggregated row.
359 Rows rows(this);
360 Row row{};
361 while (rows.next(row)) {}
362 if (rows.failed) return;
363 fallback_ = false;
364 count_ = 0;
365 Cursor cursor(this);
366 Bar bar{};
367 while (cursor.next(bar)) {
368 if (count_ == std::numeric_limits<std::size_t>::max())
369 throw coded<std::overflow_error>(RunFailureCode::run_options_rejected,
370 {{"option", "intrabar_path"}},
371 "magnifier path count exhausted");
372 ++count_;
373 }
374 }
375
376 std::size_t count() const override { return count_; }
377 bool for_each(Visitor visitor, void* context) const override {
378 if (visitor == nullptr) path_invariant("null magnifier visitor");
379 if (fallback_) {
380 for (int i = 0; i < n_; ++i) if (!visitor(context, input_[i])) return false;
381 } else {
382 Cursor cursor(this);
383 Bar bar{};
384 while (cursor.next(bar)) if (!visitor(context, bar)) return false;
385 }
386 return true;
387 }
388
389 NativeBarView segment(std::int64_t begin, std::int64_t end) override {
390 if (end < begin || (selected_ && (begin < begin_ || end < end_)))
391 path_invariant("magnifier window moved backwards");
392 if (selected_ && begin == begin_ && end == end_) return view_;
393 if (fallback_) {
394 // Fallback is the input view itself: no path allocation or copy.
395 const Bar* first = input_;
396 const Bar* last = input_;
397 if (n_ != 0) {
398 const auto less = [](const Bar& bar, std::int64_t t) { return bar.timestamp < t; };
399 first = std::lower_bound(input_, input_ + n_, begin, less);
400 last = std::lower_bound(first, input_ + n_, end, less);
401 }
402 view_ = {first, n_ == 0 ? 0 : static_cast<std::size_t>(last - first)};
403 next_ = n_ == 0 || last == input_ + n_ ? std::nullopt : std::optional<Bar>(*last);
404 } else {
405 // A candidate cursor and second reusable buffer make publication
406 // atomic. Keep overlap rows from the previous window, then append
407 // only new rows; look-ahead is a distinct single-bar buffer.
408 auto candidate = cursor_ ? std::make_unique<Cursor>(*cursor_)
409 : std::make_unique<Cursor>(this);
410 // The copy carries position only. Hand the candidate what the
411 // published cursor's calendar memos have resolved, or every window
412 // binds two memos and resolves its session days again. A candidate
413 // that fails takes them with it: the published cursor keeps its
414 // position, and the next candidate starts from empty memos.
415 if (cursor_) {
416 candidate->charts.rows.memo = std::move(cursor_->charts.rows.memo);
417 candidate->slots.rows.memo = std::move(cursor_->slots.rows.memo);
418 }
419 auto next = next_;
420 scratch_.clear();
421 for (const auto& bar : segment_)
422 if (bar.timestamp >= begin) scratch_.push_back(bar);
423 Bar bar{};
424 for (;;) {
425 if (next) { bar = *next; next.reset(); }
426 else if (!candidate->next(bar)) break;
427 if (bar.timestamp >= end) { next = bar; break; }
428 if (bar.timestamp >= begin) scratch_.push_back(bar);
429 }
430 segment_.swap(scratch_);
431 cursor_.swap(candidate);
432 next_ = next;
433 view_ = {segment_.data(), segment_.size()};
434 }
435 begin_ = begin;
436 end_ = end;
437 selected_ = true;
438 return view_;
439 }
440 const Bar* next_after_segment() const noexcept override {
441 return next_ ? &*next_ : nullptr;
442 }
443};
444
445} // namespace
446
447std::unique_ptr<NativeLowerPathSource> make_magnifier_path_source(
448 const Bar* bars, int n, const std::string& input_tf,
449 const std::string& script_tf, const std::string& session,
450 const std::string& timezone) {
451 return std::make_unique<MagnifierPathSource>(bars, n, input_tf, script_tf, session, timezone);
452}
453
454} // namespace pineforge::source
Base with a code: throw coded<std::invalid_argument>(code, {args}, text).
int t(int64_t c)
Definition color.hpp:45
std::unique_ptr< NativeLowerPathSource > make_magnifier_path_source(const Bar *bars, int n, const std::string &input_tf, const std::string &script_tf, const std::string &session, const std::string &timezone)
The same logical path without retaining the input or a whole-run path.
std::vector< Bar > tradingview_magnifier_bars(const Bar *bars, int n, const std::string &input_tf, const std::string &script_tf, const std::string &session, const std::string &timezone)
The lower-timeframe path TradingView's bar magnifier walks for every chart bar of a run whose chart b...
std::string tradingview_intrabar_timeframe(std::string_view chart_tf)
The intrabar timeframe TradingView's bar magnifier walks on a chart of chart_tf, from the table in Tr...
double open
Definition bar.hpp:7
double close
Definition bar.hpp:7
double low
Definition bar.hpp:7
double volume
Definition bar.hpp:7
int64_t timestamp
Definition bar.hpp:8
double high
Definition bar.hpp:7