oakscriptjs 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/cjs/check/format.d.ts.map +1 -1
  2. package/dist/cjs/check/format.js +5 -0
  3. package/dist/cjs/check/format.js.map +2 -2
  4. package/dist/cjs/check/harness.d.ts +24 -0
  5. package/dist/cjs/check/harness.d.ts.map +1 -1
  6. package/dist/cjs/check/harness.js +33 -0
  7. package/dist/cjs/check/harness.js.map +2 -2
  8. package/dist/cjs/check/index.d.ts +9 -0
  9. package/dist/cjs/check/index.d.ts.map +1 -1
  10. package/dist/cjs/check/index.js +7 -0
  11. package/dist/cjs/check/index.js.map +2 -2
  12. package/dist/cjs/color/index.d.ts.map +1 -1
  13. package/dist/cjs/color/index.js +19 -2
  14. package/dist/cjs/color/index.js.map +2 -2
  15. package/dist/cjs/color/parse.d.ts +8 -6
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +15 -2
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/drawing/registry.d.ts +68 -0
  20. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  21. package/dist/cjs/drawing/registry.js +99 -9
  22. package/dist/cjs/drawing/registry.js.map +2 -2
  23. package/dist/cjs/index.d.ts +3 -2
  24. package/dist/cjs/index.d.ts.map +1 -1
  25. package/dist/cjs/index.js +5 -1
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/runtime/series.d.ts +16 -0
  28. package/dist/cjs/runtime/series.d.ts.map +1 -1
  29. package/dist/cjs/runtime/series.js +19 -2
  30. package/dist/cjs/runtime/series.js.map +2 -2
  31. package/dist/cjs/script/closure-writes.d.ts +16 -0
  32. package/dist/cjs/script/closure-writes.d.ts.map +1 -0
  33. package/dist/cjs/script/closure-writes.js +435 -0
  34. package/dist/cjs/script/closure-writes.js.map +7 -0
  35. package/dist/cjs/script/globals.d.ts +2 -0
  36. package/dist/cjs/script/globals.d.ts.map +1 -1
  37. package/dist/cjs/script/globals.js.map +1 -1
  38. package/dist/cjs/script/incremental.d.ts +140 -0
  39. package/dist/cjs/script/incremental.d.ts.map +1 -0
  40. package/dist/cjs/script/incremental.js +142 -0
  41. package/dist/cjs/script/incremental.js.map +7 -0
  42. package/dist/cjs/script/index.d.ts +116 -31
  43. package/dist/cjs/script/index.d.ts.map +1 -1
  44. package/dist/cjs/script/index.js +471 -25
  45. package/dist/cjs/script/index.js.map +3 -3
  46. package/dist/cjs/str/numberformat.d.ts.map +1 -1
  47. package/dist/cjs/str/numberformat.js +23 -0
  48. package/dist/cjs/str/numberformat.js.map +2 -2
  49. package/dist/cjs/strategy/index.d.ts +8 -0
  50. package/dist/cjs/strategy/index.d.ts.map +1 -1
  51. package/dist/cjs/strategy/index.js.map +1 -1
  52. package/dist/cjs/ta/running-sum.d.ts.map +1 -1
  53. package/dist/cjs/ta/running-sum.js +72 -3
  54. package/dist/cjs/ta/running-sum.js.map +2 -2
  55. package/dist/cjs/ta/step.d.ts +476 -0
  56. package/dist/cjs/ta/step.d.ts.map +1 -0
  57. package/dist/cjs/ta/step.js +1000 -0
  58. package/dist/cjs/ta/step.js.map +7 -0
  59. package/dist/cjs/ta-series.d.ts +1 -1
  60. package/dist/cjs/ta-series.js +3 -3
  61. package/dist/cjs/ta-series.js.map +1 -1
  62. package/dist/esm/check/format.d.ts.map +1 -1
  63. package/dist/esm/check/format.js +5 -0
  64. package/dist/esm/check/format.js.map +1 -1
  65. package/dist/esm/check/harness.d.ts +24 -0
  66. package/dist/esm/check/harness.d.ts.map +1 -1
  67. package/dist/esm/check/harness.js +40 -6
  68. package/dist/esm/check/harness.js.map +1 -1
  69. package/dist/esm/check/index.d.ts +9 -0
  70. package/dist/esm/check/index.d.ts.map +1 -1
  71. package/dist/esm/check/index.js +11 -1
  72. package/dist/esm/check/index.js.map +1 -1
  73. package/dist/esm/color/index.d.ts.map +1 -1
  74. package/dist/esm/color/index.js +23 -3
  75. package/dist/esm/color/index.js.map +1 -1
  76. package/dist/esm/color/parse.d.ts +8 -6
  77. package/dist/esm/color/parse.d.ts.map +1 -1
  78. package/dist/esm/color/parse.js +19 -2
  79. package/dist/esm/color/parse.js.map +1 -1
  80. package/dist/esm/drawing/registry.d.ts +68 -0
  81. package/dist/esm/drawing/registry.d.ts.map +1 -1
  82. package/dist/esm/drawing/registry.js +156 -10
  83. package/dist/esm/drawing/registry.js.map +1 -1
  84. package/dist/esm/index.d.ts +3 -2
  85. package/dist/esm/index.d.ts.map +1 -1
  86. package/dist/esm/index.js +6 -3
  87. package/dist/esm/index.js.map +1 -1
  88. package/dist/esm/runtime/series.d.ts +16 -0
  89. package/dist/esm/runtime/series.d.ts.map +1 -1
  90. package/dist/esm/runtime/series.js +21 -1
  91. package/dist/esm/runtime/series.js.map +1 -1
  92. package/dist/esm/script/closure-writes.d.ts +16 -0
  93. package/dist/esm/script/closure-writes.d.ts.map +1 -0
  94. package/dist/esm/script/closure-writes.js +323 -0
  95. package/dist/esm/script/closure-writes.js.map +1 -0
  96. package/dist/esm/script/globals.d.ts +2 -0
  97. package/dist/esm/script/globals.d.ts.map +1 -1
  98. package/dist/esm/script/globals.js.map +1 -1
  99. package/dist/esm/script/incremental.d.ts +140 -0
  100. package/dist/esm/script/incremental.d.ts.map +1 -0
  101. package/dist/esm/script/incremental.js +173 -0
  102. package/dist/esm/script/incremental.js.map +1 -0
  103. package/dist/esm/script/index.d.ts +116 -31
  104. package/dist/esm/script/index.d.ts.map +1 -1
  105. package/dist/esm/script/index.js +561 -24
  106. package/dist/esm/script/index.js.map +1 -1
  107. package/dist/esm/str/numberformat.d.ts.map +1 -1
  108. package/dist/esm/str/numberformat.js +30 -0
  109. package/dist/esm/str/numberformat.js.map +1 -1
  110. package/dist/esm/strategy/index.d.ts +8 -0
  111. package/dist/esm/strategy/index.d.ts.map +1 -1
  112. package/dist/esm/ta/running-sum.d.ts.map +1 -1
  113. package/dist/esm/ta/running-sum.js +79 -4
  114. package/dist/esm/ta/running-sum.js.map +1 -1
  115. package/dist/esm/ta/step.d.ts +476 -0
  116. package/dist/esm/ta/step.d.ts.map +1 -0
  117. package/dist/esm/ta/step.js +1089 -0
  118. package/dist/esm/ta/step.js.map +1 -0
  119. package/dist/esm/ta-series.d.ts +1 -1
  120. package/dist/esm/ta-series.js +4 -4
  121. package/package.json +1 -1
  122. package/skills/oakscript/SKILL.md +2 -2
  123. package/skills/oakscript/reference/check.md +5 -0
  124. package/skills/oakscript/reference/errors.md +0 -1
  125. package/skills/oakscript/reference/pine-differences.md +1 -2
  126. package/skills/oakscript/reference/plotting.md +5 -7
  127. package/skills/oakscript/reference/script-structure.md +6 -0
  128. package/src/check/format.ts +7 -0
  129. package/src/check/harness.ts +57 -0
  130. package/src/check/index.ts +16 -0
  131. package/src/color/index.ts +22 -3
  132. package/src/color/parse.ts +28 -3
  133. package/src/drawing/registry.ts +172 -10
  134. package/src/index.ts +9 -2
  135. package/src/runtime/series.ts +33 -1
  136. package/src/script/closure-writes.ts +279 -0
  137. package/src/script/globals.ts +2 -0
  138. package/src/script/incremental.ts +246 -0
  139. package/src/script/index.ts +695 -26
  140. package/src/str/numberformat.ts +29 -0
  141. package/src/strategy/index.ts +8 -0
  142. package/src/ta/running-sum.ts +78 -3
  143. package/src/ta/step.ts +1145 -0
  144. package/src/ta-series.ts +4 -4
package/src/ta/step.ts ADDED
@@ -0,0 +1,1145 @@
1
+ /**
2
+ * ta.* functions one bar at a time (#196).
3
+ *
4
+ * Each machine is the state of one ta.* call. {@link BarStep.step} gives the result of the current bar from the kept
5
+ * state of the earlier bars, without changing it: calling it again on the same bar (a live update of the forming bar,
6
+ * or the same call in a loop) starts again from the same state. {@link BarStep.commit} ends the bar: its last step is
7
+ * kept for the next bars. A bar without a step is not in the history of the call (a call in an `if` block), and a
8
+ * commit without a step does nothing.
9
+ *
10
+ * Driven once per bar over an array (step, commit), a machine gives the doubles of the array function of `ta`, bit for
11
+ * bit (tests/ta/step.test.ts): the same rules for na and ±Infinity, the same operation order.
12
+ */
13
+ import { RunningSum, isNa } from './running-sum.js';
14
+ import { checkPositiveLength, checkSumLength, checkWindowLength } from './limits.js';
15
+ import { eq, ge, gt, le } from '../compare/index.js';
16
+
17
+ export interface BarStep<A extends unknown[], R> {
18
+ /** The result of the current bar from the state of the earlier bars (a later step of the same bar replaces it) */
19
+ step(...args: A): R;
20
+ /** The current bar is final: its last step is kept */
21
+ commit(): void;
22
+ }
23
+
24
+ /** A value ta.* functions skip: na (NaN, null, undefined) or ±Infinity. */
25
+ const skipped = (v: number): boolean => v === undefined || v === null || !Number.isFinite(v);
26
+
27
+ // ── Window sums ──────────────────────────────────────────────────────────────
28
+
29
+ /**
30
+ * `math.sum(source, length)`: the correctly rounded sum of the last `length` non-na values; a bar with an na value
31
+ * keeps the previous result. The length can change from one bar to the next (series length).
32
+ */
33
+ export class SumStep implements BarStep<[value: number, length: number], number> {
34
+ private readonly sum = new RunningSum();
35
+ private stepped = false;
36
+
37
+ step(value: number, length: number): number {
38
+ const len = Math.floor(length);
39
+ this.stepped = len >= 1;
40
+ if (!this.stepped) return NaN;
41
+ return isNa(value) ? this.sum.stepNa(len) : this.sum.step(value, len);
42
+ }
43
+
44
+ commit(): void {
45
+ if (this.stepped) this.sum.commit();
46
+ this.stepped = false;
47
+ }
48
+
49
+ /** Forget the steps of the current bar (the bar is not in the history) */
50
+ discard(): void {
51
+ this.stepped = false;
52
+ }
53
+ }
54
+
55
+ /** `ta.sma(source, length)`: {@link SumStep} divided by the length. */
56
+ export class SmaStep implements BarStep<[value: number, length: number], number> {
57
+ private readonly sum = new SumStep();
58
+
59
+ step(value: number, length: number): number {
60
+ checkSumLength('ta.sma', Math.floor(length), 0);
61
+ return this.sum.step(value, length) / Math.floor(length);
62
+ }
63
+
64
+ commit(): void {
65
+ this.sum.commit();
66
+ }
67
+ }
68
+
69
+ /**
70
+ * `ta.variance(source, length, biased)` from the window sums of the values and of their squares: biased
71
+ * `sumSq / n - mean * mean`, unbiased `sumSq / (n - 1) - mean * sum / (n - 1)` (na for a length of 1).
72
+ */
73
+ export class VarianceStep implements BarStep<[value: number, length: number, biased?: boolean], number> {
74
+ private readonly sums = new SumStep();
75
+ private readonly squares = new SumStep();
76
+
77
+ constructor(private readonly name = 'ta.variance') {}
78
+
79
+ step(value: number, length: number, biased = true): number {
80
+ const len = Math.floor(length);
81
+ checkSumLength(this.name, len, 0);
82
+ const sum = this.sums.step(value, len);
83
+ const sq = this.squares.step(isNa(value) ? NaN : value * value, len);
84
+ if ((biased ? len : len - 1) <= 0) return NaN;
85
+ const mean = sum / len;
86
+ return biased ? sq / len - mean * mean : sq / (len - 1) - (mean * sum) / (len - 1);
87
+ }
88
+
89
+ commit(): void {
90
+ this.sums.commit();
91
+ this.squares.commit();
92
+ }
93
+ }
94
+
95
+ /** `ta.stdev(source, length, biased)`: the square root of {@link VarianceStep} (0 when it is not positive). */
96
+ export class StdevStep implements BarStep<[value: number, length: number, biased?: boolean], number> {
97
+ private readonly variance = new VarianceStep('ta.stdev');
98
+
99
+ step(value: number, length: number, biased = true): number {
100
+ const v = this.variance.step(value, length, biased);
101
+ return Number.isNaN(v) ? NaN : v > 0 ? Math.sqrt(v) : 0;
102
+ }
103
+
104
+ commit(): void {
105
+ this.variance.commit();
106
+ }
107
+ }
108
+
109
+ // ── Moving averages ──────────────────────────────────────────────────────────
110
+
111
+ /**
112
+ * Exponential averages seeded with `ta.sma` on the bar of the `length`-th non-na value (ta.ema, ta.rma); a bar with an
113
+ * na value gives na and keeps the state.
114
+ */
115
+ abstract class SeededAverage implements BarStep<[value: number], number> {
116
+ private readonly seed = new SumStep();
117
+ private value = NaN;
118
+ private count = 0;
119
+ private stepped = false;
120
+ /** The last step of the bar added its value to the seed sum */
121
+ private seeded = false;
122
+ private nextValue = NaN;
123
+ private nextCount = 0;
124
+ protected readonly len: number;
125
+
126
+ constructor(name: string, length: number) {
127
+ checkPositiveLength(name, length, 0);
128
+ this.len = Math.floor(length);
129
+ }
130
+
131
+ protected abstract next(value: number, previous: number): number;
132
+
133
+ step(value: number): number {
134
+ this.stepped = true;
135
+ this.seeded = false;
136
+ this.nextValue = this.value;
137
+ this.nextCount = this.count;
138
+ if (skipped(value)) return NaN;
139
+ this.nextCount = this.count + 1;
140
+ if (this.count < this.len) {
141
+ this.seeded = true;
142
+ const s = this.seed.step(value, this.len);
143
+ if (this.nextCount < this.len) return NaN;
144
+ this.nextValue = s / this.len;
145
+ return this.nextValue;
146
+ }
147
+ this.nextValue = this.next(value, this.value);
148
+ return this.nextValue;
149
+ }
150
+
151
+ commit(): void {
152
+ if (!this.stepped) return;
153
+ this.stepped = false;
154
+ if (this.seeded) this.seed.commit();
155
+ else this.seed.discard();
156
+ this.value = this.nextValue;
157
+ this.count = this.nextCount;
158
+ }
159
+ }
160
+
161
+ /** `ta.ema(source, length)`: `(source - ema) * 2 / (length + 1) + ema` after the seed. */
162
+ export class EmaStep extends SeededAverage {
163
+ private readonly multiplier: number;
164
+
165
+ constructor(length: number) {
166
+ super('ema', length);
167
+ this.multiplier = 2 / (this.len + 1);
168
+ }
169
+
170
+ protected next(value: number, previous: number): number {
171
+ return (value - previous) * this.multiplier + previous;
172
+ }
173
+ }
174
+
175
+ /** `ta.rma(source, length)`: `(source + (length - 1) * rma) / length` after the seed. */
176
+ export class RmaStep extends SeededAverage {
177
+ constructor(length: number, name = 'rma') {
178
+ super(name, length);
179
+ }
180
+
181
+ protected next(value: number, previous: number): number {
182
+ return (value + (this.len - 1) * previous) / this.len;
183
+ }
184
+ }
185
+
186
+ /** The PineScript ta.wma partial sum: `a + b`, 0 when `|a + b| <= 1e-10 * max(1, |a| + |b|)`. */
187
+ function wmaAdd(a: number, b: number): number {
188
+ const sum = a + b;
189
+ return Math.abs(sum) <= 1e-10 * Math.max(1, Math.abs(a) + Math.abs(b)) ? 0 : sum;
190
+ }
191
+
192
+ /**
193
+ * `ta.wma(source, length)`: na on a bar with an na value and until `length` non-na values; otherwise the last `length`
194
+ * bars (an na bar holds the previous non-na value), summed from the oldest with the PineScript zero rule.
195
+ */
196
+ export class WmaStep implements BarStep<[value: number, length: number], number> {
197
+ private readonly filled: number[] = [];
198
+ private last = NaN;
199
+ private count = 0;
200
+ private stepped = false;
201
+ private nextFilled = NaN;
202
+ private nextValid = false;
203
+
204
+ step(value: number, length: number): number {
205
+ const len = Math.floor(length);
206
+ checkPositiveLength('wma', len, this.filled.length);
207
+ this.stepped = true;
208
+ const na = skipped(value);
209
+ this.nextValid = !na;
210
+ this.nextFilled = na ? this.last : value;
211
+ if (na || !(len >= 1) || this.count + 1 < len) return NaN;
212
+ const n = this.filled.length;
213
+ let sum = 0;
214
+ let weightSum = 0;
215
+ for (let j = len - 1; j >= 0; j--) {
216
+ const weight = len - j;
217
+ sum = wmaAdd(sum, (j === 0 ? this.nextFilled : this.filled[n - j]!) * weight);
218
+ weightSum += weight;
219
+ }
220
+ return sum / weightSum;
221
+ }
222
+
223
+ commit(): void {
224
+ if (!this.stepped) return;
225
+ this.stepped = false;
226
+ if (this.nextValid) {
227
+ this.last = this.nextFilled;
228
+ this.count++;
229
+ }
230
+ this.filled.push(this.nextFilled);
231
+ }
232
+ }
233
+
234
+ // ── Changes ──────────────────────────────────────────────────────────────────
235
+
236
+ /** The values of the earlier bars of a call (one per bar with a step), for the `source[length]` of ta.change & co. */
237
+ abstract class HistoryStep<A extends unknown[], R> implements BarStep<A, R> {
238
+ protected readonly history: number[] = [];
239
+ private stepped = false;
240
+ private pending = NaN;
241
+
242
+ /** The current bar's value, kept by commit() */
243
+ protected keep(value: number): void {
244
+ this.stepped = true;
245
+ this.pending = value;
246
+ }
247
+
248
+ /** The value `k` bars back (k >= 1), NaN before the first bar */
249
+ protected back(k: number): number {
250
+ const i = this.history.length - k;
251
+ return i >= 0 ? this.history[i]! : NaN;
252
+ }
253
+
254
+ abstract step(...args: A): R;
255
+
256
+ commit(): void {
257
+ if (!this.stepped) return;
258
+ this.stepped = false;
259
+ this.history.push(this.pending);
260
+ }
261
+ }
262
+
263
+ /** `ta.change(source, length)`: `source - source[length]` (na for the first `length` bars). */
264
+ export class ChangeStep extends HistoryStep<[value: number], number> {
265
+ constructor(private readonly length = 1) {
266
+ super();
267
+ checkPositiveLength('change', length, 0);
268
+ }
269
+
270
+ step(value: number): number {
271
+ this.keep(value);
272
+ return this.history.length < this.length ? NaN : value - this.back(this.length);
273
+ }
274
+ }
275
+
276
+ /** `ta.mom(source, length)`: `source - source[length]`, na when either is na. */
277
+ export class MomStep extends HistoryStep<[value: number], number> {
278
+ constructor(private readonly length: number) {
279
+ super();
280
+ checkPositiveLength('mom', length, 0);
281
+ }
282
+
283
+ step(value: number): number {
284
+ this.keep(value);
285
+ if (this.history.length < this.length) return NaN;
286
+ const old = this.back(this.length);
287
+ return Number.isNaN(value) || Number.isNaN(old) ? NaN : value - old;
288
+ }
289
+ }
290
+
291
+ /** `ta.roc(source, length)`: `100 * (source - source[length]) / source[length]` (a zero base gives ±Infinity). */
292
+ export class RocStep extends HistoryStep<[value: number], number> {
293
+ constructor(private readonly length: number) {
294
+ super();
295
+ checkPositiveLength('roc', length, 0);
296
+ }
297
+
298
+ step(value: number): number {
299
+ this.keep(value);
300
+ if (this.history.length < this.length) return NaN;
301
+ const old = this.back(this.length);
302
+ if (Number.isNaN(old) || Number.isNaN(value)) return NaN;
303
+ return (100 * (value - old)) / old;
304
+ }
305
+ }
306
+
307
+ /** `ta.tr(handle_na)`: max(high - low, |high - close[1]|, |low - close[1]|); on the first bar or after an na close, na
308
+ * (or high - low with handle_na). */
309
+ export class TrStep extends HistoryStep<[high: number, low: number, close: number], number> {
310
+ constructor(private readonly handleNa = false) {
311
+ super();
312
+ }
313
+
314
+ step(high: number, low: number, close: number): number {
315
+ this.keep(close);
316
+ const prev = this.back(1);
317
+ if (this.history.length === 0 || Number.isNaN(prev)) return this.handleNa ? high - low : NaN;
318
+ return Math.max(high - low, Math.abs(high - prev), Math.abs(low - prev));
319
+ }
320
+ }
321
+
322
+ /** `ta.atr(length)`: {@link RmaStep} of `ta.tr(true)`. */
323
+ export class AtrStep implements BarStep<[high: number, low: number, close: number], number> {
324
+ private readonly tr = new TrStep(true);
325
+ private readonly rma: RmaStep;
326
+
327
+ constructor(length: number) {
328
+ checkPositiveLength('atr->rma', length, 0);
329
+ this.rma = new RmaStep(length, 'atr->rma');
330
+ }
331
+
332
+ step(high: number, low: number, close: number): number {
333
+ return this.rma.step(this.tr.step(high, low, close));
334
+ }
335
+
336
+ commit(): void {
337
+ this.tr.commit();
338
+ this.rma.commit();
339
+ }
340
+ }
341
+
342
+ /**
343
+ * `ta.rsi(source, length)`: the rma of the gains and of the losses of the changes from the previous bar; 100 when the
344
+ * average loss is 0, else 0 when the average gain is 0 (comparisons with the 1e-10 tolerance).
345
+ */
346
+ export class RsiStep extends HistoryStep<[value: number], number> {
347
+ private readonly gains: RmaStep;
348
+ private readonly losses: RmaStep;
349
+
350
+ constructor(length: number) {
351
+ super();
352
+ checkPositiveLength('rsi', length, 0, 'y');
353
+ this.gains = new RmaStep(length);
354
+ this.losses = new RmaStep(length);
355
+ }
356
+
357
+ step(value: number): number {
358
+ this.keep(value);
359
+ if (this.history.length === 0) return NaN;
360
+ const c = value - this.back(1);
361
+ const up = this.gains.step(Number.isNaN(c) ? NaN : c > 0 ? c : 0);
362
+ const down = this.losses.step(Number.isNaN(c) ? NaN : c < 0 ? -c : 0);
363
+ if (eq(down, 0)) return 100;
364
+ if (eq(up, 0)) return 0;
365
+ return 100 - 100 / (1 + up / down);
366
+ }
367
+
368
+ override commit(): void {
369
+ super.commit();
370
+ this.gains.commit();
371
+ this.losses.commit();
372
+ }
373
+ }
374
+
375
+ // ── Running state ────────────────────────────────────────────────────────────
376
+
377
+ /** `ta.cum(source)`: the sum of the non-na values; na on a bar with an na value. */
378
+ export class CumStep implements BarStep<[value: number], number> {
379
+ private sum = 0;
380
+ private next = 0;
381
+ private stepped = false;
382
+
383
+ step(value: number): number {
384
+ this.stepped = true;
385
+ this.next = this.sum;
386
+ if (!Number.isFinite(value)) return NaN;
387
+ this.next = this.sum + value;
388
+ return this.next;
389
+ }
390
+
391
+ commit(): void {
392
+ if (this.stepped) this.sum = this.next;
393
+ this.stepped = false;
394
+ }
395
+ }
396
+
397
+ /** Compared with the last earlier bar where both values were not na (ta.crossover, ta.crossunder). */
398
+ class CrossTestStep implements BarStep<[a: number, b: number], boolean> {
399
+ private prevA = NaN;
400
+ private prevB = NaN;
401
+ private nextA = NaN;
402
+ private nextB = NaN;
403
+ private stepped = false;
404
+
405
+ constructor(private readonly test: (a: number, b: number, pa: number, pb: number) => boolean) {}
406
+
407
+ step(a: number, b: number): boolean {
408
+ this.stepped = true;
409
+ const both = !Number.isNaN(a) && !Number.isNaN(b);
410
+ this.nextA = both ? a : this.prevA;
411
+ this.nextB = both ? b : this.prevB;
412
+ return this.test(a, b, this.prevA, this.prevB);
413
+ }
414
+
415
+ commit(): void {
416
+ if (!this.stepped) return;
417
+ this.stepped = false;
418
+ this.prevA = this.nextA;
419
+ this.prevB = this.nextB;
420
+ }
421
+ }
422
+
423
+ /** `ta.crossover(a, b)` */
424
+ export class CrossoverStep extends CrossTestStep {
425
+ constructor() {
426
+ super((a, b, pa, pb) => a > b && pa <= pb);
427
+ }
428
+ }
429
+
430
+ /** `ta.crossunder(a, b)` */
431
+ export class CrossunderStep extends CrossTestStep {
432
+ constructor() {
433
+ super((a, b, pa, pb) => a < b && pa >= pb);
434
+ }
435
+ }
436
+
437
+ /** `ta.cross(a, b)`: true when the values are strictly on the other side of the last strict side. */
438
+ export class CrossStep implements BarStep<[a: number, b: number], boolean> {
439
+ private side = 0;
440
+ private next = 0;
441
+ private stepped = false;
442
+
443
+ step(a: number, b: number): boolean {
444
+ this.stepped = true;
445
+ this.next = this.side;
446
+ if (Number.isNaN(a) || Number.isNaN(b)) return false;
447
+ const crossed = (this.side < 0 && a > b) || (this.side > 0 && a < b);
448
+ if (a < b) this.next = -1;
449
+ else if (a > b) this.next = 1;
450
+ return crossed;
451
+ }
452
+
453
+ commit(): void {
454
+ if (this.stepped) this.side = this.next;
455
+ this.stepped = false;
456
+ }
457
+ }
458
+
459
+ /** `ta.barssince(condition)`: 0 on a true bar, then +1 per bar; na before the first true bar. */
460
+ export class BarssinceStep implements BarStep<[condition: boolean | number], number> {
461
+ private value = NaN;
462
+ private next = NaN;
463
+ private stepped = false;
464
+
465
+ step(condition: boolean | number): number {
466
+ this.stepped = true;
467
+ this.next = condition ? 0 : Number.isNaN(this.value) ? NaN : this.value + 1;
468
+ return this.next;
469
+ }
470
+
471
+ commit(): void {
472
+ if (this.stepped) this.value = this.next;
473
+ this.stepped = false;
474
+ }
475
+ }
476
+
477
+ /** `ta.valuewhen(condition, source, occurrence)`: the source value of the `occurrence`-th last true bar (0: the last). */
478
+ export class ValuewhenStep implements BarStep<[condition: boolean | number, value: number], number> {
479
+ private readonly values: number[] = [];
480
+ private pending: number | null = null;
481
+ private stepped = false;
482
+
483
+ constructor(private readonly occurrence: number) {}
484
+
485
+ step(condition: boolean | number, value: number): number {
486
+ this.stepped = true;
487
+ this.pending = condition ? value : null;
488
+ const n = this.values.length + (condition ? 1 : 0);
489
+ const k = n - 1 - this.occurrence;
490
+ if (k < 0 || k >= n) return NaN;
491
+ return k === this.values.length ? value : (this.values[k] ?? NaN);
492
+ }
493
+
494
+ commit(): void {
495
+ if (this.stepped && this.pending !== null) this.values.push(this.pending);
496
+ this.stepped = false;
497
+ this.pending = null;
498
+ }
499
+ }
500
+
501
+ /** `ta.obv`: the cumulated `sign(close - close[1]) * volume` (na on the first bar). */
502
+ export class ObvStep extends HistoryStep<[close: number, volume: number], number> {
503
+ private readonly cum = new CumStep();
504
+
505
+ step(close: number, volume: number): number {
506
+ this.keep(close);
507
+ return this.cum.step(this.history.length === 0 ? NaN : Math.sign(close - this.back(1)) * volume);
508
+ }
509
+
510
+ override commit(): void {
511
+ super.commit();
512
+ this.cum.commit();
513
+ }
514
+ }
515
+
516
+ // ── Window extremes ──────────────────────────────────────────────────────────
517
+
518
+ /**
519
+ * `ta.highest` / `ta.lowest`: the extreme of the last `length` non-na values (all of them when fewer), also on a bar
520
+ * whose own value is na; na before bar `length - 1` and while no value was received. Math.max / Math.min of the
521
+ * window: +0 wins over -0 for the highest, -0 for the lowest.
522
+ */
523
+ class ExtremeStep implements BarStep<[value: number, length: number], number> {
524
+ private readonly values: number[] = [];
525
+ private bars = 0;
526
+ private pending = NaN;
527
+ private stepped = false;
528
+
529
+ constructor(private readonly lowest: boolean) {}
530
+
531
+ step(value: number, length: number): number {
532
+ checkWindowLength(this.lowest ? 'lowest' : 'highest', length, this.bars);
533
+ this.stepped = true;
534
+ this.pending = value;
535
+ const len = Math.trunc(length);
536
+ const own = !skipped(value);
537
+ const n = this.values.length + (own ? 1 : 0);
538
+ if (this.bars < len - 1 || n === 0) return NaN;
539
+ let best = own ? value : this.values[n - 1]!;
540
+ const from = Math.max(0, n - len);
541
+ for (let i = from; i < this.values.length; i++) {
542
+ const v = this.values[i]!;
543
+ best = this.lowest ? Math.min(best, v) : Math.max(best, v);
544
+ }
545
+ return best;
546
+ }
547
+
548
+ commit(): void {
549
+ if (!this.stepped) return;
550
+ this.stepped = false;
551
+ this.bars++;
552
+ if (!skipped(this.pending)) this.values.push(this.pending);
553
+ }
554
+ }
555
+
556
+ /** `ta.highest(source, length)` */
557
+ export class HighestStep extends ExtremeStep {
558
+ constructor() {
559
+ super(false);
560
+ }
561
+ }
562
+
563
+ /** `ta.lowest(source, length)` */
564
+ export class LowestStep extends ExtremeStep {
565
+ constructor() {
566
+ super(true);
567
+ }
568
+ }
569
+
570
+ // ── Composites ───────────────────────────────────────────────────────────────
571
+
572
+ /** `ta.macd(source, fast, slow, signal)`: `[macd, signal, histogram]`. */
573
+ export class MacdStep implements BarStep<[value: number], [number, number, number]> {
574
+ private readonly fast: EmaStep;
575
+ private readonly slow: EmaStep;
576
+ private readonly signal: EmaStep;
577
+
578
+ constructor(fastLength: number, slowLength: number, signalLength: number) {
579
+ this.fast = new EmaStep(fastLength);
580
+ this.slow = new EmaStep(slowLength);
581
+ this.signal = new EmaStep(signalLength);
582
+ }
583
+
584
+ step(value: number): [number, number, number] {
585
+ const line = this.fast.step(value) - this.slow.step(value);
586
+ const signal = this.signal.step(line);
587
+ return [line, signal, line - signal];
588
+ }
589
+
590
+ commit(): void {
591
+ this.fast.commit();
592
+ this.slow.commit();
593
+ this.signal.commit();
594
+ }
595
+ }
596
+
597
+ /** `ta.bb(source, length, mult)`: `[basis, upper, lower]`. */
598
+ export class BbStep implements BarStep<[value: number], [number, number, number]> {
599
+ private readonly basis = new SumStep();
600
+ private readonly dev = new StdevStep();
601
+ private readonly len: number;
602
+
603
+ constructor(length: number, private readonly mult: number) {
604
+ checkSumLength('ta.bb', length, 0);
605
+ this.len = Math.floor(length);
606
+ }
607
+
608
+ step(value: number): [number, number, number] {
609
+ const basis = this.basis.step(value, this.len) / this.len;
610
+ const dev = this.dev.step(value, this.len);
611
+ return [basis, basis + this.mult * dev, basis - this.mult * dev];
612
+ }
613
+
614
+ commit(): void {
615
+ this.basis.commit();
616
+ this.dev.commit();
617
+ }
618
+ }
619
+
620
+ /** `ta.vwma(source, length)`: `sma(source * volume) / sma(volume)`, na when the volume average is 0 or na. */
621
+ export class VwmaStep implements BarStep<[value: number, volume: number], number> {
622
+ private readonly numerator = new SumStep();
623
+ private readonly denominator = new SumStep();
624
+ private readonly len: number;
625
+
626
+ constructor(length: number) {
627
+ checkPositiveLength('vwma->sma', length, 0);
628
+ this.len = Math.floor(length);
629
+ }
630
+
631
+ step(value: number, volume: number): number {
632
+ checkSumLength('ta.sma', this.len, 0);
633
+ const num = this.numerator.step(value * volume, this.len) / this.len;
634
+ const den = this.denominator.step(volume, this.len) / this.len;
635
+ return den === 0 || Number.isNaN(den) ? NaN : num / den;
636
+ }
637
+
638
+ commit(): void {
639
+ this.numerator.commit();
640
+ this.denominator.commit();
641
+ }
642
+ }
643
+
644
+ /**
645
+ * `ta.stoch(source, high, low, length)`: `100 * (source - lowest(low)) / (highest(high) - lowest(low))`; an na result
646
+ * keeps the previous one.
647
+ */
648
+ export class StochStep implements BarStep<[source: number, high: number, low: number], number> {
649
+ private readonly highest = new HighestStep();
650
+ private readonly lowest = new LowestStep();
651
+ private previous = NaN;
652
+ private next = NaN;
653
+ private stepped = false;
654
+
655
+ constructor(private readonly length: number) {
656
+ checkPositiveLength('stoch->highest', length, 0);
657
+ }
658
+
659
+ step(source: number, high: number, low: number): number {
660
+ this.stepped = true;
661
+ const lo = this.lowest.step(low, this.length);
662
+ const k = (100 * (source - lo)) / (this.highest.step(high, this.length) - lo);
663
+ this.next = Number.isNaN(k) ? this.previous : k;
664
+ return this.next;
665
+ }
666
+
667
+ commit(): void {
668
+ if (!this.stepped) return;
669
+ this.stepped = false;
670
+ this.previous = this.next;
671
+ this.highest.commit();
672
+ this.lowest.commit();
673
+ }
674
+ }
675
+
676
+ // ── More composites ──────────────────────────────────────────────────────────
677
+
678
+ /** `ta.hma(source, length)`: wma(2 * wma(source, length / 2) - wma(source, length), floor(sqrt(length))). */
679
+ export class HmaStep implements BarStep<[value: number], number> {
680
+ private readonly half = new WmaStep();
681
+ private readonly full = new WmaStep();
682
+ private readonly outer = new WmaStep();
683
+ private readonly halfLength: number;
684
+ private readonly sqrtLength: number;
685
+
686
+ constructor(private readonly length: number) {
687
+ checkPositiveLength('hma', length, 0);
688
+ this.halfLength = Math.floor(length / 2);
689
+ this.sqrtLength = Math.floor(Math.sqrt(length));
690
+ }
691
+
692
+ step(value: number): number {
693
+ const diff = 2 * this.half.step(value, this.halfLength) - this.full.step(value, this.length);
694
+ return this.outer.step(diff, this.sqrtLength);
695
+ }
696
+
697
+ commit(): void {
698
+ this.half.commit();
699
+ this.full.commit();
700
+ this.outer.commit();
701
+ }
702
+ }
703
+
704
+ /** `ta.dev(source, length)`: the mean of |source - sma| over the last `length` bars (na until bar length - 1). */
705
+ export class DevStep extends HistoryStep<[value: number], number> {
706
+ private readonly mean = new SmaStep();
707
+ private readonly len: number;
708
+
709
+ constructor(length: number) {
710
+ super();
711
+ checkPositiveLength('dev', length, 0);
712
+ this.len = Math.floor(length);
713
+ }
714
+
715
+ step(value: number): number {
716
+ this.keep(value);
717
+ const mean = this.mean.step(value, this.len);
718
+ if (this.history.length < this.len - 1 || Number.isNaN(mean)) return NaN;
719
+ let sum = 0;
720
+ for (let k = 0; k < this.len; k++) sum += Math.abs((k === 0 ? value : this.back(k)) - mean);
721
+ return sum / this.len;
722
+ }
723
+
724
+ override commit(): void {
725
+ super.commit();
726
+ this.mean.commit();
727
+ }
728
+ }
729
+
730
+ /** `ta.cci(source, length)`: (source - sma) / (0.015 * dev); a zero dev keeps the previous value (0 at the start). */
731
+ export class CciStep implements BarStep<[value: number], number> {
732
+ private readonly mean = new SmaStep();
733
+ private readonly dev: DevStep;
734
+ private last = 0;
735
+ private next = 0;
736
+ private stepped = false;
737
+
738
+ constructor(private readonly length: number) {
739
+ checkPositiveLength('cci', length, 0);
740
+ this.dev = new DevStep(length);
741
+ }
742
+
743
+ step(value: number): number {
744
+ this.stepped = true;
745
+ this.next = this.last;
746
+ const mean = this.mean.step(value, this.length);
747
+ const d = this.dev.step(value);
748
+ if (Number.isNaN(mean) || Number.isNaN(d)) return NaN;
749
+ if (!eq(d, 0)) this.next = (value - mean) / (0.015 * d);
750
+ return this.next;
751
+ }
752
+
753
+ commit(): void {
754
+ if (this.stepped) this.last = this.next;
755
+ this.stepped = false;
756
+ this.mean.commit();
757
+ this.dev.commit();
758
+ }
759
+ }
760
+
761
+ /** `ta.mfi(source, length)`: the window sums of the money flow of the up and down bars. */
762
+ export class MfiStep extends HistoryStep<[value: number, volume: number], number> {
763
+ private readonly upper = new SumStep();
764
+ private readonly lower = new SumStep();
765
+
766
+ constructor(private readonly length: number) {
767
+ super();
768
+ checkPositiveLength('mfi', length, 0);
769
+ }
770
+
771
+ step(value: number, volume: number): number {
772
+ this.keep(value);
773
+ const change = this.history.length === 0 ? NaN : value - this.back(1);
774
+ const flow = volume * value;
775
+ const zero = (x: number): number => (Math.abs(x) <= 1e-10 ? 0 : x);
776
+ const u = zero(this.upper.step(le(change, 0) ? 0 : flow, this.length));
777
+ const l = zero(this.lower.step(ge(change, 0) ? 0 : flow, this.length));
778
+ if (Number.isNaN(u) || Number.isNaN(l)) return NaN;
779
+ if (l === 0) return 100;
780
+ const ratio = 1 + u / l;
781
+ return ratio === 0 ? NaN : 100 - 100 / ratio;
782
+ }
783
+
784
+ override commit(): void {
785
+ super.commit();
786
+ this.upper.commit();
787
+ this.lower.commit();
788
+ }
789
+ }
790
+
791
+ /** `ta.dmi(diLength, adxSmoothing)`: [+DI, -DI, ADX]; a DI that cannot be computed keeps the previous one. */
792
+ export class DmiStep implements BarStep<[high: number, low: number, close: number], [number, number, number]> {
793
+ private readonly tr = new TrStep(false);
794
+ private readonly trur: RmaStep;
795
+ private readonly plus: RmaStep;
796
+ private readonly minus: RmaStep;
797
+ private readonly adx: RmaStep;
798
+ private prevHigh = NaN;
799
+ private prevLow = NaN;
800
+ private bars = 0;
801
+ private lastPlus = NaN;
802
+ private lastMinus = NaN;
803
+ private next: [number, number, number, number] = [NaN, NaN, NaN, NaN];
804
+ private stepped = false;
805
+
806
+ constructor(diLength: number, adxSmoothing: number) {
807
+ this.trur = new RmaStep(diLength);
808
+ this.plus = new RmaStep(diLength);
809
+ this.minus = new RmaStep(diLength);
810
+ this.adx = new RmaStep(adxSmoothing);
811
+ }
812
+
813
+ step(high: number, low: number, close: number): [number, number, number] {
814
+ this.stepped = true;
815
+ const up = this.bars === 0 ? NaN : high - this.prevHigh;
816
+ const down = this.bars === 0 ? NaN : this.prevLow - low;
817
+ const plusDM = Number.isNaN(up) ? NaN : gt(up, down) && gt(up, 0) ? up : 0;
818
+ const minusDM = Number.isNaN(down) ? NaN : gt(down, up) && gt(down, 0) ? down : 0;
819
+ const t = this.trur.step(this.tr.step(high, low, close));
820
+ const directional = (v: number, last: number): number => {
821
+ const value = t === 0 ? NaN : (100 * v) / t;
822
+ return Number.isNaN(value) ? last : value;
823
+ };
824
+ const plus = directional(this.plus.step(plusDM), this.lastPlus);
825
+ const minus = directional(this.minus.step(minusDM), this.lastMinus);
826
+ const sum = plus + minus;
827
+ const dx = Math.abs(plus - minus) / (eq(sum, 0) ? 1 : sum);
828
+ const adx = 100 * this.adx.step(dx);
829
+ this.next = [plus, minus, high, low];
830
+ return [plus, minus, adx];
831
+ }
832
+
833
+ commit(): void {
834
+ if (!this.stepped) return;
835
+ this.stepped = false;
836
+ [this.lastPlus, this.lastMinus, this.prevHigh, this.prevLow] = this.next;
837
+ this.bars++;
838
+ this.tr.commit();
839
+ this.trur.commit();
840
+ this.plus.commit();
841
+ this.minus.commit();
842
+ this.adx.commit();
843
+ }
844
+ }
845
+
846
+ /** `ta.linreg(source, length, offset)`: least squares line of the last `length` bars (na when one of them is NaN). */
847
+ export class LinregStep extends HistoryStep<[value: number], number> {
848
+ private readonly len: number;
849
+
850
+ constructor(length: number, private readonly offset = 0) {
851
+ super();
852
+ checkPositiveLength('linreg', length, 0);
853
+ this.len = Math.floor(length);
854
+ }
855
+
856
+ step(value: number): number {
857
+ this.keep(value);
858
+ const len = this.len;
859
+ if (this.history.length < len - 1) return NaN;
860
+ const at = (j: number): number => (j === len - 1 ? value : this.back(len - 1 - j));
861
+ for (let j = 0; j < len; j++) if (isNaN(at(j))) return NaN;
862
+ let sumX = 0;
863
+ let sumY = 0;
864
+ let sumXY = 0;
865
+ let sumX2 = 0;
866
+ for (let j = 0; j < len; j++) {
867
+ const x = j + 1;
868
+ const y = at(j);
869
+ sumX += x;
870
+ sumY += y;
871
+ sumXY += x * y;
872
+ sumX2 += x * x;
873
+ }
874
+ const slope = (len * sumXY - sumX * sumY) / (len * sumX2 - sumX * sumX);
875
+ const intercept = sumY / len - (slope * sumX) / len + slope;
876
+ return intercept + slope * (len - 1 - this.offset);
877
+ }
878
+ }
879
+
880
+ /** `ta.percentrank(source, length)`: the percentage of the `length` bars before that are less than or equal to the bar. */
881
+ export class PercentrankStep extends HistoryStep<[value: number], number> {
882
+ constructor(private readonly length: number) {
883
+ super();
884
+ checkPositiveLength('percentrank', length, 0);
885
+ }
886
+
887
+ step(value: number): number {
888
+ this.keep(value);
889
+ if (this.history.length < this.length) return NaN;
890
+ let count = 0;
891
+ for (let j = 1; j <= this.length; j++) if (le(this.back(j), value)) count++;
892
+ return (count * 100) / this.length;
893
+ }
894
+ }
895
+
896
+ /** `ta.median(source, length)`: the median of the last `length` non-na values (sorted as ta.median keeps them). */
897
+ export class MedianStep implements BarStep<[value: number], number> {
898
+ private sorted: number[] = [];
899
+ private readonly kept: number[] = [];
900
+ private nextSorted: number[] | null = null;
901
+ private nextValue: number | null = null;
902
+ private stepped = false;
903
+ private readonly len: number;
904
+
905
+ constructor(length: number) {
906
+ checkPositiveLength('median', length, 0);
907
+ this.len = Math.floor(length);
908
+ }
909
+
910
+ private static bound(sorted: readonly number[], v: number, after: boolean): number {
911
+ let lo = 0;
912
+ let hi = sorted.length;
913
+ while (lo < hi) {
914
+ const m = (lo + hi) >> 1;
915
+ if (after ? sorted[m]! <= v : sorted[m]! < v) lo = m + 1;
916
+ else hi = m;
917
+ }
918
+ return lo;
919
+ }
920
+
921
+ step(value: number): number {
922
+ this.stepped = true;
923
+ const len = this.len;
924
+ let sorted = this.sorted;
925
+ let count = this.kept.length;
926
+ this.nextValue = null;
927
+ this.nextSorted = null;
928
+ if (Number.isFinite(value)) {
929
+ sorted = sorted.slice();
930
+ count++;
931
+ sorted.splice(MedianStep.bound(sorted, value, false), 0, value);
932
+ // the value that leaves the window: kept[count - 1 - len] in the order of the kept values (this one is last)
933
+ if (count > len) {
934
+ const k = count - 1 - len;
935
+ const leaving = k === this.kept.length ? value : this.kept[k]!;
936
+ sorted.splice(MedianStep.bound(sorted, leaving, true) - 1, 1);
937
+ }
938
+ this.nextValue = value;
939
+ this.nextSorted = sorted;
940
+ }
941
+ if (!(len >= 1) || count < len) return NaN;
942
+ const mid = Math.floor(len / 2);
943
+ return len % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;
944
+ }
945
+
946
+ commit(): void {
947
+ if (!this.stepped) return;
948
+ this.stepped = false;
949
+ if (this.nextValue !== null) {
950
+ this.kept.push(this.nextValue);
951
+ this.sorted = this.nextSorted!;
952
+ }
953
+ }
954
+ }
955
+
956
+ /** `ta.correlation(source1, source2, length)`: covariance over the square root of the two variances. */
957
+ export class CorrelationStep implements BarStep<[a: number, b: number], number> {
958
+ private readonly meanXY = new SmaStep();
959
+ private readonly meanX = new SmaStep();
960
+ private readonly meanY = new SmaStep();
961
+ private readonly varX = new VarianceStep();
962
+ private readonly varY = new VarianceStep();
963
+
964
+ constructor(private readonly length: number) {
965
+ checkPositiveLength('correlation', length, 0);
966
+ }
967
+
968
+ step(a: number, b: number): number {
969
+ const product = a === null || a === undefined || b === null || b === undefined ? NaN : a * b;
970
+ const mxy = this.meanXY.step(product, this.length);
971
+ const cov = mxy - this.meanX.step(a, this.length) * this.meanY.step(b, this.length);
972
+ const vx = this.varX.step(a, this.length);
973
+ const vy = this.varY.step(b, this.length);
974
+ if (Number.isNaN(cov)) return NaN;
975
+ if (Math.abs(cov) <= 1e-10) return 0;
976
+ const denominator = Math.sqrt(vx * vy);
977
+ return denominator === 0 ? NaN : cov / denominator;
978
+ }
979
+
980
+ commit(): void {
981
+ this.meanXY.commit();
982
+ this.meanX.commit();
983
+ this.meanY.commit();
984
+ this.varX.commit();
985
+ this.varY.commit();
986
+ }
987
+ }
988
+
989
+ /** `ta.wpr(length)`: 100 * (close - highest(high)) / (highest(high) - lowest(low)); na on a zero range. */
990
+ export class WprStep implements BarStep<[high: number, low: number, close: number], number> {
991
+ private readonly highest = new HighestStep();
992
+ private readonly lowest = new LowestStep();
993
+
994
+ constructor(private readonly length = 14) {
995
+ checkPositiveLength('wpr', length, 0);
996
+ }
997
+
998
+ step(high: number, low: number, close: number): number {
999
+ const hmax = this.highest.step(high, this.length);
1000
+ const range = hmax - this.lowest.step(low, this.length);
1001
+ return range === 0 ? NaN : (100 * (close - hmax)) / range;
1002
+ }
1003
+
1004
+ commit(): void {
1005
+ this.highest.commit();
1006
+ this.lowest.commit();
1007
+ }
1008
+ }
1009
+
1010
+ /** `ta.supertrend(factor, atrPeriod)`: [supertrend, direction] (bands from hl2 and the atr, as ta.supertrend). */
1011
+ export class SupertrendStep implements BarStep<[high: number, low: number, close: number], [number, number]> {
1012
+ private readonly atr: AtrStep;
1013
+ private lastLower = NaN;
1014
+ private lastUpper = NaN;
1015
+ private prevSuperTrend = NaN;
1016
+ private prevAtr = NaN;
1017
+ private prevHigh = NaN;
1018
+ private prevLow = NaN;
1019
+ private bars = 0;
1020
+ private next: [number, number, number, number, number, number] = [NaN, NaN, NaN, NaN, NaN, NaN];
1021
+ private stepped = false;
1022
+
1023
+ constructor(private readonly factor: number, atrPeriod: number, private readonly wicks = false) {
1024
+ this.atr = new AtrStep(atrPeriod);
1025
+ }
1026
+
1027
+ step(high: number, low: number, close: number): [number, number] {
1028
+ this.stepped = true;
1029
+ const nz = (v: number): number => (isNaN(v) ? 0 : v);
1030
+ const source = (high + low) / 2;
1031
+ const atr = this.atr.step(high, low, close);
1032
+ const atrValue = atr * this.factor;
1033
+ let upperBand = source + atrValue;
1034
+ let lowerBand = source - atrValue;
1035
+ const prevLowerBand = nz(this.lastLower);
1036
+ const prevUpperBand = nz(this.lastUpper);
1037
+ const highPrice = this.wicks ? high : close;
1038
+ const lowPrice = this.wicks ? low : close;
1039
+ const prevLowPrice = this.bars > 0 ? this.prevLow : NaN;
1040
+ const prevHighPrice = this.bars > 0 ? this.prevHigh : NaN;
1041
+ lowerBand = lowerBand > prevLowerBand || prevLowPrice < prevLowerBand ? lowerBand : prevLowerBand;
1042
+ upperBand = upperBand < prevUpperBand || prevHighPrice > prevUpperBand ? upperBand : prevUpperBand;
1043
+ let direction: number;
1044
+ if (this.bars === 0 || isNaN(this.prevAtr)) direction = 1;
1045
+ else if (this.prevSuperTrend === prevUpperBand) direction = highPrice > upperBand ? -1 : 1;
1046
+ else direction = lowPrice < lowerBand ? 1 : -1;
1047
+ const superTrend = direction === -1 ? lowerBand : upperBand;
1048
+ this.next = [lowerBand, upperBand, superTrend, atr, highPrice, lowPrice];
1049
+ return [superTrend, direction];
1050
+ }
1051
+
1052
+ commit(): void {
1053
+ if (!this.stepped) return;
1054
+ this.stepped = false;
1055
+ [this.lastLower, this.lastUpper, this.prevSuperTrend, this.prevAtr, this.prevHigh, this.prevLow] = this.next;
1056
+ this.bars++;
1057
+ this.atr.commit();
1058
+ }
1059
+ }
1060
+
1061
+ // ── Factories (PineScript names) ─────────────────────────────────────────────
1062
+
1063
+ /**
1064
+ * One machine per ta.* call, by PineScript name (#196): `const ema = taStep.ema(14)`, then on each bar
1065
+ * `ema.step(close)` (again on the same bar for a live update of the forming bar) and `ema.commit()` when the bar is
1066
+ * final. Driven once per bar over an array, a machine gives the doubles of the `ta` / `taCore` function.
1067
+ * The window functions take their length on each step (a series length is allowed); the others at creation.
1068
+ */
1069
+ export const taStep = {
1070
+ /** `math.sum(source, length)`: step(value, length) */
1071
+ sum: (): SumStep => new SumStep(),
1072
+ /** `ta.sma(source, length)`: step(value, length) */
1073
+ sma: (): SmaStep => new SmaStep(),
1074
+ /** `ta.variance(source, length, biased)`: step(value, length, biased?) */
1075
+ variance: (): VarianceStep => new VarianceStep(),
1076
+ /** `ta.stdev(source, length, biased)`: step(value, length, biased?) */
1077
+ stdev: (): StdevStep => new StdevStep(),
1078
+ /** `ta.ema(source, length)`: step(value) */
1079
+ ema: (length: number): EmaStep => new EmaStep(length),
1080
+ /** `ta.rma(source, length)`: step(value) */
1081
+ rma: (length: number): RmaStep => new RmaStep(length),
1082
+ /** `ta.wma(source, length)`: step(value, length) */
1083
+ wma: (): WmaStep => new WmaStep(),
1084
+ /** `ta.change(source, length)`: step(value) */
1085
+ change: (length = 1): ChangeStep => new ChangeStep(length),
1086
+ /** `ta.mom(source, length)`: step(value) */
1087
+ mom: (length: number): MomStep => new MomStep(length),
1088
+ /** `ta.roc(source, length)`: step(value) */
1089
+ roc: (length: number): RocStep => new RocStep(length),
1090
+ /** `ta.tr(handle_na)`: step(high, low, close) */
1091
+ tr: (handle_na = false): TrStep => new TrStep(handle_na),
1092
+ /** `ta.atr(length)`: step(high, low, close) */
1093
+ atr: (length: number): AtrStep => new AtrStep(length),
1094
+ /** `ta.rsi(source, length)`: step(value) */
1095
+ rsi: (length: number): RsiStep => new RsiStep(length),
1096
+ /** `ta.cum(source)`: step(value) */
1097
+ cum: (): CumStep => new CumStep(),
1098
+ /** `ta.crossover(a, b)`: step(a, b) */
1099
+ crossover: (): CrossoverStep => new CrossoverStep(),
1100
+ /** `ta.crossunder(a, b)`: step(a, b) */
1101
+ crossunder: (): CrossunderStep => new CrossunderStep(),
1102
+ /** `ta.cross(a, b)`: step(a, b) */
1103
+ cross: (): CrossStep => new CrossStep(),
1104
+ /** `ta.barssince(condition)`: step(condition) */
1105
+ barssince: (): BarssinceStep => new BarssinceStep(),
1106
+ /** `ta.valuewhen(condition, source, occurrence)`: step(condition, value) */
1107
+ valuewhen: (occurrence: number): ValuewhenStep => new ValuewhenStep(occurrence),
1108
+ /** `ta.obv`: step(close, volume) */
1109
+ obv: (): ObvStep => new ObvStep(),
1110
+ /** `ta.highest(source, length)`: step(value, length) */
1111
+ highest: (): HighestStep => new HighestStep(),
1112
+ /** `ta.lowest(source, length)`: step(value, length) */
1113
+ lowest: (): LowestStep => new LowestStep(),
1114
+ /** `ta.macd(source, fast, slow, signal)`: step(value) gives [macd, signal, histogram] */
1115
+ macd: (fastLength: number, slowLength: number, signalLength: number): MacdStep =>
1116
+ new MacdStep(fastLength, slowLength, signalLength),
1117
+ /** `ta.bb(source, length, mult)`: step(value) gives [basis, upper, lower] */
1118
+ bb: (length: number, mult: number): BbStep => new BbStep(length, mult),
1119
+ /** `ta.vwma(source, length)`: step(value, volume) */
1120
+ vwma: (length: number): VwmaStep => new VwmaStep(length),
1121
+ /** `ta.stoch(source, high, low, length)`: step(source, high, low) */
1122
+ stoch: (length: number): StochStep => new StochStep(length),
1123
+ /** `ta.hma(source, length)`: step(value) */
1124
+ hma: (length: number): HmaStep => new HmaStep(length),
1125
+ /** `ta.dev(source, length)`: step(value) */
1126
+ dev: (length: number): DevStep => new DevStep(length),
1127
+ /** `ta.cci(source, length)`: step(value) */
1128
+ cci: (length: number): CciStep => new CciStep(length),
1129
+ /** `ta.mfi(source, length)`: step(value, volume) */
1130
+ mfi: (length: number): MfiStep => new MfiStep(length),
1131
+ /** `ta.dmi(diLength, adxSmoothing)`: step(high, low, close) gives [plus, minus, adx] */
1132
+ dmi: (diLength: number, adxSmoothing: number): DmiStep => new DmiStep(diLength, adxSmoothing),
1133
+ /** `ta.linreg(source, length, offset)`: step(value), called on every bar (in an if block: callsite.linreg) */
1134
+ linreg: (length: number, offset = 0): LinregStep => new LinregStep(length, offset),
1135
+ /** `ta.percentrank(source, length)`: step(value) */
1136
+ percentrank: (length: number): PercentrankStep => new PercentrankStep(length),
1137
+ /** `ta.median(source, length)`: step(value) */
1138
+ median: (length: number): MedianStep => new MedianStep(length),
1139
+ /** `ta.correlation(source1, source2, length)`: step(a, b) */
1140
+ correlation: (length: number): CorrelationStep => new CorrelationStep(length),
1141
+ /** `ta.wpr(length)`: step(high, low, close) */
1142
+ wpr: (length = 14): WprStep => new WprStep(length),
1143
+ /** `ta.supertrend(factor, atrPeriod)`: step(high, low, close) gives [supertrend, direction] */
1144
+ supertrend: (factor: number, atrPeriod: number): SupertrendStep => new SupertrendStep(factor, atrPeriod),
1145
+ };