PineForge unreleased
Deterministic PineScript v6 backtest runtime — C ABI reference
Loading...
Searching...
No Matches
pine_ta_series_osc.hpp
Go to the documentation of this file.
1#pragma once
2// TradingView's oscillator and momentum ta.* calls whose length is a series:
3// ta.stoch, ta.cci, ta.mfi, ta.mom, ta.roc, ta.cmo, ta.wpr, ta.cog, ta.rising
4// and ta.falling.
5//
6// TradingView compiles each of these ten functions with a length that changes
7// from bar to bar (observed on synthetic scripts, one call per script). The
8// fixed-length classes of <pineforge/ta.hpp> size their window in the
9// constructor, so they cannot take such a length. The classes below take the
10// length on every call, as SeriesSma of <pineforge/source/pine_ta_length.hpp>
11// does, and share its shape: a default constructor and one taking a
12// WindowCacheCapacity, compute(<inputs>, length), recompute(<inputs>, length)
13// and observe_owned_storage. The inputs are the ones the fixed-length class
14// takes, in the same order; the length is always the last argument.
15//
16// The rule of every class: a call answers what the fixed-length call answers
17// for the length of that call, on the inputs the site has received so far.
18// A length that stays constant therefore gives the fixed-length class's
19// values on every bar, bit for bit, na bars included, for a site that
20// executes on every bar. The values TradingView gives after the length
21// changes are not recorded for these ten functions: the rule above is the
22// definition of each function applied to the last `length` bars.
23//
24// The fixed-length call is the Pine call's. For ta.mfi and ta.cci that is
25// the source layer's own type, PineMfi (pine_ta_length.hpp) and PineCci
26// (<pineforge/source/pine_ta_cci.hpp>). Each answers one case differently
27// from ta::MFI and ta::CCI, and SeriesMfi and SeriesCci answer that case as
28// the two types do (their bullets below).
29//
30// Which inputs a class keeps, and what an na input does, follow the
31// fixed-length class of the same function:
32//
33// * SeriesMom, SeriesRoc: one position per call, na included. The answer
34// reads the position `length` calls back and is na when that position or
35// the current source is na (`source - source[length]`, and
36// `(source - source[length]) / source[length] * 100` with na for a zero
37// `source[length]`). On a source with no na after its first value this is
38// ta::Mom and ta::ROC bit for bit; after an na bar those two classes read
39// the length-th previous present sample instead, and the positional rule
40// here is the one of Pine's history subscript.
41// * SeriesRising, SeriesFalling: the last `length + 1` non-na sources, as
42// ta::Rising and ta::Falling keep them. An na source answers 0 and records
43// nothing. The answer is 1 when every consecutive pair of that window
44// rises (falls) strictly, else 0; the result type is the double those two
45// classes return.
46// * SeriesCci: the last `length` non-na sources, as ta::CCI keeps them. An na
47// source answers na and records nothing. A window whose mean deviation is
48// zero up to rounding (inside the comparison band) answers 0, as PineCci
49// answers it.
50// * SeriesCog: one position per call, na included, as ta::COG keeps them; an
51// na inside the window makes the answer na.
52// * SeriesCmo, SeriesMfi: one position per call, na included. The answer sums
53// the last `length` bar-to-bar moves (ta::CMO) or money flows (ta::MFI) and
54// is na until `length` earlier calls exist. A move out of an na source
55// counts as zero, as in the two classes. SeriesMfi has one value before
56// that, PineMfi's first value: the call that completes the site's first
57// `length` calls counts the first call's flow on both sides.
58// * SeriesStoch, SeriesWpr: the highest high and the lowest low of the last
59// `length` bars come from SeriesWindowExtreme, the series-length rule of
60// ta.highest and ta.lowest, where ta::Stoch and ta::WPR read ta::Highest
61// and ta::Lowest. For a site that executes on every bar the two rules give
62// the same extremes for a constant length. A site inside an `if` follows
63// SeriesWindowExtreme's held history, not the fixed classes' ring.
64//
65// The length is checked before anything is recorded, as SeriesSma checks it:
66// an na or non-finite length stops the run ("... It must not be na"), a
67// length below 1 stops it ("... It must be > 0."), a finite fraction
68// truncates toward zero, and a configured lookback cap refuses a length
69// whose `length - 1` exceeds it. The texts name the function without "ta.".
70// A failed check changes nothing, so the next call starts from the same
71// state.
72//
73// recompute() replaces the call made last: it starts from the state that
74// call found, whatever its length was. A recompute() before the first
75// compute() is that first compute().
76//
77// History is kept whole by default, or bounded by the lookback cap when the
78// host sets one (enough for every length the cap admits). Storage is
79// copy-on-write; the cache capacity controls residency only.
80//
81// The arithmetic is inline and is meant to be compiled with the flags the
82// library exports (-ffp-contract=off): ta.cog's weighted sum must not be
83// contracted into a fused multiply-add if it is to equal ta::COG's.
86#include <pineforge/na.hpp>
88#include <pineforge/series.hpp>
90
91#include <algorithm>
92#include <cmath>
93#include <cstddef>
94#include <cstdint>
95#include <limits>
96#include <stdexcept>
97#include <string>
98#include <utility>
99
100namespace pineforge {
101namespace source {
102
104
105inline constexpr std::size_t kMaxHistorySlots =
106 std::numeric_limits<std::size_t>::max() / sizeof(double);
107
108[[noreturn]] inline void lookback_exceeded(std::uint64_t offset, std::int64_t maximum,
109 bool beyond_uint64) {
112 {{"limit", "max_bars_back"}, {"max", maximum}},
114 "The script attempts to reference historical data that is too far from "
115 "the current bar (" + (beyond_uint64 ? "more than " : "") +
116 std::to_string(offset) + " bars back). The historical buffer's limit is " +
117 std::to_string(maximum) + " bars.");
118}
119
120// The length of one call as the unsigned count it names, checked the way
121// SeriesSma checks its own: the same rules, codes and texts, with this
122// function's name.
123inline std::uint64_t checked_length(double length, const char* function,
124 std::int64_t maximum) {
125 if (!std::isfinite(length)) {
128 {{"function", function}, {"argument", "length"}, {"rule", "must_not_be_na"}},
129 run_error_bar_prefix() + "Invalid value of the 'length' argument in the '" +
130 function + "' function. It must not be na");
131 }
132 if (!(length >= 1.0)) {
133 // Truncated toward zero, saturating far outside any window.
134 const double truncated = std::trunc(length);
135 const long long shown = truncated < -1e15 ? static_cast<long long>(-1e15)
136 : static_cast<long long>(truncated);
139 {{"function", function}, {"argument", "length"}, {"rule", "must_be_positive"}},
140 run_error_bar_prefix() + "Invalid value of the 'length' argument (" +
141 std::to_string(shown) + ") in the '" + function +
142 "' function. It must be > 0.");
143 }
144 if (length >= 0x1p64) {
145 constexpr auto last = std::numeric_limits<std::uint64_t>::max();
146 if (maximum != 0) lookback_exceeded(last, maximum, length > 0x1p64);
147 return last;
148 }
149 // The unsigned conversion preserves the integer part, including 2^63.
150 const auto requested = static_cast<std::uint64_t>(length);
151 if (maximum != 0 && requested - 1 > static_cast<std::uint64_t>(maximum))
152 lookback_exceeded(requested - 1, maximum, false);
153 return requested;
154}
155
156// How many values a history keeps under the lookback cap `maximum`: enough
157// for the longest length the cap admits (`maximum + 1`) plus `extra` older
158// values the function reads behind its window. 0 keeps every value: no cap,
159// or a cap beyond addressable storage, which cannot cause an eviction.
160inline std::size_t history_slots(std::int64_t maximum, std::size_t extra) {
161 const auto cap = static_cast<std::uint64_t>(maximum);
162 if (maximum == 0 || cap >= kMaxHistorySlots - extra) return 0;
163 return static_cast<std::size_t>(cap) + 1 + extra;
164}
165
166// The values one call site has recorded, oldest first: all of them, or the
167// newest `limit`. undo() takes back the value recorded last and brings back
168// the one it pushed out, so a recompute() starts from what its bar found.
169class History {
170public:
171 static constexpr std::size_t kChunk = 1024;
172
173 History(WindowCacheCapacity cache, std::size_t limit) : values_(cache), limit_(limit) {}
174 // Copy even from an rvalue: the counts still name the source's storage.
175 History(const History&) = default;
176 History& operator=(const History&) = default;
177
178 std::size_t size() const noexcept { return count_; }
179
180 // The value `back` records before the newest one; `back` < size().
181 double newest(std::size_t back) const {
182 const std::size_t offset = back + 1;
183 return values_.read(offset <= next_ ? next_ - offset
184 : values_.size() - (offset - next_));
185 }
186
187 void push(double value) {
188 if (limit_ != 0 && count_ == limit_) {
189 // Full: the oldest value leaves and is kept for undo().
190 const double oldest = values_.read(next_);
191 values_.write(next_, value);
192 evicted_value_ = oldest;
193 evicted_ = true;
194 next_ = next_ + 1 == limit_ ? 0 : next_ + 1;
195 } else {
196 if (next_ == values_.size()) grow(count_ + 1);
197 values_.write(next_, value);
198 evicted_ = false;
199 ++count_;
200 ++next_;
201 if (count_ == limit_) next_ = 0;
202 }
203 pushed_ = true;
204 }
205
206 // The call recorded nothing: there is nothing for undo() to take back.
207 void skip() noexcept { pushed_ = false; }
208
209 void undo() {
210 if (!pushed_) return;
211 if (evicted_) {
212 const std::size_t slot = next_ == 0 ? limit_ - 1 : next_ - 1;
213 values_.write(slot, evicted_value_);
214 next_ = slot;
215 } else {
216 next_ = (next_ == 0 ? values_.size() : next_) - 1;
217 --count_;
218 }
219 pushed_ = false;
220 }
221
222 void observe_owned_storage(OwnedStorage& out) const noexcept {
223 values_.observe_owned_storage(out);
224 }
225
226private:
227 // Storage grows only before it has ever been full, so the values still
228 // sit in slots [0, count_) and keep their indices in the copy.
229 void grow(std::size_t minimum) {
230 if (minimum > kMaxHistorySlots) {
232 RunFailureCode::scratch_capacity_exceeded, {{"resource", "layout"}},
233 "history byte extent is not representable");
234 }
235 const std::size_t current = values_.size();
236 std::size_t wanted = kChunk;
237 if (current != 0)
238 wanted = current > kMaxHistorySlots / 2 ? kMaxHistorySlots : 2 * current;
239 wanted = std::max(wanted, minimum);
240 wanted = std::min(wanted, limit_ != 0 ? limit_ : kMaxHistorySlots);
242 values_.cache_capacity());
243 for (std::size_t i = 0; i < count_; ++i) next.write(i, values_.read(i));
244 values_ = std::move(next);
245 }
246
247 ::pineforge::detail::WindowValues<double> values_;
248 std::size_t limit_; // 0: every value is kept
249 std::size_t next_ = 0; // slot of the next write
250 std::size_t count_ = 0; // values held
251 bool pushed_ = false; // the last call recorded a value
252 bool evicted_ = false; // ... and that value pushed the oldest one out
253 double evicted_value_ = na<double>();
254};
255
256// One position per call, na included. False while fewer than `length`
257// earlier positions exist; otherwise `previous` is the value `length`
258// positions back, na if that position holds na.
259inline bool lagged(History& history, double source, std::uint64_t length, bool replace,
260 double& previous) {
261 if (replace) history.undo();
262 history.push(source);
263 if (history.size() <= length) return false;
264 previous = history.newest(static_cast<std::size_t>(length));
265 return true;
266}
267
268// The last `count` non-na sources including this one. False when the source
269// is na (nothing is recorded) or fewer than `count` are held.
270inline bool present_window(History& history, double source, std::uint64_t count,
271 bool replace) {
272 if (replace) history.undo();
273 if (is_na(source)) {
274 history.skip();
275 return false;
276 }
277 history.push(source);
278 return history.size() >= count;
279}
280
281} // namespace series_osc_detail
282
283// ta.stoch(source, high, low, length) with a series length:
284// 100 * (source - lowest(low, length)) / (highest(high, length) - lowest(low, length)),
285// the multiplication first, na when either extreme or the source is na and
286// na on a zero range, as ta::Stoch answers.
288public:
290 explicit SeriesStoch(WindowCacheCapacity cache) : highest_(cache), lowest_(cache) {}
291 double compute(double source, double high, double low, double length) {
292 return update(source, high, low, length, true);
293 }
294 double recompute(double source, double high, double low, double length) {
295 return update(source, high, low, length, false);
296 }
297 void observe_owned_storage(OwnedStorage& out) const noexcept {
298 highest_.observe_owned_storage(out);
299 lowest_.observe_owned_storage(out);
300 }
301
302private:
303 double update(double source, double high, double low, double length, bool advance) {
304 // Checked once here, so neither window moves on a refused length.
305 (void)series_osc_detail::checked_length(length, "stoch", max_lookback_);
306 const double hi = highest_.update_series(high, length, advance, true, "stoch").value;
307 const double lo = lowest_.update_series(low, length, advance, false, "stoch").value;
308 if (is_na(hi) || is_na(lo) || is_na(source)) return na<double>();
309 const double range = hi - lo;
310 if (range == 0.0) return na<double>();
311 return 100.0 * (source - lo) / range;
312 }
313
314 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
315 SeriesWindowExtreme highest_;
316 SeriesWindowExtreme lowest_;
317};
318
319// ta.wpr(length) with a series length:
320// (highest(high, length) - close) / (highest(high, length) - lowest(low, length)) * -100,
321// na when either extreme is na or the two are equal, as ta::WPR answers. The
322// inputs are the three ta::WPR takes, in its order: close, high, low.
324public:
326 explicit SeriesWpr(WindowCacheCapacity cache) : highest_(cache), lowest_(cache) {}
327 double compute(double close, double high, double low, double length) {
328 return update(close, high, low, length, true);
329 }
330 double recompute(double close, double high, double low, double length) {
331 return update(close, high, low, length, false);
332 }
333 void observe_owned_storage(OwnedStorage& out) const noexcept {
334 highest_.observe_owned_storage(out);
335 lowest_.observe_owned_storage(out);
336 }
337
338private:
339 double update(double close, double high, double low, double length, bool advance) {
340 (void)series_osc_detail::checked_length(length, "wpr", max_lookback_);
341 const double hh = highest_.update_series(high, length, advance, true, "wpr").value;
342 const double ll = lowest_.update_series(low, length, advance, false, "wpr").value;
343 if (is_na(hh) || is_na(ll) || hh == ll) return na<double>();
344 return (hh - close) / (hh - ll) * -100.0;
345 }
346
347 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
348 SeriesWindowExtreme highest_;
349 SeriesWindowExtreme lowest_;
350};
351
352// ta.cci(source, length) with a series length, over the last `length` non-na
353// sources: (source - mean) / (0.015 * mean absolute deviation) in ta::CCI's
354// operation order (both sums oldest first), and 0 on a deviation that is
355// zero up to rounding: at most 1e-10 from zero, the comparison band of
356// <pineforge/ta_compare_band.hpp>. That is the rule of PineCci
357// (<pineforge/source/pine_ta_cci.hpp>), the Pine call's fixed-length type:
358// identical values such as three of 0.1 leave a deviation of one rounding
359// step, on which the quotient would read about -66.67. The deviation tested
360// here is the one ta::Dev gives PineCci: the same window, summed in the same
361// order.
363public:
366 : history_(cache, series_osc_detail::history_slots(max_lookback_, 0)) {}
367 double compute(double source, double length) { return update(source, length, false); }
368 double recompute(double source, double length) { return update(source, length, true); }
369 void observe_owned_storage(OwnedStorage& out) const noexcept {
370 history_.observe_owned_storage(out);
371 }
372
373private:
374 double update(double source, double length, bool replace) {
375 const std::uint64_t n = series_osc_detail::checked_length(length, "cci", max_lookback_);
376 if (!series_osc_detail::present_window(history_, source, n, replace))
377 return na<double>();
378 const auto count = static_cast<std::size_t>(n);
379 double sum = 0.0;
380 for (std::size_t back = count; back > 0; --back) sum += history_.newest(back - 1);
381 const double mean = sum / static_cast<double>(n);
382 double md_sum = 0.0;
383 for (std::size_t back = count; back > 0; --back)
384 md_sum += std::abs(history_.newest(back - 1) - mean);
385 const double mean_dev = md_sum / static_cast<double>(n);
386 if (float_band_eq(mean_dev, 0.0)) return 0.0;
387 return (source - mean) / (0.015 * mean_dev);
388 }
389
390 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
392};
393
394// ta.mfi(series, length) with a series length. The inputs are the two
395// ta::MFI takes, in its order: the source, then the bar's volume. Each call
396// has a money flow `source * volume`, positive when the source is above the
397// previous call's source by more than the comparison band, negative when it
398// is below by more than the band, zero otherwise and after an na source.
399// The answer is 100 - 100 / (1 + positive sum / negative sum) over the last
400// `length` flows, summed oldest first, 100 on a zero negative sum, and na
401// until `length` earlier calls exist, with one exception: the call that
402// completes the site's first `length` calls has the first value of PineMfi
403// (pine_ta_length.hpp), the Pine call's fixed-length type. The first call
404// has no call before it and counts its flow on both sides; the other calls
405// count by direction as above; each side is summed oldest first. An na sum
406// answers na and a zero negative sum 100. One call later the window no
407// longer holds the first call, and the answer is ta::MFI's. With a length
408// that changes, every call that finds exactly `length` calls recorded, its
409// own included, is such a call.
411public:
414 : sources_(cache, series_osc_detail::history_slots(max_lookback_, 1)),
415 volumes_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
416 double compute(double source, double volume, double length) {
417 return update(source, volume, length, false);
418 }
419 double recompute(double source, double volume, double length) {
420 return update(source, volume, length, true);
421 }
422 void observe_owned_storage(OwnedStorage& out) const noexcept {
423 sources_.observe_owned_storage(out);
424 volumes_.observe_owned_storage(out);
425 }
426
427private:
428 double update(double source, double volume, double length, bool replace) {
429 const std::uint64_t n = series_osc_detail::checked_length(length, "mfi", max_lookback_);
430 if (replace) {
431 sources_.undo();
432 volumes_.undo();
433 }
434 sources_.push(source);
435 volumes_.push(volume);
436 if (sources_.size() < n) return na<double>();
437 const auto count = static_cast<std::size_t>(n);
438 if (sources_.size() == count) return first_value(count);
439 double pos_sum = 0, neg_sum = 0;
440 double previous = sources_.newest(count);
441 for (std::size_t back = count; back > 0; --back) {
442 const double src = sources_.newest(back - 1);
443 double pos = 0, neg = 0;
444 if (!is_na(previous)) {
445 const double flow = src * volumes_.newest(back - 1);
446 if (float_band_gt(src, previous)) pos = flow;
447 else if (float_band_lt(src, previous)) neg = flow;
448 }
449 pos_sum += pos;
450 neg_sum += neg;
451 previous = src;
452 }
453 if (neg_sum == 0) return 100.0;
454 return 100.0 - 100.0 / (1.0 + pos_sum / neg_sum);
455 }
456
457 // The call that completes the first `count` calls, which are all the
458 // calls recorded (a lookback cap keeps one more than its longest
459 // length): PineMfi's first value, statement for statement.
460 double first_value(std::size_t count) const {
461 double previous = sources_.newest(count - 1);
462 double upper = previous * volumes_.newest(count - 1);
463 double lower = upper;
464 for (std::size_t back = count - 1; back > 0; --back) {
465 const double src = sources_.newest(back - 1);
466 const double flow = src * volumes_.newest(back - 1);
467 if (float_band_gt(src, previous)) upper += flow;
468 else if (float_band_lt(src, previous)) lower += flow;
469 previous = src;
470 }
471 if (is_na(upper) || is_na(lower)) return na<double>();
472 if (lower == 0) return 100.0;
473 return 100.0 - 100.0 / (1.0 + upper / lower);
474 }
475
476 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
477 series_osc_detail::History sources_;
478 series_osc_detail::History volumes_;
479};
480
481// ta.mom(source, length) with a series length: `source - source[length]`,
482// positions counted one per call, na included.
484public:
487 : history_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
488 double compute(double source, double length) { return update(source, length, false); }
489 double recompute(double source, double length) { return update(source, length, true); }
490 void observe_owned_storage(OwnedStorage& out) const noexcept {
491 history_.observe_owned_storage(out);
492 }
493
494private:
495 double update(double source, double length, bool replace) {
496 const std::uint64_t n = series_osc_detail::checked_length(length, "mom", max_lookback_);
497 double previous = na<double>();
498 if (!series_osc_detail::lagged(history_, source, n, replace, previous) ||
499 is_na(source) || is_na(previous)) {
500 return na<double>();
501 }
502 return source - previous;
503 }
504
505 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
506 series_osc_detail::History history_;
507};
508
509// ta.roc(source, length) with a series length:
510// `(source - source[length]) / source[length] * 100` in ta::ROC's operation
511// order, na for a zero `source[length]`, positions counted as SeriesMom
512// counts them.
514public:
517 : history_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
518 double compute(double source, double length) { return update(source, length, false); }
519 double recompute(double source, double length) { return update(source, length, true); }
520 void observe_owned_storage(OwnedStorage& out) const noexcept {
521 history_.observe_owned_storage(out);
522 }
523
524private:
525 double update(double source, double length, bool replace) {
526 const std::uint64_t n = series_osc_detail::checked_length(length, "roc", max_lookback_);
527 double previous = na<double>();
528 if (!series_osc_detail::lagged(history_, source, n, replace, previous) ||
529 is_na(source) || is_na(previous) || previous == 0.0) {
530 return na<double>();
531 }
532 return (source - previous) / previous * 100.0;
533 }
534
535 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
536 series_osc_detail::History history_;
537};
538
539// ta.cmo(series, length) with a series length. Each call has an upward move
540// (the source's rise over the previous call's source) and a downward move
541// (its fall, or minus a zero or na difference, as ta::CMO stores it); both
542// are zero after an na source. The answer is 100 * (up - down) / (up + down)
543// over the last `length` moves, summed oldest first, na on a zero total and
544// na until `length` earlier calls exist.
546public:
549 : history_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
550 double compute(double source, double length) { return update(source, length, false); }
551 double recompute(double source, double length) { return update(source, length, true); }
552 void observe_owned_storage(OwnedStorage& out) const noexcept {
553 history_.observe_owned_storage(out);
554 }
555
556private:
557 double update(double source, double length, bool replace) {
558 const std::uint64_t n = series_osc_detail::checked_length(length, "cmo", max_lookback_);
559 if (replace) history_.undo();
560 history_.push(source);
561 if (history_.size() <= n) return na<double>();
562 const auto count = static_cast<std::size_t>(n);
563 double up_sum = 0, down_sum = 0;
564 double previous = history_.newest(count);
565 for (std::size_t back = count; back > 0; --back) {
566 const double src = history_.newest(back - 1);
567 double up = 0, down = 0;
568 if (!is_na(previous)) {
569 const double diff = src - previous;
570 if (diff > 0) up = diff;
571 else down = -diff;
572 }
573 up_sum += up;
574 down_sum += down;
575 previous = src;
576 }
577 const double denom = up_sum + down_sum;
578 if (denom == 0) return na<double>();
579 return 100.0 * (up_sum - down_sum) / denom;
580 }
581
582 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
583 series_osc_detail::History history_;
584};
585
586// ta.cog(source, length) with a series length, over the last `length` calls:
587// minus the sum of source[i] * (i + 1), newest first, over the sum of the
588// sources, oldest first, as ta::COG adds them; na on a zero sum and until
589// `length` calls exist.
591public:
594 : history_(cache, series_osc_detail::history_slots(max_lookback_, 0)) {}
595 double compute(double source, double length) { return update(source, length, false); }
596 double recompute(double source, double length) { return update(source, length, true); }
597 void observe_owned_storage(OwnedStorage& out) const noexcept {
598 history_.observe_owned_storage(out);
599 }
600
601private:
602 double update(double source, double length, bool replace) {
603 const std::uint64_t n = series_osc_detail::checked_length(length, "cog", max_lookback_);
604 if (replace) history_.undo();
605 history_.push(source);
606 if (history_.size() < n) return na<double>();
607 const auto count = static_cast<std::size_t>(n);
608 double num = 0, den = 0;
609 for (std::size_t i = 0; i < count; ++i) {
610 num += history_.newest(i) * static_cast<double>(i + 1);
611 den += history_.newest(count - 1 - i);
612 }
613 if (den == 0) return na<double>();
614 return -num / den;
615 }
616
617 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
618 series_osc_detail::History history_;
619};
620
621// ta.rising(source, length) with a series length: 1 when the last
622// `length + 1` non-na sources rise strictly from each one to the next, else
623// 0; 0 on an na source and until that many sources exist.
625public:
628 : history_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
629 double compute(double source, double length) { return update(source, length, false); }
630 double recompute(double source, double length) { return update(source, length, true); }
631 void observe_owned_storage(OwnedStorage& out) const noexcept {
632 history_.observe_owned_storage(out);
633 }
634
635private:
636 double update(double source, double length, bool replace) {
637 const std::uint64_t n =
638 series_osc_detail::checked_length(length, "rising", max_lookback_);
639 // `length + 1` sources: more than `length` of them.
640 if (!series_osc_detail::present_window(history_, source, 1, replace) ||
641 history_.size() <= n) {
642 return 0.0;
643 }
644 for (auto back = static_cast<std::size_t>(n); back > 0; --back) {
645 if (history_.newest(back - 1) <= history_.newest(back)) return 0.0;
646 }
647 return 1.0;
648 }
649
650 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
651 series_osc_detail::History history_;
652};
653
654// ta.falling(source, length) with a series length: SeriesRising's mirror.
656public:
659 : history_(cache, series_osc_detail::history_slots(max_lookback_, 1)) {}
660 double compute(double source, double length) { return update(source, length, false); }
661 double recompute(double source, double length) { return update(source, length, true); }
662 void observe_owned_storage(OwnedStorage& out) const noexcept {
663 history_.observe_owned_storage(out);
664 }
665
666private:
667 double update(double source, double length, bool replace) {
668 const std::uint64_t n =
669 series_osc_detail::checked_length(length, "falling", max_lookback_);
670 if (!series_osc_detail::present_window(history_, source, 1, replace) ||
671 history_.size() <= n) {
672 return 0.0;
673 }
674 for (auto back = static_cast<std::size_t>(n); back > 0; --back) {
675 if (history_.newest(back - 1) >= history_.newest(back)) return 0.0;
676 }
677 return 1.0;
678 }
679
680 std::int64_t max_lookback_ = ::pineforge::detail::ta_lookback_limit();
681 series_osc_detail::History history_;
682};
683
684} // namespace source
685} // namespace pineforge
686
687// Feature macros: one per class above.
688#define PINEFORGE_HAS_PINE_SERIES_STOCH 1
689#define PINEFORGE_HAS_PINE_SERIES_CCI 1
690#define PINEFORGE_HAS_PINE_SERIES_MFI 1
691#define PINEFORGE_HAS_PINE_SERIES_MOM 1
692#define PINEFORGE_HAS_PINE_SERIES_ROC 1
693#define PINEFORGE_HAS_PINE_SERIES_CMO 1
694#define PINEFORGE_HAS_PINE_SERIES_WPR 1
695#define PINEFORGE_HAS_PINE_SERIES_COG 1
696#define PINEFORGE_HAS_PINE_SERIES_RISING 1
697#define PINEFORGE_HAS_PINE_SERIES_FALLING 1
Base with a code: throw coded<std::invalid_argument>(code, {args}, text).
std::size_t size() const
Definition series.hpp:188
WindowCacheCapacity cache_capacity() const
Definition series.hpp:189
T read(std::size_t index) const
Definition series.hpp:138
SeriesCci(WindowCacheCapacity cache)
double recompute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
double compute(double source, double length)
double compute(double source, double length)
SeriesCmo(WindowCacheCapacity cache)
double recompute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
double recompute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
SeriesCog(WindowCacheCapacity cache)
double compute(double source, double length)
SeriesFalling(WindowCacheCapacity cache)
double recompute(double source, double length)
double compute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
void observe_owned_storage(OwnedStorage &out) const noexcept
double recompute(double source, double volume, double length)
SeriesMfi(WindowCacheCapacity cache)
double compute(double source, double volume, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
double recompute(double source, double length)
double compute(double source, double length)
SeriesMom(WindowCacheCapacity cache)
double recompute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
double compute(double source, double length)
SeriesRising(WindowCacheCapacity cache)
double compute(double source, double length)
SeriesRoc(WindowCacheCapacity cache)
double recompute(double source, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
double compute(double source, double high, double low, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
SeriesStoch(WindowCacheCapacity cache)
double recompute(double source, double high, double low, double length)
Result update_series(double src, double length, bool advance, bool want_max, const char *function)
void observe_owned_storage(OwnedStorage &out) const noexcept
SeriesWpr(WindowCacheCapacity cache)
double compute(double close, double high, double low, double length)
double recompute(double close, double high, double low, double length)
void observe_owned_storage(OwnedStorage &out) const noexcept
History(WindowCacheCapacity cache, std::size_t limit)
History & operator=(const History &)=default
std::int64_t ta_lookback_limit() noexcept
void lookback_exceeded(std::uint64_t offset, std::int64_t maximum, bool beyond_uint64)
bool lagged(History &history, double source, std::uint64_t length, bool replace, double &previous)
bool present_window(History &history, double source, std::uint64_t count, bool replace)
std::size_t history_slots(std::int64_t maximum, std::size_t extra)
std::uint64_t checked_length(double length, const char *function, std::int64_t maximum)
double na< double >()
Definition na.hpp:64
bool is_na(const Line &h)
Definition drawing.hpp:58
WindowCacheCapacity & window_cache_capacity()
Definition series.hpp:40
std::string run_error_bar_prefix()
Stops using TradingView's text prepend "Error on bar N: " when a bar context is installed,...
bool float_band_lt(double a, double b)
bool float_band_eq(double a, double b)
bool float_band_gt(double a, double b)