9#include "../native_calendar_memo.hpp"
22namespace cal = native_calendar;
24constexpr std::int64_t kSecondMs = 1000;
25constexpr std::int64_t kMinuteMs = 60 * kSecondMs;
28std::int64_t fixed_ms(
const cal::Timeframe& tf)
noexcept {
30 case cal::TimeframeUnit::Second:
return tf.count() * kSecondMs;
31 case cal::TimeframeUnit::Minute:
return tf.count() * kMinuteMs;
36Bar one_price(
double price, std::int64_t timestamp)
noexcept {
38 bar.open = bar.high = bar.low = bar.close =
price;
40 bar.timestamp = timestamp;
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:
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";
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);
83 const auto input = cal::parse_timeframe(input_tf);
84 const auto chart = cal::parse_timeframe(script_tf);
86 if (!
input || !chart || !intrabar)
return unchanged;
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))
96 for (
int i = 1; i < n; ++i) {
97 if (bars[i].timestamp <= bars[i - 1].timestamp)
return unchanged;
99 const auto calendar = cal::parse_session(session, timezone);
100 if (!calendar)
return unchanged;
101 cal::SessionDayMemo memo;
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;
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;
122 rows[
static_cast<std::size_t
>(i)] = {chart_at->open_ms, slot_at->open_ms, owner_at->open_ms};
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});
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});
139 slots.back().last = i;
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) {
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;
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) {
159 path.push_back(one_price(chart_first.
open, floor));
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) {
167 intrabar.
low = std::min(intrabar.
low, bars[i].
low);
173 path.push_back(intrabar);
175 if (slots[slot - 1].last < bar.last) {
178 path.push_back(one_price(chart_last.
close, std::max(chart_last.
timestamp, floor)));
186[[noreturn]]
void path_failure(
const char* message) {
188 {{
"option",
"intrabar_path"}}, message);
191[[noreturn]]
void path_invariant(
const char* message) {
195std::int64_t after_stamp(std::int64_t stamp) {
196 if (stamp == std::numeric_limits<std::int64_t>::max())
198 {{
"option",
"intrabar_path"}},
199 "magnifier timestamp exhausted");
206class MagnifierPathSource final :
public NativeLowerPathSource {
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;
215 std::int64_t chart, slot, owner;
219 const MagnifierPathSource* source;
222 cal::SessionDayMemo memo;
223 std::optional<cal::NativeInterval> chart, slot, owner;
225 explicit Rows(
const MagnifierPathSource* value) : source(
value) {}
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; }
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;
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; }
246 row = {chart->open_ms, slot->open_ms, owner->open_ms, at++};
251 std::int64_t key, owner;
258 std::optional<Row> pending;
259 Spans(
const MagnifierPathSource* source,
bool is_slot) : rows(source), slots(is_slot) {}
260 std::optional<Span> next() {
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");
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) {
274 out.last = row.index;
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;
283 if (rows.failed) path_failure(
"magnifier calendar lookup changed after pre-scan");
288 const MagnifierPathSource* source;
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()) {}
296 bool next(Bar& out) {
298 chart = charts.next();
299 if (!chart)
return false;
300 while (slot && slot->owner < chart->key) slot = slots.next();
302 if (!slot || slot->owner != chart->key)
continue;
303 floor = source->input_[chart->first].timestamp;
304 opening = slot->first < chart->first;
309 out = one_price(source->input_[chart->first].open, floor);
310 floor = after_stamp(floor);
312 }
else if (closing) {
313 const Bar& last = source->input_[chart->last];
314 out = one_price(last.close, std::max(last.timestamp, floor));
318 out.timestamp = std::max(out.timestamp, floor);
319 floor = after_stamp(out.timestamp);
320 const int last = slot->last;
322 if (!slot || slot->owner != chart->key) {
323 closing = last < chart->last;
324 if (!closing) active =
false;
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_;
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)
343 count_ =
static_cast<std::size_t
>(n_);
345 const auto input_grid = cal::parse_timeframe(input_tf);
346 chart_tf_ = cal::parse_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)))
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;
361 while (rows.next(row)) {}
362 if (rows.failed)
return;
367 while (cursor.next(bar)) {
368 if (count_ == std::numeric_limits<std::size_t>::max())
370 {{
"option",
"intrabar_path"}},
371 "magnifier path count exhausted");
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");
380 for (
int i = 0; i < n_; ++i)
if (!visitor(context, input_[i]))
return false;
384 while (cursor.next(bar))
if (!visitor(context, bar))
return false;
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_;
395 const Bar* first = input_;
396 const Bar* last = input_;
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);
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);
408 auto candidate = cursor_ ? std::make_unique<Cursor>(*cursor_)
409 : std::make_unique<Cursor>(this);
416 candidate->charts.rows.memo = std::move(cursor_->charts.rows.memo);
417 candidate->slots.rows.memo = std::move(cursor_->slots.rows.memo);
421 for (
const auto& bar : segment_)
422 if (bar.timestamp >= begin) scratch_.push_back(bar);
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);
430 segment_.swap(scratch_);
431 cursor_.swap(candidate);
433 view_ = {segment_.data(), segment_.size()};
440 const Bar* next_after_segment() const noexcept
override {
441 return next_ ? &*next_ :
nullptr;
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);
Base with a code: throw coded<std::invalid_argument>(code, {args}, text).
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...