Skip to content

Commit ade627e

Browse files
luisleo526luisleo526
authored andcommitted
engine: TradingView's sliding-window sum re-sums whenever the carried compensation is under-applied to the incoming source, and ta.stdev is sqrt(Sxx/n - m*m) over the same sliding sums (round 9, family W, jayentriken stochRSI/BBWP on six lanes)
KahanWindowSum (ta.sma / math.sum): the round-7 trigger "the incoming source swallows the carried compensation" (c != 0 and fl(x - c) == x) is the special case of the rule TradingView actually applies: with y0 = fl(x - c_pre), the window is re-summed newest-first (c reset, the bar's ring addend stored as the raw source) whenever |y0 - x| < |c_pre| -- the compensation was under-applied (fully swallowed, or rounded toward x: 1.25 ulp applied as 1 ulp, a 1.5-ulp tie resolved toward x). An exact subtraction or one rounded away from x continues. Pinned on a full-precision NYSE:F@15 oracle (pineforge-workflow tapes famw-f15-kdhi-0..7000, every value exported as its exact double): math.sum(stoch, 3) 7,018/7,018 and k = sum/3 7,018/7,018 bit-exact (round 7: 6,849), every k vs d sign and ta.crossover/crossunder event on the lane identical to TradingView (round 7: 24 signs, 12 events wrong -- the family-W divergences). Open pin: on residue-only inputs (|x| ~ 1e-15 comparable to |c|) TradingView's decision is a signed comparison (it flips under negation of the series); the magnitude form reproduces 6,991/7,016 math.sum(k, 3) bars there and no k vs d decision on the lane depends on those bits. StdDev (ta.stdev, biased): sqrt(Sxx / n - m * m) with m = Sx / n, where Sx = math.sum(src, n) and Sxx = math.sum(src * src, n) are the same KahanWindowSum sliding sums -- 7,029/7,029 bars bit-exact on the famw-f15-sd-* oracle (the documented two-pass form is exact on none). This is why two identical 7-close windows rank differently in the strategy's BBW percentile on TradingView. BB / BBW inherit it; the unbiased variant keeps the two-pass arithmetic (unpinned). recompute() replays the bar through KahanWindowSum::repush. tests: test_ta_window_underapplied (10 cold-start-synced segments through the pinned re-sum bars + the range-start stdev segment, bit-for-bit); the round-7 residual pins (test_ta_sma_window_residual, 12,905 checks) still pass, and test_ta_sma_stochrsi_ties' open 2025-06-03 01:15 case now fires like TradingView.
1 parent 51cc4e8 commit ade627e

7 files changed

Lines changed: 246 additions & 13 deletions

File tree

‎include/pineforge/ta.hpp‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,10 +407,23 @@ class HMA {
407407

408408
// --- StdDev (Standard Deviation) ---
409409

410+
// TradingView's ta.stdev (biased, the default) is NOT the two-pass
411+
// sum-of-squared-deviations of its documentation: it is
412+
// sqrt(Sxx / n - m * m), m = Sx / n,
413+
// with Sx = math.sum(src, n) and Sxx = math.sum(src * src, n) the same
414+
// sliding-window Kahan sums as ta.sma (window_sum.hpp) -- so the value carries
415+
// the cancellation error of that form and of those running sums. Pinned
416+
// 2026-09-05 (round 9, family W) on a full-precision NYSE:F@15 oracle
417+
// (pineforge-workflow famw-f15-sd-*: 7,029/7,029 bars bit-exact; the
418+
// two-pass form is exact on none of them). The unbiased variant
419+
// (biased = false) is unpinned and keeps the two-pass window arithmetic.
410420
class StdDev {
411421
int length_;
412422
bool biased_;
413-
std::deque<double> buffer_;
423+
std::deque<double> buffer_; // unbiased path only
424+
KahanWindowSum sum_x_; // Sx (biased path)
425+
KahanWindowSum sum_xx_; // Sxx (biased path)
426+
int bar_count_;
414427

415428
public:
416429
explicit StdDev(int length, bool biased = true);
@@ -419,6 +432,7 @@ class StdDev {
419432

420433
private:
421434
double held_stdev() const;
435+
double biased_value() const;
422436
};
423437

424438
// --- Supertrend ---

‎include/pineforge/window_sum.hpp‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ namespace pineforge {
1212
// * the ring stores the COMPENSATED addend y = x - c each source entered
1313
// with, and subtracts that y (through the same Kahan step) when the
1414
// source leaves the window `length` bars later -- sub before add;
15-
// * on the bar whose incoming source swallows the carried compensation
16-
// (c != 0 and fl(x - c) == x), the sum is re-summed newest-first over the
17-
// window's sources and c is reset.
15+
// * on the bar whose incoming source UNDER-applies the carried compensation
16+
// (c != 0 and, with y0 = fl(x - c), |y0 - x| < |c|: fully swallowed or
17+
// rounded toward x -- round-9 family-W pin generalising the round-7
18+
// swallow case), the sum is re-summed newest-first over the window's
19+
// sources, c is reset and the bar's ring addend is its raw source.
1820
//
1921
// Both users divide S by `length` themselves (ta.sma) or emit S (math.sum).
2022
class KahanWindowSum {

‎src/ta_moving_averages.cpp‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,23 @@ namespace pineforge {
4040
// x), the emitted sum is the newest-first direct re-sum of the window
4141
// with c reset (block 63 of both tapes drops an 18-unit / 182-unit
4242
// residue to exactly 1.1 there; block 69 reads (0.7 + 0.3) + 0.7000000000000001
43-
// = 1.7000000000000002, the oldest-first order gives 1.7).
43+
// = 1.7000000000000002, the oldest-first order gives 1.7);
44+
// * round 9 (family W, jayentriken stochRSI on six lanes) generalised that
45+
// trigger on a full-coverage NYSE:F@15 oracle (pineforge-workflow
46+
// famw-f15-kdhi-*: 7,035 bars of math.sum(stoch, 3), k, math.sum(k, 3),
47+
// d, every value exported as its exact double): the re-sum fires whenever
48+
// the compensation is UNDER-applied to the incoming source, i.e. with
49+
// y0 = fl(x - c), |y0 - x| < |c| -- fully swallowed (round 7) or rounded
50+
// toward x (c = 1.25 ulp(x) applied as 1 ulp; a 1.5-ulp tie resolved
51+
// toward x). An exact subtraction or one rounded away from x continues.
52+
// Bit-exact 7,018/7,018 on math.sum(stoch, 3) (round-7 trigger 6,849) and
53+
// every k vs d sign / ta.crossover event on the lane (round 7: 24 signs,
54+
// 12 events wrong). The re-summed bar stores its raw source as its ring
55+
// addend (c is 0 after the re-sum). Known open pin: on residue-only
56+
// inputs (|x| ~ 1e-15 comparable to |c|) TradingView's decision is a
57+
// SIGNED comparison (it flips under negation of the series) that this
58+
// magnitude form reproduces on 6,991/7,016 math.sum(k, 3) bars; no k vs d
59+
// decision on the lane depends on those bits.
4460
//
4561
// The stochRSI consequence (round-7 family D, jayentriken): k = sma(stoch, 3)
4662
// and d = sma(k, 3) sit on ALGEBRAIC ties whenever stoch plateaus; TradingView
@@ -53,7 +69,8 @@ namespace pineforge {
5369
// c_pre = c
5470
// if t >= n: y = -y[t-n] - c; T = S + y; c = (T - S) - y; S = T
5571
// y = x - c; T = S + y; c = (T - S) - y; S = T; store y
56-
// if c_pre != 0 and (x - c_pre) == x: S = (x + x[1]) + ... + x[n-1]; c = 0
72+
// if c_pre != 0 and |fl(x - c_pre) - x| < |c_pre|:
73+
// S = (x + x[1]) + ... + x[n-1]; c = 0; store x instead of y
5774
// sma = S / n
5875

5976
KahanWindowSum::KahanWindowSum(int length)
@@ -81,13 +98,23 @@ void KahanWindowSum::enter(double src, double comp_before) {
8198
sum_ = t;
8299
addends_.push_front(y);
83100
values_.push_front(src);
84-
if (comp_before != 0.0 && (src - comp_before) == src) {
85-
double total = 0.0;
86-
for (double v : values_) { // newest first
87-
total += v;
101+
if (comp_before != 0.0) {
102+
// Round-9 pin (family W): the re-sum fires whenever the carried
103+
// compensation is UNDER-applied to the incoming source -- the
104+
// compensated addend fl(src - c) landed closer to src than the exact
105+
// src - c would have (fully swallowed, the round-7 case, or rounded
106+
// toward src: c = 1.25 ulp(src) applied as 1 ulp). An exact
107+
// subtraction, or one that rounds away from src, continues.
108+
const double y0 = src - comp_before;
109+
if (std::fabs(y0 - src) < std::fabs(comp_before)) {
110+
double total = 0.0;
111+
for (double v : values_) { // newest first
112+
total += v;
113+
}
114+
sum_ = total;
115+
comp_ = 0.0;
116+
addends_.front() = src; // the re-summed bar stores its raw source
88117
}
89-
sum_ = total;
90-
comp_ = 0.0;
91118
}
92119
}
93120

‎src/ta_volatility_trend.cpp‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,19 @@ double ATR::recompute(double high, double low, double close, double prev_chart_c
120120

121121
// --- StdDev (Standard Deviation) ---
122122

123-
StdDev::StdDev(int length, bool biased) : length_(length), biased_(biased) {}
123+
StdDev::StdDev(int length, bool biased)
124+
: length_(length), biased_(biased), sum_x_(length), sum_xx_(length), bar_count_(0) {}
125+
126+
// The biased (default) value from the two sliding sums: TradingView's
127+
// sqrt(Sxx / n - m * m) with m = Sx / n (see the class note in ta.hpp). The
128+
// argument never went negative on the pinned lane; the clamp only guards a
129+
// pathological cancellation from producing NaN.
130+
double StdDev::biased_value() const {
131+
const double n = static_cast<double>(length_);
132+
const double m = sum_x_.sum() / n;
133+
const double var = sum_xx_.sum() / n - m * m;
134+
return std::sqrt(var > 0.0 ? var : 0.0);
135+
}
124136

125137
double StdDev::held_stdev() const {
126138
double sum = 0.0;
@@ -136,6 +148,20 @@ double StdDev::held_stdev() const {
136148
}
137149

138150
double StdDev::compute(double src) {
151+
if (biased_) {
152+
if (is_na(src)) {
153+
// na never enters (KI-66); the seeded value is held (see below).
154+
sum_x_.note_no_push();
155+
sum_xx_.note_no_push();
156+
if (bar_count_ >= length_) return biased_value();
157+
return na<double>();
158+
}
159+
sum_x_.push(src);
160+
sum_xx_.push(src * src);
161+
bar_count_++;
162+
if (bar_count_ < length_) return na<double>();
163+
return biased_value();
164+
}
139165
if (is_na(src)) {
140166
// Pine ta.stdev, like ta.sma (KI-66): an na input never enters the
141167
// compact last-N-valid window; once `length` valid values have been
@@ -724,6 +750,16 @@ double ATR::recompute(double high, double low, double close) {
724750

725751
// --- StdDev ---
726752
double StdDev::recompute(double src) {
753+
if (biased_) {
754+
if (is_na(src)) return na<double>();
755+
if (sum_x_.count() == 0) return compute(src);
756+
// Replay the bar with the new source against the same evicted addends
757+
// and the same pre-bar sums (KahanWindowSum::repush), as SMA does.
758+
sum_x_.repush(src);
759+
sum_xx_.repush(src * src);
760+
if (bar_count_ < length_) return na<double>();
761+
return biased_value();
762+
}
727763
if (buffer_.empty()) return compute(src);
728764
buffer_.back() = src;
729765

‎tests/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ set(TEST_SOURCES
1616
test_ta_sma_exact_order
1717
test_ta_sma_window_residual
1818
test_ta_sma_stochrsi_ties
19+
test_ta_window_underapplied
1920
test_ta_na_source_rules
2021
test_matrix
2122
test_matrix_identity
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// test_ta_window_underapplied -- round 9 (family W, jayentriken stochRSI on
2+
// six lanes): TradingView's sliding-window sum re-sums the window whenever the
3+
// carried Kahan compensation is UNDER-applied to the incoming source
4+
// (|fl(x - c) - x| < |c|: fully swallowed, the round-7 case, or rounded toward
5+
// x), and ta.stdev is sqrt(Sxx / n - m * m) over the same sliding sums
6+
// (window_sum.hpp, ta.hpp StdDev). Pinned 2026-09-05 on full-precision
7+
// NYSE:F@15 oracles exported by pineforge-workflow (famw-f15-kdhi-*,
8+
// famw-f15-sd-*: every value is TradingView's exact double, tiny residues
9+
// scaled by 2^60 on export).
10+
//
11+
// Every segment below starts cold at a bar from which the fitted arithmetic
12+
// reproduces TradingView bit-for-bit through the pinned re-sum bar (the
13+
// round-7 trigger misses each one: bars 747, 1156, 2324, 2659, 3362, 4351,
14+
// 4879, 5623 of math.sum(stoch, 3) and 262, 305 of math.sum(k, 3)); the
15+
// stdev segment is the lane's own range start (bar 0 = 2025-04-01 13:30Z).
16+
17+
#include <pineforge/ta.hpp>
18+
#include <pineforge/math.hpp>
19+
#include <pineforge/na.hpp>
20+
21+
#include <cmath>
22+
#include <cstdio>
23+
24+
#include "test_ta_window_underapplied_data.hpp"
25+
26+
using namespace pineforge;
27+
28+
static int tests_passed = 0;
29+
static int tests_failed = 0;
30+
31+
#define CHECK_TRUE(cond, tag) do { \
32+
if (cond) { tests_passed++; } \
33+
else { tests_failed++; std::printf("FAIL %s\n", (tag)); } \
34+
} while (0)
35+
36+
static bool same_bits(double a, double b) {
37+
if (std::isnan(a) && std::isnan(b)) return true;
38+
return a == b && std::signbit(a) == std::signbit(b);
39+
}
40+
41+
int main() {
42+
// 1. math.sum(x, n) / ta.sma(x, n): the re-sum trigger.
43+
for (const WindowSumSeg& seg : kWindowSumSegs) {
44+
math::Sum sum(seg.length);
45+
ta::SMA sma(seg.length);
46+
int bad = 0;
47+
for (int i = 0; i < seg.len; ++i) {
48+
const double s = sum.compute(seg.x[i]);
49+
const double m = sma.compute(seg.x[i]);
50+
if (i < seg.length - 1) continue;
51+
if (!same_bits(s, seg.tv[i])) {
52+
if (bad++ < 3) std::printf(" %s: bar %d math.sum %.17g != TradingView %.17g\n", seg.name, i, s, seg.tv[i]);
53+
}
54+
if (!same_bits(m, seg.tv[i] / seg.length)) {
55+
if (bad++ < 3) std::printf(" %s: bar %d ta.sma %.17g != TradingView %.17g\n", seg.name, i, m, seg.tv[i] / seg.length);
56+
}
57+
}
58+
char tag[200];
59+
std::snprintf(tag, sizeof tag, "%s: math.sum / ta.sma bit-exact (%d bad)", seg.name, bad);
60+
CHECK_TRUE(bad == 0, tag);
61+
}
62+
63+
// 2. ta.stdev(close, 7) = sqrt(Sxx/7 - m*m) over the sliding sums; ta.sma basis = Sx/7.
64+
for (const StdevSeg& seg : kStdevSegs) {
65+
math::Sum sx(7), sxx(7);
66+
ta::SMA basis(7);
67+
ta::StdDev sd(7);
68+
int bad = 0;
69+
for (int i = 0; i < seg.len; ++i) {
70+
const double c = seg.close[i];
71+
const double vsx = sx.compute(c);
72+
const double vsxx = sxx.compute(c * c);
73+
const double vb = basis.compute(c);
74+
const double vsd = sd.compute(c);
75+
if (i < 6) continue;
76+
if (!same_bits(vsx, seg.tv_sx[i]) || !same_bits(vsxx, seg.tv_sxx[i]) ||
77+
!same_bits(vb, seg.tv_basis[i]) || !same_bits(vsd, seg.tv_stdev[i])) {
78+
if (bad++ < 3) std::printf(" %s: bar %d sx %.17g/%.17g sxx %.17g/%.17g basis %.17g/%.17g stdev %.17g/%.17g\n",
79+
seg.name, i, vsx, seg.tv_sx[i], vsxx, seg.tv_sxx[i], vb, seg.tv_basis[i], vsd, seg.tv_stdev[i]);
80+
}
81+
}
82+
char tag[200];
83+
std::snprintf(tag, sizeof tag, "%s: math.sum(close), math.sum(close*close), ta.sma, ta.stdev bit-exact (%d bad)", seg.name, bad);
84+
CHECK_TRUE(bad == 0, tag);
85+
}
86+
87+
// 3. recompute() replays a bar bit-for-bit (intrabar path): feed each
88+
// stdev bar twice (a wrong first tick, then the real source).
89+
{
90+
const StdevSeg& seg = kStdevSegs[0];
91+
ta::StdDev sd(7);
92+
int bad = 0;
93+
for (int i = 0; i < seg.len; ++i) {
94+
sd.compute(seg.close[i] + 0.5);
95+
const double v = sd.recompute(seg.close[i]);
96+
if (i >= 6 && !same_bits(v, seg.tv_stdev[i])) bad++;
97+
}
98+
CHECK_TRUE(bad == 0, "ta.stdev recompute() replays the bar bit-for-bit");
99+
}
100+
101+
std::printf("test_ta_window_underapplied: passed=%d failed=%d\n", tests_passed, tests_failed);
102+
return tests_failed == 0 ? 0 : 1;
103+
}

0 commit comments

Comments
 (0)