trading-signals 7.2.0 → 7.4.2

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2073 @@
1
+ //#region src/error/NotEnoughDataError.ts
2
+ var NotEnoughDataError = class extends Error {
3
+ constructor(requiredAmount) {
4
+ super(`Not enough data. A minimum of "${requiredAmount}" inputs is required to perform the computation.`);
5
+ Object.setPrototypeOf(this, new.target.prototype);
6
+ this.name = "NotEnoughDataError";
7
+ }
8
+ };
9
+
10
+ //#endregion
11
+ //#region src/types/Indicator.ts
12
+ const TradingSignal = {
13
+ BEARISH: "BEARISH",
14
+ BULLISH: "BULLISH",
15
+ SIDEWAYS: "SIDEWAYS",
16
+ UNKNOWN: "UNKNOWN"
17
+ };
18
+ /**
19
+ * Implements common update behaviour among indicators.
20
+ */
21
+ var TechnicalIndicator = class {
22
+ result;
23
+ getResult() {
24
+ try {
25
+ return this.getResultOrThrow();
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ getResultOrThrow() {
31
+ if (this.result === void 0) throw new NotEnoughDataError(this.getRequiredInputs());
32
+ return this.result;
33
+ }
34
+ get isStable() {
35
+ return this.result !== void 0;
36
+ }
37
+ add(input) {
38
+ return this.update(input, false);
39
+ }
40
+ replace(input) {
41
+ return this.update(input, true);
42
+ }
43
+ updates(inputs, replace = false) {
44
+ return inputs.map((input) => this.update(input, replace));
45
+ }
46
+ };
47
+ /**
48
+ * Tracks results of an indicator over time.
49
+ */
50
+ var IndicatorSeries = class extends TechnicalIndicator {
51
+ previousResult;
52
+ setResult(value, replace) {
53
+ if (replace) this.result = this.previousResult;
54
+ this.previousResult = this.result;
55
+ return this.result = value;
56
+ }
57
+ };
58
+ /**
59
+ * Calculates a signal for an indicator.
60
+ */
61
+ var TrendIndicatorSeries = class extends IndicatorSeries {
62
+ #previousSignalState;
63
+ setResult(value, replace) {
64
+ if (replace && this.previousResult !== void 0) this.#previousSignalState = this.calculateSignalState(this.previousResult);
65
+ else if (!replace) this.#previousSignalState = this.calculateSignalState(this.result);
66
+ return super.setResult(value, replace);
67
+ }
68
+ getSignal() {
69
+ const currentState = this.calculateSignalState(this.getResult());
70
+ return {
71
+ hasChanged: this.#previousSignalState !== void 0 && this.#previousSignalState !== currentState,
72
+ state: currentState
73
+ };
74
+ }
75
+ };
76
+
77
+ //#endregion
78
+ //#region src/trend/MA/MovingAverage.ts
79
+ /**
80
+ * Moving Average (MA)
81
+ * Type: Trend
82
+ *
83
+ * Base class for trend-following (lagging) indicators. The longer the moving average interval, the greater the lag.
84
+ *
85
+ * @see https://www.investopedia.com/terms/m/movingaverage.asp
86
+ */
87
+ var MovingAverage = class extends IndicatorSeries {
88
+ constructor(interval) {
89
+ super();
90
+ this.interval = interval;
91
+ }
92
+ };
93
+
94
+ //#endregion
95
+ //#region src/util/getAverage.ts
96
+ /**
97
+ * Return the mean / average value.
98
+ */
99
+ function getAverage(values) {
100
+ return values.length ? values.reduce((sum, x) => sum + x, 0) / values.length : 0;
101
+ }
102
+
103
+ //#endregion
104
+ //#region src/util/pushUpdate.ts
105
+ /**
106
+ * Adds an item to the array or replaces the last item in the array.
107
+ * If the array limit size is exceeded, the oldest array element will be removed and returned by the function.
108
+ */
109
+ function pushUpdate(array, replace, item, maxLength) {
110
+ if (array.length > 0 && replace === true) array[array.length - 1] = item;
111
+ else array.push(item);
112
+ if (array.length > maxLength) return array.shift();
113
+ return null;
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/trend/SMA/SMA.ts
118
+ /**
119
+ * Simple Moving Average (SMA)
120
+ * Type: Trend
121
+ *
122
+ * The Simple Moving Average (SMA) creates an average of all prices within a fixed interval. The SMA weights the prices of all periods equally which makes it not as responsive to recent prices as the EMA.
123
+ *
124
+ * @see https://www.investopedia.com/terms/s/sma.asp
125
+ */
126
+ var SMA = class extends MovingAverage {
127
+ prices = [];
128
+ getRequiredInputs() {
129
+ return this.interval;
130
+ }
131
+ update(price, replace) {
132
+ pushUpdate(this.prices, replace, price, this.interval);
133
+ if (this.prices.length === this.interval) return this.setResult(getAverage(this.prices), replace);
134
+ return null;
135
+ }
136
+ };
137
+
138
+ //#endregion
139
+ //#region src/momentum/AO/AO.ts
140
+ /**
141
+ * Awesome Oscillator (AO)
142
+ * Type: Momentum
143
+ *
144
+ * The Awesome Oscillator (AO) is an indicator used to measure market momentum.
145
+ * It has been developed by the technical analyst and charting enthusiast Bill Williams.
146
+ *
147
+ * When AO crosses above Zero, short term momentum is rising faster than long term momentum which signals a bullish
148
+ * buying opportunity.
149
+ *
150
+ * When AO crosses below Zero, short term momentum is falling faster then the long term momentum
151
+ * which signals a bearish selling opportunity.
152
+ *
153
+ * @see https://www.tradingview.com/support/solutions/43000501826-awesome-oscillator-ao/
154
+ * @see https://tradingstrategyguides.com/bill-williams-awesome-oscillator-strategy/
155
+ */
156
+ var AO = class extends TrendIndicatorSeries {
157
+ long;
158
+ short;
159
+ constructor(shortInterval, longInterval, SmoothingIndicator = SMA) {
160
+ super();
161
+ this.shortInterval = shortInterval;
162
+ this.longInterval = longInterval;
163
+ this.short = new SmoothingIndicator(shortInterval);
164
+ this.long = new SmoothingIndicator(longInterval);
165
+ }
166
+ getRequiredInputs() {
167
+ return this.long.getRequiredInputs();
168
+ }
169
+ update({ low, high }, replace) {
170
+ const medianPrice = (low + high) / 2;
171
+ this.short.update(medianPrice, replace);
172
+ this.long.update(medianPrice, replace);
173
+ if (this.long.isStable) return this.setResult(this.short.getResultOrThrow() - this.long.getResultOrThrow(), replace);
174
+ return null;
175
+ }
176
+ calculateSignalState(result) {
177
+ const hasResult = result !== null && result !== void 0;
178
+ const isBullish = hasResult && result > 0;
179
+ const isBearish = hasResult && result < 0;
180
+ switch (true) {
181
+ case !hasResult: return TradingSignal.UNKNOWN;
182
+ case isBullish: return TradingSignal.BULLISH;
183
+ case isBearish: return TradingSignal.BEARISH;
184
+ default: return TradingSignal.SIDEWAYS;
185
+ }
186
+ }
187
+ };
188
+
189
+ //#endregion
190
+ //#region src/momentum/MOM/MOM.ts
191
+ /**
192
+ * Momentum Indicator (MOM / MTM)
193
+ * Type: Momentum
194
+ *
195
+ * The Momentum indicator returns the change between the current price and the price n times ago.
196
+ *
197
+ * @see https://en.wikipedia.org/wiki/Momentum_(technical_analysis)
198
+ * @see https://www.warriortrading.com/momentum-indicator/
199
+ */
200
+ var MOM = class extends TrendIndicatorSeries {
201
+ #history;
202
+ #historyLength;
203
+ constructor(interval) {
204
+ super();
205
+ this.interval = interval;
206
+ this.#historyLength = interval + 1;
207
+ this.#history = [];
208
+ }
209
+ getRequiredInputs() {
210
+ return this.#historyLength;
211
+ }
212
+ update(value, replace) {
213
+ pushUpdate(this.#history, replace, value, this.#historyLength);
214
+ if (this.#history.length === this.#historyLength) return this.setResult(value - this.#history[0], replace);
215
+ return null;
216
+ }
217
+ calculateSignalState(result) {
218
+ if (!(result !== null && result !== void 0)) return TradingSignal.UNKNOWN;
219
+ if (result > 0) return TradingSignal.BULLISH;
220
+ if (result < 0) return TradingSignal.BEARISH;
221
+ return TradingSignal.SIDEWAYS;
222
+ }
223
+ };
224
+
225
+ //#endregion
226
+ //#region src/momentum/AC/AC.ts
227
+ /**
228
+ * Accelerator Oscillator (AC)
229
+ * Type: Momentum
230
+ *
231
+ * The Accelerator Oscillator (AC) is an indicator used to detect when a momentum changes. It has been developed by Bill Williams. If the momentum in an uptrend is starting to slow down, that could suggest that there is less interest in the asset. This typically leads to selling. In the inverse, momentum to the downside will start to slow down before buy orders come in. The Accelerator Oscillator also looks at whether there is an acceleration in the change of momentum.
232
+ *
233
+ * @see https://www.thinkmarkets.com/en/indicators/bill-williams-accelerator/
234
+ * @see https://help.quantower.com/quantower/analytics-panels/chart/technical-indicators/oscillators/accelerator-oscillator
235
+ */
236
+ var AC = class extends TrendIndicatorSeries {
237
+ ao;
238
+ momentum;
239
+ signal;
240
+ constructor(shortAO, longAO, signalInterval) {
241
+ super();
242
+ this.shortAO = shortAO;
243
+ this.longAO = longAO;
244
+ this.signalInterval = signalInterval;
245
+ this.ao = new AO(shortAO, longAO);
246
+ this.momentum = new MOM(1);
247
+ this.signal = new SMA(signalInterval);
248
+ }
249
+ getRequiredInputs() {
250
+ return this.ao.getRequiredInputs() + this.signal.getRequiredInputs();
251
+ }
252
+ update(input, replace) {
253
+ const ao = this.ao.update(input, replace);
254
+ if (ao) {
255
+ this.signal.update(ao, replace);
256
+ if (this.signal.isStable) {
257
+ const result = this.setResult(ao - this.signal.getResultOrThrow(), replace);
258
+ this.momentum.update(result, replace);
259
+ return result;
260
+ }
261
+ }
262
+ return null;
263
+ }
264
+ calculateSignalState(result) {
265
+ const hasResult = result !== null && result !== void 0;
266
+ const isPositive = hasResult && result > 0;
267
+ switch (true) {
268
+ case !hasResult: return TradingSignal.UNKNOWN;
269
+ case isPositive: return TradingSignal.BULLISH;
270
+ default: return TradingSignal.BEARISH;
271
+ }
272
+ }
273
+ };
274
+
275
+ //#endregion
276
+ //#region src/util/getGrid.ts
277
+ function getGrid({ lower, upper, levels, tickSize, spacing }) {
278
+ const prices = [];
279
+ if (spacing === "arithmetic") {
280
+ const step = (upper - lower) / (levels - 1);
281
+ for (let i = 0; i < levels; i++) prices.push(lower + step * i);
282
+ } else {
283
+ const ratio = Math.pow(upper / lower, 1 / (levels - 1));
284
+ for (let i = 0; i < levels; i++) prices.push(lower * Math.pow(ratio, i));
285
+ }
286
+ if (tickSize) {
287
+ const roundToTick = (x) => Math.round(x / tickSize) * tickSize;
288
+ return prices.map(roundToTick);
289
+ }
290
+ return prices;
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/util/getMaximum.ts
295
+ function getMaximum(values) {
296
+ let max = Number.MIN_SAFE_INTEGER;
297
+ for (const value of values) if (max < value) max = value;
298
+ return max;
299
+ }
300
+
301
+ //#endregion
302
+ //#region src/util/getMedian.ts
303
+ function getMedian(values) {
304
+ const n = values.length;
305
+ if (n === 0) throw new Error("Cannot calculate median of empty array");
306
+ if (n % 2 === 0) return (values[n / 2 - 1] + values[n / 2]) / 2;
307
+ return values[Math.floor(n / 2)];
308
+ }
309
+
310
+ //#endregion
311
+ //#region src/util/getMinimum.ts
312
+ function getMinimum(values) {
313
+ let min = Number.MAX_SAFE_INTEGER;
314
+ for (const value of values) if (min > value) min = value;
315
+ return min;
316
+ }
317
+
318
+ //#endregion
319
+ //#region src/util/getQuartile.ts
320
+ function getQuartile(values, q) {
321
+ const sorted = [...values].sort((a, b) => a - b);
322
+ const n = sorted.length;
323
+ const medianIndex = Math.floor(n / 2);
324
+ if (q === .25) return getMedian(sorted.slice(0, medianIndex));
325
+ else if (q === .75) {
326
+ if (n % 2 === 0) return getMedian(sorted.slice(medianIndex));
327
+ return getMedian(sorted.slice(medianIndex + 1));
328
+ }
329
+ const pos = (sorted.length - 1) * q;
330
+ const base = Math.floor(pos);
331
+ const rest = pos - base;
332
+ return sorted[base] + (sorted[base + 1] - sorted[base]) * rest;
333
+ }
334
+
335
+ //#endregion
336
+ //#region src/util/getStandardDeviation.ts
337
+ /**
338
+ * Standard deviation calculates how prices for a collection of prices are spread out from the average price of these
339
+ * prices. Standard deviation makes outliers even more visible than mean absolute deviation (MAD).
340
+ *
341
+ * @see https://www.mathsisfun.com/data/standard-deviation-formulas.html
342
+ * @see https://www.youtube.com/watch?v=9-8E8L_77-8
343
+ */
344
+ function getStandardDeviation(values, average) {
345
+ const middle = average || getAverage(values);
346
+ const averageDifference = getAverage(values.map((value) => value - middle).map((value) => value * value));
347
+ return Math.sqrt(averageDifference);
348
+ }
349
+
350
+ //#endregion
351
+ //#region src/util/getStreaks.ts
352
+ /**
353
+ * Tracks the lengths (streaks) of continuous price movements (up or down).
354
+ *
355
+ * @param prices A series of prices
356
+ * @param keepSide If you want to receive only uptrends or downtrends
357
+ * @returns An array of objects representing the filtered streaks
358
+ */
359
+ function getStreaks(prices, keepSide) {
360
+ const streaks = [];
361
+ let currentStreak = 0;
362
+ function saveStreak(i) {
363
+ const endPrice = prices[i - 1];
364
+ const startPrice = prices[i - currentStreak - 1];
365
+ const percentage = (endPrice - startPrice) / startPrice * 100;
366
+ streaks.push({
367
+ length: currentStreak,
368
+ percentage
369
+ });
370
+ }
371
+ for (let i = 1; i < prices.length; i++) {
372
+ const isUpward = keepSide === "up" && prices[i] > prices[i - 1];
373
+ const isDownward = keepSide === "down" && prices[i] < prices[i - 1];
374
+ if (isUpward || isDownward) currentStreak++;
375
+ else {
376
+ if (currentStreak > 0) saveStreak(i);
377
+ currentStreak = 0;
378
+ }
379
+ }
380
+ if (currentStreak > 0) saveStreak(prices.length);
381
+ return streaks;
382
+ }
383
+
384
+ //#endregion
385
+ //#region src/util/getWeekday.ts
386
+ /**
387
+ * Get the weekday name for a given date in a specific timezone.
388
+ * Uses IANA timezone identifiers (e.g., 'America/New_York', 'Europe/London').
389
+ */
390
+ function getWeekday(timezone, date = new Date(Date.now())) {
391
+ return new Intl.DateTimeFormat("en-US", {
392
+ timeZone: timezone,
393
+ weekday: "long"
394
+ }).format(date);
395
+ }
396
+ function isMonday(timezone, date = new Date(Date.now())) {
397
+ return getWeekday(timezone, date) === "Monday";
398
+ }
399
+ function isTuesday(timezone, date = new Date(Date.now())) {
400
+ return getWeekday(timezone, date) === "Tuesday";
401
+ }
402
+ function isWednesday(timezone, date = new Date(Date.now())) {
403
+ return getWeekday(timezone, date) === "Wednesday";
404
+ }
405
+ function isThursday(timezone, date = new Date(Date.now())) {
406
+ return getWeekday(timezone, date) === "Thursday";
407
+ }
408
+ function isFriday(timezone, date = new Date(Date.now())) {
409
+ return getWeekday(timezone, date) === "Friday";
410
+ }
411
+ function isSaturday(timezone, date = new Date(Date.now())) {
412
+ return getWeekday(timezone, date) === "Saturday";
413
+ }
414
+ function isSunday(timezone, date = new Date(Date.now())) {
415
+ return getWeekday(timezone, date) === "Sunday";
416
+ }
417
+
418
+ //#endregion
419
+ //#region src/volatility/MAD/MAD.ts
420
+ /**
421
+ * Mean Absolute Deviation (MAD)
422
+ * Type: Volatility
423
+ *
424
+ * The mean absolute deviation (MAD) is calculating the absolute deviation / difference from the mean over a period. Large outliers will reflect in a higher MAD.
425
+ *
426
+ * @see https://en.wikipedia.org/wiki/Average_absolute_deviation
427
+ */
428
+ var MAD = class extends IndicatorSeries {
429
+ prices = [];
430
+ constructor(interval) {
431
+ super();
432
+ this.interval = interval;
433
+ }
434
+ getRequiredInputs() {
435
+ return this.interval;
436
+ }
437
+ update(price, replace) {
438
+ pushUpdate(this.prices, replace, price, this.interval);
439
+ if (this.prices.length === this.interval) {
440
+ const mean = getAverage(this.prices);
441
+ let sum = 0;
442
+ for (let i = 0; i < this.interval; i++) {
443
+ const deviation = Math.abs(this.prices[i] - mean);
444
+ sum += deviation;
445
+ }
446
+ return this.setResult(sum / this.interval, replace);
447
+ }
448
+ return null;
449
+ }
450
+ static getResultFromBatch(prices, average) {
451
+ if (prices.length === 0) return 0;
452
+ const mean = average || getAverage(prices);
453
+ let sum = 0;
454
+ for (let i = 0; i < prices.length; i++) {
455
+ const deviation = Math.abs(prices[i] - mean);
456
+ sum += deviation;
457
+ }
458
+ return sum / prices.length;
459
+ }
460
+ };
461
+
462
+ //#endregion
463
+ //#region src/momentum/CCI/CCI.ts
464
+ /**
465
+ * Commodity Channel Index (CCI)
466
+ * Type: Momentum
467
+ *
468
+ * The Commodity Channel Index (CCI), developed by Donald Lambert in 1980, compares the current mean price with the
469
+ * average mean price over a period of time. Approximately 70 to 80 percent of CCI values are between −100 and +100,
470
+ * which makes it an oscillator. Values above +100 imply an overbought condition, while values below −100 imply an
471
+ * oversold condition.
472
+ *
473
+ * According to
474
+ * [Investopia.com](https://www.investopedia.com/articles/active-trading/031914/how-traders-can-utilize-cci-commodity-channel-index-trade-stock-trends.asp#multiple-timeframe-cci-strategy),
475
+ * traders often buy when the CCI dips below -100 and then rallies back above -100 to sell the security when it moves
476
+ * above +100 and then drops back below +100.
477
+ *
478
+ * Interpretation:
479
+ * -100 and below: Indicates an oversold condition or the start of a strong downtrend.
480
+ * +100 and above: Indicates an overbought condition or the start of a strong uptrend.
481
+ * Values near 0 often signal a lack of clear momentum.
482
+ *
483
+ * Note: Traders often combine CCI with other indicators to confirm trends or signals, as using it alone can lead to false signals.
484
+ * It's particularly useful in volatile markets or when identifying shorter-term trading opportunities.
485
+ *
486
+ * @see https://en.wikipedia.org/wiki/Commodity_channel_index
487
+ */
488
+ var CCI = class extends TrendIndicatorSeries {
489
+ #sma;
490
+ #typicalPrices;
491
+ constructor(interval) {
492
+ super();
493
+ this.interval = interval;
494
+ this.#sma = new SMA(this.interval);
495
+ this.#typicalPrices = [];
496
+ }
497
+ getRequiredInputs() {
498
+ return this.#sma.getRequiredInputs();
499
+ }
500
+ update(candle, replace) {
501
+ const typicalPrice = this.#cacheTypicalPrice(candle, replace);
502
+ this.#sma.update(typicalPrice, replace);
503
+ if (this.#sma.isStable) {
504
+ const mean = this.#sma.getResultOrThrow();
505
+ const meanDeviation = MAD.getResultFromBatch(this.#typicalPrices, mean);
506
+ const numerator = typicalPrice - mean;
507
+ const denominator = .015 * meanDeviation;
508
+ return this.setResult(numerator / denominator, replace);
509
+ }
510
+ return null;
511
+ }
512
+ #cacheTypicalPrice({ high, low, close }, replace) {
513
+ const typicalPrice = (high + low + close) / 3;
514
+ pushUpdate(this.#typicalPrices, replace, typicalPrice, this.interval);
515
+ return typicalPrice;
516
+ }
517
+ calculateSignalState(result) {
518
+ const hasResult = result !== null && result !== void 0;
519
+ const isOversold = hasResult && result <= -100;
520
+ const isOverbought = hasResult && result >= 100;
521
+ switch (true) {
522
+ case !hasResult: return TradingSignal.UNKNOWN;
523
+ case isOversold: return TradingSignal.BEARISH;
524
+ case isOverbought: return TradingSignal.BULLISH;
525
+ default: return TradingSignal.SIDEWAYS;
526
+ }
527
+ }
528
+ };
529
+
530
+ //#endregion
531
+ //#region src/momentum/CG/CG.ts
532
+ /**
533
+ * Center of Gravity (CG)
534
+ * Type: Momentum
535
+ *
536
+ * Implementation of the Center of Gravity (CG) oscillator by John Ehlers. The Center of Gravity (CG) aims to identify turning points in price action with minimal lag (leading indicator). Peaks and troughs in CG can precede actual price highs and lows. The CG is often paired with its own signal line for entry/exit triggers.
537
+ *
538
+ * Interpretation:
539
+ * Crossing the zero line may suggest a shift in trend.
540
+ *
541
+ * Note:
542
+ * - According to the specification, the price inputs shall be calculated the following way: ((High Price + Low Price) / 2)
543
+ * - The selected interval should be half the dominant cycle length (signal line)
544
+ * - If the interval gets too short, the CG oscillator loses its smoothing and gets a little too nervous for profitable trading
545
+ * @see http://www.mesasoftware.com/papers/TheCGOscillator.pdf
546
+ */
547
+ var CG = class extends TrendIndicatorSeries {
548
+ signal;
549
+ prices = [];
550
+ get isStable() {
551
+ return this.signal.isStable;
552
+ }
553
+ constructor(interval, signalInterval) {
554
+ super();
555
+ this.interval = interval;
556
+ this.signalInterval = signalInterval;
557
+ this.signal = new SMA(signalInterval);
558
+ }
559
+ getRequiredInputs() {
560
+ return this.signal.getRequiredInputs();
561
+ }
562
+ calculateSignalState(result) {
563
+ const hasResult = result !== null && result !== void 0;
564
+ const signalValue = this.signal.getResult();
565
+ const hasSignal = signalValue !== null;
566
+ const isAboveSignal = hasResult && hasSignal && result > signalValue;
567
+ const isBelowSignal = hasResult && hasSignal && result < signalValue;
568
+ switch (true) {
569
+ case !hasResult || !hasSignal: return TradingSignal.UNKNOWN;
570
+ case isAboveSignal: return TradingSignal.BULLISH;
571
+ case isBelowSignal: return TradingSignal.BEARISH;
572
+ default: return TradingSignal.SIDEWAYS;
573
+ }
574
+ }
575
+ update(price, replace) {
576
+ pushUpdate(this.prices, replace, price, this.interval);
577
+ let nominator = 0;
578
+ let denominator = 0;
579
+ for (let i = 0; i < this.prices.length; ++i) {
580
+ const price$1 = this.prices[i];
581
+ nominator = nominator + price$1 * (i + 1);
582
+ denominator = denominator + price$1;
583
+ }
584
+ const cg = denominator > 0 ? nominator / denominator : 0;
585
+ this.signal.update(cg, replace);
586
+ if (this.signal.isStable) return this.setResult(cg, replace);
587
+ return null;
588
+ }
589
+ };
590
+
591
+ //#endregion
592
+ //#region src/momentum/MACD/MACD.ts
593
+ /**
594
+ * Moving Average Convergence Divergence (MACD)
595
+ * Type: Momentum
596
+ *
597
+ * The MACD triggers trading signals when it crosses above (bullish buying opportunity) or below (bearish selling
598
+ * opportunity) its signal line. MACD can be used together with the RSI to provide a more accurate trading signal.
599
+ *
600
+ * @see https://www.investopedia.com/terms/m/macd.asp
601
+ */
602
+ var MACD = class extends TechnicalIndicator {
603
+ prices = [];
604
+ #previousResult;
605
+ constructor(short, long, signal) {
606
+ super();
607
+ this.short = short;
608
+ this.long = long;
609
+ this.signal = signal;
610
+ }
611
+ getRequiredInputs() {
612
+ return this.long.getRequiredInputs();
613
+ }
614
+ update(price, replace) {
615
+ pushUpdate(this.prices, replace, price, this.long.interval);
616
+ const short = this.short.update(price, replace);
617
+ const long = this.long.update(price, replace);
618
+ if (this.prices.length === this.long.interval) {
619
+ const macd = short - long;
620
+ const signal = this.signal.update(macd, replace);
621
+ if (replace) this.result = this.#previousResult;
622
+ this.#previousResult = this.result;
623
+ return this.result = {
624
+ histogram: macd - signal,
625
+ macd,
626
+ signal
627
+ };
628
+ }
629
+ return null;
630
+ }
631
+ calculateSignal(result) {
632
+ const hasResult = result !== null && result !== void 0;
633
+ const isBullish = hasResult && result.histogram > 0;
634
+ const isBearish = hasResult && result.histogram < 0;
635
+ switch (true) {
636
+ case !hasResult: return TradingSignal.UNKNOWN;
637
+ case isBullish: return TradingSignal.BULLISH;
638
+ case isBearish:
639
+ default: return TradingSignal.BEARISH;
640
+ }
641
+ }
642
+ getSignal() {
643
+ const previousState = this.calculateSignal(this.#previousResult);
644
+ const state = this.calculateSignal(this.getResult());
645
+ return {
646
+ hasChanged: previousState !== state,
647
+ state
648
+ };
649
+ }
650
+ };
651
+
652
+ //#endregion
653
+ //#region src/momentum/OBV/OBV.ts
654
+ /**
655
+ * On-Balance Volume (OBV)
656
+ * Type: Momentum
657
+ *
658
+ * On-balance volume (OBV) is a technical trading momentum indicator that uses volume flow to predict changes in stock price. Joseph Granville first developed the OBV metric in the 1963 book Granville's New Key to Stock Market Profits.
659
+ *
660
+ * @see https://www.investopedia.com/terms/o/onbalancevolume.asp
661
+ */
662
+ var OBV = class extends TrendIndicatorSeries {
663
+ candles = [];
664
+ constructor(interval) {
665
+ super();
666
+ this.interval = interval;
667
+ }
668
+ getRequiredInputs() {
669
+ return this.interval;
670
+ }
671
+ update(candle, replace) {
672
+ pushUpdate(this.candles, replace, candle, this.getRequiredInputs());
673
+ if (this.candles.length < this.getRequiredInputs()) return null;
674
+ const prevPrice = this.candles[this.candles.length - 2].close;
675
+ const prevResult = this.result ?? 0;
676
+ const currentPrice = candle.close;
677
+ const nextResult = currentPrice > prevPrice ? candle.volume : currentPrice < prevPrice ? -candle.volume : 0;
678
+ return this.setResult(prevResult + nextResult, false);
679
+ }
680
+ calculateSignalState(result) {
681
+ const hasResult = result !== null && result !== void 0;
682
+ const previousResult = this.previousResult;
683
+ const hasPreviousResult = previousResult !== void 0;
684
+ const isBullish = hasResult && hasPreviousResult && result > previousResult;
685
+ const isBearish = hasResult && hasPreviousResult && result < previousResult;
686
+ switch (true) {
687
+ case !hasResult: return TradingSignal.UNKNOWN;
688
+ case isBullish: return TradingSignal.BULLISH;
689
+ case isBearish: return TradingSignal.BEARISH;
690
+ default: return TradingSignal.SIDEWAYS;
691
+ }
692
+ }
693
+ };
694
+
695
+ //#endregion
696
+ //#region src/momentum/REI/REI.ts
697
+ /**
698
+ * Range Expansion Index (REI)
699
+ * Type: Momentum Oscillator
700
+ *
701
+ * The Range Expansion Index (REI) is a momentum oscillator, measuring the velocity and magnitude of directional price movements. Developed by Thomas DeMark, it compares the current day's range to the average range over a given period. It quantifies whether the current price range represents a contraction or expansion compared to the average. The REI is most typically used on an 8 day timeframe. Extreme REI values often signal potential reversal points, as they reflect sharp directional moves that may not be sustainable.
702
+ *
703
+ * Interpretation:
704
+ * According to Thomas DeMark, potential shifts in momentum when the REI rises above +60 and then drops below (price weakness). Conversely, when it falls below -60 and then climbs back above, it may signal price strength.
705
+ *
706
+ * - REI > +60: Overbought condition — strong upward momentum that may be unsustainable (when crossed from above)
707
+ * - REI between +60 and -60: Neutral zone — the market is neither gaining upward strength nor showing downside pressure
708
+ * - REI < -60: Oversold condition — strong downward momentum that could reverse (when crossed from below)
709
+ *
710
+ * @see https://en.wikipedia.org/wiki/Range_expansion_index
711
+ * @see https://www.quantifiedstrategies.com/range-expansion-index/
712
+ * @see https://www.prorealcode.com/prorealtime-indicators/range-expansion-index-rei/
713
+ * @see https://github.com/EarnForex/Range-Expansion-Index
714
+ * @see https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=448
715
+ */
716
+ var REI = class extends TrendIndicatorSeries {
717
+ #highs = [];
718
+ #lows = [];
719
+ #closes = [];
720
+ constructor(interval) {
721
+ super();
722
+ this.interval = interval;
723
+ }
724
+ calculateSignalState(result) {
725
+ const hasResult = result !== null && result !== void 0;
726
+ const isOverbought = hasResult && result > 60;
727
+ const isOversold = hasResult && result < -60;
728
+ switch (true) {
729
+ case !hasResult: return TradingSignal.UNKNOWN;
730
+ case isOverbought: return TradingSignal.BULLISH;
731
+ case isOversold: return TradingSignal.BEARISH;
732
+ default: return TradingSignal.SIDEWAYS;
733
+ }
734
+ }
735
+ getRequiredInputs() {
736
+ return this.interval + 8;
737
+ }
738
+ #calculateN(j) {
739
+ if (this.#highs[j - 2] < this.#closes[j - 7] && this.#highs[j - 2] < this.#closes[j - 8] && this.#highs[j] < this.#highs[j - 5] && this.#highs[j] < this.#highs[j - 6]) return 0;
740
+ return 1;
741
+ }
742
+ #calculateM(j) {
743
+ if (this.#lows[j - 2] > this.#closes[j - 7] && this.#lows[j - 2] > this.#closes[j - 8] && this.#lows[j] > this.#lows[j - 5] && this.#lows[j] > this.#lows[j - 6]) return 0;
744
+ return 1;
745
+ }
746
+ update(candle, replace) {
747
+ if (replace) {
748
+ this.#highs.pop();
749
+ this.#lows.pop();
750
+ this.#closes.pop();
751
+ }
752
+ this.#highs.push(candle.high);
753
+ this.#lows.push(candle.low);
754
+ this.#closes.push(candle.close);
755
+ if (this.#highs.length < this.getRequiredInputs()) return null;
756
+ let subValueSum = 0;
757
+ let absValueSum = 0;
758
+ const limitIndex = this.#highs.length - 1;
759
+ for (let j = limitIndex; j > this.interval; j--) {
760
+ const diffHighs = this.#highs[j] - this.#highs[j - 2];
761
+ const diffLows = this.#lows[j] - this.#lows[j - 2];
762
+ const n = this.#calculateN(j);
763
+ const m = this.#calculateM(j);
764
+ const s = diffHighs + diffLows;
765
+ const subValue = n * m * s;
766
+ const absDailyValue = Math.abs(diffHighs) + Math.abs(diffLows);
767
+ subValueSum += subValue;
768
+ absValueSum += absDailyValue;
769
+ }
770
+ if (absValueSum === 0) return this.setResult(0, replace);
771
+ const rei = subValueSum / absValueSum * 100;
772
+ return this.setResult(rei, replace);
773
+ }
774
+ };
775
+
776
+ //#endregion
777
+ //#region src/momentum/ROC/ROC.ts
778
+ /**
779
+ * Rate Of Change Indicator (ROC)
780
+ * Type: Momentum
781
+ *
782
+ * A positive Rate of Change (ROC) signals a high momentum and a positive trend. A decreasing ROC or even negative ROC
783
+ * indicates a downtrend.
784
+ *
785
+ * @see https://www.investopedia.com/terms/r/rateofchange.asp
786
+ */
787
+ var ROC = class extends TrendIndicatorSeries {
788
+ prices = [];
789
+ constructor(interval) {
790
+ super();
791
+ this.interval = interval;
792
+ }
793
+ getRequiredInputs() {
794
+ return this.interval;
795
+ }
796
+ update(price, replace) {
797
+ const comparePrice = pushUpdate(this.prices, replace, price, this.interval);
798
+ if (comparePrice) return this.setResult((price - comparePrice) / comparePrice, replace);
799
+ return null;
800
+ }
801
+ calculateSignalState(result) {
802
+ const hasResult = result !== null && result !== void 0;
803
+ const isBearish = hasResult && result < 0;
804
+ switch (true) {
805
+ case !hasResult: return TradingSignal.UNKNOWN;
806
+ case isBearish: return TradingSignal.BEARISH;
807
+ default: return TradingSignal.BULLISH;
808
+ }
809
+ }
810
+ };
811
+
812
+ //#endregion
813
+ //#region src/trend/WSMA/WSMA.ts
814
+ /**
815
+ * Wilder's Smoothed Moving Average (WSMA)
816
+ * Type: Trend
817
+ *
818
+ * Developed by John Welles Wilder (Jr.) to help identifying and spotting bullish and bearish trends. Similar to
819
+ * Exponential Moving Averages with the difference that a smoothing factor of 1/interval is being used, which makes it
820
+ * respond more slowly to price changes.
821
+ *
822
+ * Synonyms:
823
+ * - Modified Exponential Moving Average (MEMA)
824
+ * - Smoothed Moving Average (SMMA)
825
+ * - Welles Wilder's Smoothing (WWS)
826
+ *
827
+ * @see https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/V-Z/WildersSmoothing
828
+ */
829
+ var WSMA = class extends IndicatorSeries {
830
+ #indicator;
831
+ #smoothingFactor;
832
+ constructor(interval) {
833
+ super();
834
+ this.interval = interval;
835
+ this.#indicator = new SMA(interval);
836
+ this.#smoothingFactor = 1 / this.interval;
837
+ }
838
+ getRequiredInputs() {
839
+ return this.interval;
840
+ }
841
+ update(price, replace) {
842
+ const sma = this.#indicator.update(price, replace);
843
+ if (replace && this.previousResult !== void 0) {
844
+ const smoothed = (price - this.previousResult) * this.#smoothingFactor;
845
+ return this.setResult(smoothed + this.previousResult, replace);
846
+ } else if (!replace && this.result !== void 0) {
847
+ const smoothed = (price - this.result) * this.#smoothingFactor;
848
+ return this.setResult(smoothed + this.result, replace);
849
+ } else if (this.result === void 0 && sma !== null) return this.setResult(sma, replace);
850
+ return null;
851
+ }
852
+ };
853
+
854
+ //#endregion
855
+ //#region src/momentum/RSI/RSI.ts
856
+ /**
857
+ * Relative Strength Index (RSI)
858
+ * Type: Momentum
859
+ *
860
+ * The Relative Strength Index (RSI) is an oscillator that ranges between 0 and 100. The RSI can be used to find trend reversals, i.e. when a downtrend doesn't generate a RSI below 30 and rallies above 70 it could mean that a trend reversal to the upside is taking place. Trend lines and moving averages should be used to validate such statements.
861
+ *
862
+ * The RSI is mostly useful in markets that alternate between bullish and bearish movements.
863
+ *
864
+ * Interpretation:
865
+ * A RSI value of 30 or below indicates an oversold condition (not a good time to sell because there is an oversupply).
866
+ * A RSI value of 70 or above indicates an overbought condition (sell high opportunity because market may correct the price in the near future).
867
+ *
868
+ * @see https://en.wikipedia.org/wiki/Relative_strength_index
869
+ * @see https://www.investopedia.com/terms/r/rsi.asp
870
+ */
871
+ var RSI = class extends TrendIndicatorSeries {
872
+ #previousPrices = [];
873
+ #avgGain;
874
+ #avgLoss;
875
+ #maxValue = 100;
876
+ constructor(interval, SmoothingIndicator = WSMA) {
877
+ super();
878
+ this.interval = interval;
879
+ this.#avgGain = new SmoothingIndicator(this.interval);
880
+ this.#avgLoss = new SmoothingIndicator(this.interval);
881
+ }
882
+ getRequiredInputs() {
883
+ return this.#avgGain.getRequiredInputs();
884
+ }
885
+ update(price, replace) {
886
+ pushUpdate(this.#previousPrices, replace, price, this.interval);
887
+ if (this.#previousPrices.length < 2) return null;
888
+ const currentPrice = price;
889
+ const previousPrice = this.#previousPrices[this.#previousPrices.length - 2];
890
+ if (currentPrice > previousPrice) {
891
+ this.#avgLoss.update(0, replace);
892
+ this.#avgGain.update(price - previousPrice, replace);
893
+ } else {
894
+ this.#avgLoss.update(previousPrice - currentPrice, replace);
895
+ this.#avgGain.update(0, replace);
896
+ }
897
+ if (this.#avgGain.isStable) {
898
+ const avgLoss = this.#avgLoss.getResultOrThrow();
899
+ if (avgLoss === 0) return this.setResult(100, replace);
900
+ const relativeStrength = this.#avgGain.getResultOrThrow() / avgLoss;
901
+ return this.setResult(this.#maxValue - this.#maxValue / (relativeStrength + 1), replace);
902
+ }
903
+ return null;
904
+ }
905
+ calculateSignalState(result) {
906
+ const hasResult = result !== null && result !== void 0;
907
+ const isOversold = hasResult && result <= 30;
908
+ const isOverbought = hasResult && result >= 70;
909
+ switch (true) {
910
+ case !hasResult: return TradingSignal.UNKNOWN;
911
+ case isOversold: return TradingSignal.BEARISH;
912
+ case isOverbought: return TradingSignal.BULLISH;
913
+ default: return TradingSignal.SIDEWAYS;
914
+ }
915
+ }
916
+ };
917
+
918
+ //#endregion
919
+ //#region src/momentum/STOCH/StochasticOscillator.ts
920
+ /**
921
+ * Stochastic Oscillator (STOCH)
922
+ * Type: Momentum
923
+ *
924
+ * The Stochastic Oscillator was developed by George Lane and is range-bound between 0 and 100. The Stochastic
925
+ * Oscillator attempts to predict price turning points. A value of 80 indicates that the asset is on the verge of being
926
+ * overbought. By default, a Simple Moving Average (SMA) is used. When the momentum starts to slow down, the Stochastic
927
+ * Oscillator values start to turn down. In the case of an uptrend, prices tend to make higher highs, and the
928
+ * settlement price usually tends to be in the upper end of that time period's trading range.
929
+ *
930
+ * The stochastic k (%k) values represent the relation between current close to the period's price range (high/low). It
931
+ * is sometimes referred as the "fast" stochastic period (fastk). The stochastic d (%d) values represent a Moving
932
+ * Average of the %k values. It is sometimes referred as the "slow" period.
933
+ *
934
+ * @see https://en.wikipedia.org/wiki/Stochastic_oscillator
935
+ * @see https://www.investopedia.com/terms/s/stochasticoscillator.asp
936
+ * @see https://tulipindicators.org/stoch
937
+ */
938
+ var StochasticOscillator = class extends TechnicalIndicator {
939
+ candles = [];
940
+ #periodM;
941
+ #periodP;
942
+ #previousResult;
943
+ /**
944
+ * @param n The %k period
945
+ * @param m The %k slowing period
946
+ * @param p The %d period
947
+ */
948
+ constructor(n, m, p) {
949
+ super();
950
+ this.n = n;
951
+ this.m = m;
952
+ this.p = p;
953
+ this.#periodM = new SMA(m);
954
+ this.#periodP = new SMA(p);
955
+ }
956
+ getRequiredInputs() {
957
+ return this.n + this.p + 1;
958
+ }
959
+ update(candle, replace) {
960
+ pushUpdate(this.candles, replace, candle, this.n);
961
+ if (this.candles.length === this.n) {
962
+ const highest = Math.max(...this.candles.map((candle$1) => candle$1.high));
963
+ const lowest = Math.min(...this.candles.map((candle$1) => candle$1.low));
964
+ const divisor = highest - lowest;
965
+ let fastK = (candle.close - lowest) * 100;
966
+ fastK = fastK / (divisor === 0 ? 1 : divisor);
967
+ const stochK = this.#periodM.update(fastK, replace);
968
+ const stochD = stochK && this.#periodP.update(stochK, replace);
969
+ if (stochK !== null && stochD !== null) {
970
+ if (replace) this.result = this.#previousResult;
971
+ this.#previousResult = this.result;
972
+ return this.result = {
973
+ stochD,
974
+ stochK
975
+ };
976
+ }
977
+ }
978
+ return null;
979
+ }
980
+ calculateSignal(result) {
981
+ const hasResult = result !== null && result !== void 0;
982
+ const isOversold = hasResult && result.stochK <= 20;
983
+ const isOverbought = hasResult && result.stochK >= 80;
984
+ switch (true) {
985
+ case !hasResult: return TradingSignal.UNKNOWN;
986
+ case isOversold: return TradingSignal.BEARISH;
987
+ case isOverbought: return TradingSignal.BULLISH;
988
+ default: return TradingSignal.SIDEWAYS;
989
+ }
990
+ }
991
+ getSignal() {
992
+ const previousState = this.calculateSignal(this.#previousResult);
993
+ const state = this.calculateSignal(this.getResult());
994
+ return {
995
+ hasChanged: previousState !== state,
996
+ state
997
+ };
998
+ }
999
+ };
1000
+
1001
+ //#endregion
1002
+ //#region src/types/Period.ts
1003
+ var Period = class extends TechnicalIndicator {
1004
+ values;
1005
+ /** Highest return value during the current period. */
1006
+ #highest;
1007
+ /** Lowest return value during the current period. */
1008
+ #lowest;
1009
+ get highest() {
1010
+ return this.#highest;
1011
+ }
1012
+ get lowest() {
1013
+ return this.#lowest;
1014
+ }
1015
+ constructor(interval) {
1016
+ super();
1017
+ this.interval = interval;
1018
+ this.values = [];
1019
+ }
1020
+ getRequiredInputs() {
1021
+ return this.interval;
1022
+ }
1023
+ update(value, replace) {
1024
+ pushUpdate(this.values, replace, value, this.interval);
1025
+ if (this.values.length === this.interval) {
1026
+ this.#lowest = Math.min(...this.values);
1027
+ this.#highest = Math.max(...this.values);
1028
+ return this.result = {
1029
+ highest: this.#highest,
1030
+ lowest: this.#lowest
1031
+ };
1032
+ }
1033
+ return null;
1034
+ }
1035
+ };
1036
+
1037
+ //#endregion
1038
+ //#region src/momentum/STOCHRSI/StochasticRSI.ts
1039
+ /**
1040
+ * Stochastic RSI (STOCHRSI)
1041
+ * Type: Momentum
1042
+ *
1043
+ * The Stochastic RSI is an oscillator ranging from 0 to 1 and was developed by Tushar S. Chande and Stanley Kroll.
1044
+ * Compared to the RSI, the Stochastic RSI is much steeper and often resides at the extremes (0 or 1). It can be used to identify short-term trends.
1045
+ *
1046
+ * - A return value of 0.2 or below indicates an oversold condition
1047
+ * - A return value around 0.5 indicates a neutral market
1048
+ * - A return value of 0.8 or above indicates an overbought condition
1049
+ * - Overbought doesn't mean that the price will reverse lower but it shows that the RSI reached an extreme
1050
+ * - Oversold doesn't mean that the price will reverse higher but it shows that the RSI reached an extreme
1051
+ *
1052
+ * The Stochastic RSI is often read through crossovers of its %K (fast) and %D (signal) lines. A %K crossing above %D in the oversold zone (below 20) may suggest a buy, while a %K crossing below %D in the overbought zone (above 80) can signal a potential sell.
1053
+ *
1054
+ * @see https://www.investopedia.com/terms/s/stochrsi.asp
1055
+ * @see https://lakshmishree.com/blog/stochastic-rsi-indicator/
1056
+ * @see https://alchemymarkets.com/education/indicators/stochastic-rsi/
1057
+ */
1058
+ var StochasticRSI = class extends TrendIndicatorSeries {
1059
+ #period;
1060
+ #rsi;
1061
+ constructor(interval, SmoothingRSI = WSMA, smoothing = {
1062
+ d: new SMA(3),
1063
+ k: new SMA(3)
1064
+ }) {
1065
+ super();
1066
+ this.interval = interval;
1067
+ this.smoothing = smoothing;
1068
+ this.#period = new Period(interval);
1069
+ this.#rsi = new RSI(interval, SmoothingRSI);
1070
+ }
1071
+ getRequiredInputs() {
1072
+ return this.#rsi.getRequiredInputs() + this.#period.getRequiredInputs();
1073
+ }
1074
+ update(price, replace) {
1075
+ const rsiResult = this.#rsi.update(price, replace);
1076
+ if (rsiResult) {
1077
+ const periodResult = this.#period.update(rsiResult, replace);
1078
+ if (periodResult) {
1079
+ const min = periodResult.lowest;
1080
+ const denominator = periodResult.highest - min;
1081
+ if (denominator === 0) return this.setResult(100, replace);
1082
+ const stochRSI = (rsiResult - min) / denominator;
1083
+ const k = this.smoothing.k.update(stochRSI, replace);
1084
+ if (k) this.smoothing.d.update(k, replace);
1085
+ return this.setResult(stochRSI, replace);
1086
+ }
1087
+ }
1088
+ return null;
1089
+ }
1090
+ calculateSignalState(result) {
1091
+ const hasResult = result !== null && result !== void 0;
1092
+ const isOversold = hasResult && result <= .2;
1093
+ const isOverbought = hasResult && result >= .8;
1094
+ switch (true) {
1095
+ case !hasResult: return TradingSignal.UNKNOWN;
1096
+ case isOversold: return TradingSignal.BEARISH;
1097
+ case isOverbought: return TradingSignal.BULLISH;
1098
+ default: return TradingSignal.SIDEWAYS;
1099
+ }
1100
+ }
1101
+ };
1102
+
1103
+ //#endregion
1104
+ //#region src/momentum/TDS/TDS.ts
1105
+ /**
1106
+ * Tom Demark's Sequential Indicator (TDS)
1107
+ * Type: Momentum
1108
+ *
1109
+ * The TD Sequential indicator is used to identify potential turning points in the price of an asset.
1110
+ * It consists of two phases: TD Setup and TD Countdown. This implementation focuses on the TD Setup phase,
1111
+ * which is the most commonly used part for trend exhaustion signals.
1112
+ *
1113
+ * - A bullish setup occurs when there are 9 consecutive closes greater than the close 4 bars earlier. A possible sell opportunity is when the low of bars 6 and 7 in the count are exceeded by the low of bars 8 or 9.
1114
+ * - A bearish setup occurs when there are 9 consecutive closes less than the close 4 bars earlier. A possible buy opportunity is when the low of bars 6 and 7 in the count are exceeded by the low of bars 8 or 9.
1115
+ *
1116
+ * @see https://github.com/bennycode/trading-signals/discussions/239
1117
+ * @see https://hackernoon.com/how-to-buy-sell-cryptocurrency-with-number-indicator-td-sequential-5af46f0ebce1
1118
+ * @see https://practicaltechnicalanalysis.blogspot.com/2013/01/tom-demark-sequential.html
1119
+ */
1120
+ var TDS = class extends TrendIndicatorSeries {
1121
+ closes = [];
1122
+ setupCount = 0;
1123
+ setupDirection = null;
1124
+ getRequiredInputs() {
1125
+ return 9;
1126
+ }
1127
+ update(close, replace) {
1128
+ if (replace) this.closes.pop();
1129
+ this.closes.push(close);
1130
+ if (this.closes.length < 5) return null;
1131
+ if (this.closes.length > 13) this.closes.shift();
1132
+ const index = this.closes.length - 1;
1133
+ const prev4 = this.closes[index - 4];
1134
+ if (close > prev4) if (this.setupDirection === "bearish") {
1135
+ this.setupCount = 1;
1136
+ this.setupDirection = "bullish";
1137
+ } else {
1138
+ this.setupCount++;
1139
+ this.setupDirection = "bullish";
1140
+ }
1141
+ else if (close < prev4) if (this.setupDirection === "bullish") {
1142
+ this.setupCount = 1;
1143
+ this.setupDirection = "bearish";
1144
+ } else {
1145
+ this.setupCount++;
1146
+ this.setupDirection = "bearish";
1147
+ }
1148
+ if (this.setupCount >= this.getRequiredInputs()) {
1149
+ const result = this.setupDirection === "bullish" ? 1 : -1;
1150
+ this.setupCount = 0;
1151
+ this.setupDirection = null;
1152
+ return this.setResult(result, replace);
1153
+ }
1154
+ return null;
1155
+ }
1156
+ calculateSignalState(result) {
1157
+ const hasResult = result !== null && result !== void 0;
1158
+ const isOverbought = hasResult && result === 1;
1159
+ switch (true) {
1160
+ case !hasResult: return TradingSignal.UNKNOWN;
1161
+ case isOverbought: return TradingSignal.BULLISH;
1162
+ default: return TradingSignal.BEARISH;
1163
+ }
1164
+ }
1165
+ };
1166
+
1167
+ //#endregion
1168
+ //#region src/momentum/WILLR/WilliamsR.ts
1169
+ /**
1170
+ * Williams %R (Williams Percent Range)
1171
+ * Type: Momentum
1172
+ *
1173
+ * The Williams %R indicator, developed by Larry Williams, is a momentum indicator that measures overbought
1174
+ * and oversold levels. It is similar to the Stochastic Oscillator but is plotted on an inverted scale,
1175
+ * ranging from 0 to -100. Readings from 0 to -20 are considered overbought, while readings from -80 to -100
1176
+ * are considered oversold.
1177
+ *
1178
+ * The Williams %R is arithmetically exactly equivalent to the %K stochastic oscillator, mirrored at the 0%-line.
1179
+ *
1180
+ * Formula: %R = (Highest High - Close) / (Highest High - Lowest Low) × -100
1181
+ *
1182
+ * @see https://en.wikipedia.org/wiki/Williams_%25R
1183
+ * @see https://www.investopedia.com/terms/w/williamsr.asp
1184
+ */
1185
+ var WilliamsR = class extends TrendIndicatorSeries {
1186
+ candles = [];
1187
+ constructor(interval) {
1188
+ super();
1189
+ this.interval = interval;
1190
+ }
1191
+ getRequiredInputs() {
1192
+ return this.interval;
1193
+ }
1194
+ update(candle, replace) {
1195
+ pushUpdate(this.candles, replace, candle, this.interval);
1196
+ if (this.candles.length === this.interval) {
1197
+ let highest = this.candles[0].high;
1198
+ let lowest = this.candles[0].low;
1199
+ for (let i = 1; i < this.candles.length; i++) {
1200
+ if (this.candles[i].high > highest) highest = this.candles[i].high;
1201
+ if (this.candles[i].low < lowest) lowest = this.candles[i].low;
1202
+ }
1203
+ const divisor = highest - lowest;
1204
+ if (divisor === 0) return this.setResult(-100, replace);
1205
+ const willR = (highest - candle.close) / divisor * -100;
1206
+ return this.setResult(willR, replace);
1207
+ }
1208
+ return null;
1209
+ }
1210
+ calculateSignalState(result) {
1211
+ const hasResult = result !== null && result !== void 0;
1212
+ const isOverbought = hasResult && result >= -20;
1213
+ const isOversold = hasResult && result <= -80;
1214
+ switch (true) {
1215
+ case !hasResult: return TradingSignal.UNKNOWN;
1216
+ case isOverbought: return TradingSignal.BULLISH;
1217
+ case isOversold: return TradingSignal.BEARISH;
1218
+ default: return TradingSignal.SIDEWAYS;
1219
+ }
1220
+ }
1221
+ };
1222
+
1223
+ //#endregion
1224
+ //#region src/volatility/TR/TR.ts
1225
+ /**
1226
+ * True Range (TR)
1227
+ * Type: Volatility
1228
+ *
1229
+ * The True Range (TR) was developed by John Welles Wilder (Jr.). The range (R) is a candle's highest price minus it's lowest price. The true range extends it to yesterday's closing price if it was outside of the current range.
1230
+ *
1231
+ * Low return values indicate a sideways trend with little volatility.
1232
+ *
1233
+ * @see https://www.linnsoft.com/techind/true-range-tr
1234
+ */
1235
+ var TR = class extends IndicatorSeries {
1236
+ #previousCandle;
1237
+ #twoPreviousCandle;
1238
+ getRequiredInputs() {
1239
+ return 2;
1240
+ }
1241
+ update(candle, replace) {
1242
+ const { high, low } = candle;
1243
+ const highLow = high - low;
1244
+ if (this.#previousCandle && replace) this.#previousCandle = this.#twoPreviousCandle;
1245
+ if (this.#previousCandle) {
1246
+ const highClose = Math.abs(high - this.#previousCandle.close);
1247
+ const lowClose = Math.abs(low - this.#previousCandle.close);
1248
+ this.#twoPreviousCandle = this.#previousCandle;
1249
+ this.#previousCandle = candle;
1250
+ return this.setResult(Math.max(highLow, highClose, lowClose), replace);
1251
+ }
1252
+ this.#twoPreviousCandle = this.#previousCandle;
1253
+ this.#previousCandle = candle;
1254
+ return this.setResult(highLow, replace);
1255
+ }
1256
+ };
1257
+
1258
+ //#endregion
1259
+ //#region src/volatility/ATR/ATR.ts
1260
+ /**
1261
+ * Average True Range (ATR)
1262
+ * Type: Volatility
1263
+ *
1264
+ * The ATR was developed by John Welles Wilder (Jr.). The idea of ranges is that they show the commitment or enthusiasm of traders. Large or increasing ranges suggest traders prepared to continue to bid up or sell down a stock through the course of the day. Decreasing range indicates declining interest.
1265
+ *
1266
+ * A stock with a higher ATR is indicative of increased volatility, while a lower ATR suggests decreased volatility during the assessed time frame.
1267
+ *
1268
+ * - Low ATR (e.g., 0.5 to 1): Typically associated with low-volatility stocks or markets. Prices tend to move in a relatively calm and steady manner.
1269
+ *
1270
+ * - Moderate ATR (e.g., 1 to 2): Indicates moderate volatility. Prices may experience periodic fluctuations, but they are not extreme. Many traders find stocks with ATR around 2 to be suitable for trading with manageable risk.
1271
+ *
1272
+ * - High ATR (e.g., 2 or higher): Suggests higher volatility. Stocks with ATR values greater than 2 are prone to more significant price swings, and they may exhibit larger price movements.
1273
+ *
1274
+ * @see https://www.investopedia.com/terms/a/atr.asp
1275
+ */
1276
+ var ATR = class extends IndicatorSeries {
1277
+ #tr;
1278
+ #smoothing;
1279
+ constructor(interval, SmoothingIndicator = WSMA) {
1280
+ super();
1281
+ this.interval = interval;
1282
+ this.#tr = new TR();
1283
+ this.#smoothing = new SmoothingIndicator(interval);
1284
+ }
1285
+ getRequiredInputs() {
1286
+ return this.#smoothing.getRequiredInputs();
1287
+ }
1288
+ update(candle, replace) {
1289
+ const trueRange = this.#tr.update(candle, replace);
1290
+ this.#smoothing.update(trueRange, replace);
1291
+ if (this.#smoothing.isStable) return this.setResult(this.#smoothing.getResultOrThrow(), replace);
1292
+ return null;
1293
+ }
1294
+ };
1295
+
1296
+ //#endregion
1297
+ //#region src/trend/DX/DX.ts
1298
+ /**
1299
+ * Directional Movement Index (DMI / DX)
1300
+ * Type: Trend (using +DI & -DI)
1301
+ *
1302
+ * The DX was developed by John Welles Wilder (Jr.). and may help traders assess the strength of a trend (momentum)
1303
+ * and direction of the trend.
1304
+ *
1305
+ * If there is no change in the trend, then the DX is `0`. The return value increases when there is a stronger trend
1306
+ * (either negative or positive). To detect if the trend is bullish or bearish you have to compare +DI and -DI. When
1307
+ * +DI is above -DI, then there is more upward pressure than downward pressure in the market.
1308
+ *
1309
+ * @see https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/dmi
1310
+ */
1311
+ var DX = class extends IndicatorSeries {
1312
+ #movesUp;
1313
+ #movesDown;
1314
+ #previousCandle;
1315
+ #secondLastCandle;
1316
+ #atr;
1317
+ mdi;
1318
+ pdi;
1319
+ constructor(interval, SmoothingIndicator = WSMA) {
1320
+ super();
1321
+ this.interval = interval;
1322
+ this.#atr = new ATR(this.interval, SmoothingIndicator);
1323
+ this.#movesDown = new SmoothingIndicator(this.interval);
1324
+ this.#movesUp = new SmoothingIndicator(this.interval);
1325
+ }
1326
+ #updateState(candle, pdm, mdm, replace) {
1327
+ this.#atr.update(candle, replace);
1328
+ this.#movesUp.update(pdm, replace);
1329
+ this.#movesDown.update(mdm, replace);
1330
+ if (this.#previousCandle) this.#secondLastCandle = this.#previousCandle;
1331
+ this.#previousCandle = candle;
1332
+ }
1333
+ getRequiredInputs() {
1334
+ return this.#movesUp.getRequiredInputs();
1335
+ }
1336
+ update(candle, replace) {
1337
+ if (!this.#previousCandle) {
1338
+ this.#updateState(candle, 0, 0, replace);
1339
+ return null;
1340
+ }
1341
+ if (this.#secondLastCandle && replace) this.#previousCandle = this.#secondLastCandle;
1342
+ const currentHigh = candle.high;
1343
+ const previousHigh = this.#previousCandle.high;
1344
+ const currentLow = candle.low;
1345
+ const previousLow = this.#previousCandle.low;
1346
+ const higherHigh = currentHigh - previousHigh;
1347
+ const lowerLow = previousLow - currentLow;
1348
+ const pdm = higherHigh < 0 || higherHigh < lowerLow ? 0 : higherHigh;
1349
+ const mdm = lowerLow < 0 || lowerLow < higherHigh ? 0 : lowerLow;
1350
+ this.#updateState(candle, pdm, mdm, replace);
1351
+ if (this.#movesUp.isStable) {
1352
+ this.pdi = this.#movesUp.getResultOrThrow() / this.#atr.getResultOrThrow();
1353
+ this.mdi = this.#movesDown.getResultOrThrow() / this.#atr.getResultOrThrow();
1354
+ const dmDiff = Math.abs(this.pdi - this.mdi);
1355
+ const dmSum = this.pdi + this.mdi;
1356
+ if (dmSum === 0) return this.setResult(0, replace);
1357
+ return this.setResult(dmDiff / dmSum * 100, replace);
1358
+ }
1359
+ return null;
1360
+ }
1361
+ };
1362
+
1363
+ //#endregion
1364
+ //#region src/trend/ADX/ADX.ts
1365
+ /**
1366
+ * Average Directional Index (ADX)
1367
+ * Type: Trend (using +DI & -DI), Volatility
1368
+ *
1369
+ * The ADX was developed by John Welles Wilder (Jr.). It is a lagging indicator; that is, a
1370
+ * trend must have established itself before the ADX will generate a signal that a trend is under way.
1371
+ *
1372
+ * ADX will range between 0 and 100 which makes it an oscillator. It is a smoothed average of the Directional Movement
1373
+ * Index (DMI / DX).
1374
+ *
1375
+ * Generally, ADX readings below 20 indicate trend weakness, and readings above 40 indicate trend strength.
1376
+ * A strong trend is indicated by readings above 50. ADX values of 75-100 signal an extremely strong trend.
1377
+ *
1378
+ * Interpretation:
1379
+ * If ADX increases, it means that volatility is increasing and indicating the beginning of a new trend.
1380
+ * If ADX decreases, it means that volatility is decreasing, and the current trend is slowing down and may even
1381
+ * reverse.
1382
+ * When +DI is above -DI, then there is more upward pressure than downward pressure in the market.
1383
+ *
1384
+ * Note:
1385
+ * The ADX calculation relies on the DX becoming stable before producing meaningful results.
1386
+ * For an interval of 5, at least 9 candles are required. The first 5 candles are used to stabilize the DX, which then generates the initial ADX value.
1387
+ * The subsequent 4 candles produce additional ADX values, allowing it to stabilize with 5 values for an interval of 5.
1388
+ *
1389
+ * @see https://www.investopedia.com/terms/a/adx.asp
1390
+ * @see https://en.wikipedia.org/wiki/Average_directional_movement_index
1391
+ * @see https://paperswithbacktest.com/wiki/wilders-adx-dmi-indicator-calculation-method
1392
+ * @see https://www.youtube.com/watch?v=n2J1H3NeF70
1393
+ * @see https://learn.tradimo.com/technical-analysis-how-to-work-with-indicators/adx-determing-the-strength-of-price-movement
1394
+ * @see https://medium.com/codex/algorithmic-trading-with-average-directional-index-in-python-2b5a20ecf06a
1395
+ */
1396
+ var ADX = class extends IndicatorSeries {
1397
+ #dx;
1398
+ #smoothed;
1399
+ constructor(interval, SmoothingIndicator = WSMA) {
1400
+ super();
1401
+ this.interval = interval;
1402
+ this.#smoothed = new SmoothingIndicator(this.interval);
1403
+ this.#dx = new DX(interval, SmoothingIndicator);
1404
+ }
1405
+ get mdi() {
1406
+ return this.#dx.mdi;
1407
+ }
1408
+ get pdi() {
1409
+ return this.#dx.pdi;
1410
+ }
1411
+ getRequiredInputs() {
1412
+ return this.interval * 2 - 1;
1413
+ }
1414
+ update(candle, replace) {
1415
+ const result = this.#dx.update(candle, replace);
1416
+ if (result !== null) this.#smoothed.update(result, replace);
1417
+ if (this.#smoothed.isStable) return this.setResult(this.#smoothed.getResultOrThrow(), replace);
1418
+ return null;
1419
+ }
1420
+ };
1421
+
1422
+ //#endregion
1423
+ //#region src/trend/EMA/EMA.ts
1424
+ /**
1425
+ * Exponential Moving Average (EMA)
1426
+ * Type: Trend
1427
+ *
1428
+ * Compared to SMA, the EMA puts more emphasis on the recent prices to reduce lag. Due to its responsiveness to price changes, it rises faster and falls faster than the SMA when the price is inclining or declining.
1429
+ *
1430
+ * @see https://www.investopedia.com/terms/e/ema.asp
1431
+ */
1432
+ var EMA = class extends MovingAverage {
1433
+ #pricesCounter = 0;
1434
+ #weightFactor;
1435
+ constructor(interval) {
1436
+ super(interval);
1437
+ this.interval = interval;
1438
+ this.#weightFactor = 2 / (this.interval + 1);
1439
+ }
1440
+ getRequiredInputs() {
1441
+ return this.interval;
1442
+ }
1443
+ update(price, replace) {
1444
+ if (!replace) this.#pricesCounter++;
1445
+ else if (replace && this.#pricesCounter === 0) this.#pricesCounter++;
1446
+ if (replace && this.previousResult !== void 0) return this.setResult(price * this.#weightFactor + this.previousResult * (1 - this.#weightFactor), replace);
1447
+ return this.setResult(price * this.#weightFactor + (this.result !== void 0 ? this.result : price) * (1 - this.#weightFactor), replace);
1448
+ }
1449
+ getResultOrThrow() {
1450
+ if (this.#pricesCounter < this.interval) throw new NotEnoughDataError(this.getRequiredInputs());
1451
+ return this.result;
1452
+ }
1453
+ get isStable() {
1454
+ try {
1455
+ this.getResultOrThrow();
1456
+ return true;
1457
+ } catch {
1458
+ return false;
1459
+ }
1460
+ }
1461
+ };
1462
+
1463
+ //#endregion
1464
+ //#region src/trend/DEMA/DEMA.ts
1465
+ /**
1466
+ * Double Exponential Moving Average (DEMA)
1467
+ * Type: Trend
1468
+ *
1469
+ * The Double Exponential Moving Average (DEMA) was developed by Patrick G. Mulloy. It attempts to remove the lag associated with Moving Averages by placing more weight on recent values. It has its name because the value of an EMA is doubled which makes it responds more quickly to short-term price changes than a normal EMA.
1470
+ *
1471
+ * @see https://www.investopedia.com/terms/d/double-exponential-moving-average.asp
1472
+ */
1473
+ var DEMA = class extends IndicatorSeries {
1474
+ #inner;
1475
+ #outer;
1476
+ constructor(interval) {
1477
+ super();
1478
+ this.interval = interval;
1479
+ this.#inner = new EMA(interval);
1480
+ this.#outer = new EMA(interval);
1481
+ }
1482
+ getRequiredInputs() {
1483
+ return this.#outer.getRequiredInputs();
1484
+ }
1485
+ update(price, replace) {
1486
+ const innerResult = this.#inner.update(price, replace);
1487
+ const outerResult = this.#outer.update(innerResult, replace);
1488
+ return this.setResult(innerResult * 2 - outerResult, replace);
1489
+ }
1490
+ get isStable() {
1491
+ return this.#outer.isStable;
1492
+ }
1493
+ };
1494
+
1495
+ //#endregion
1496
+ //#region src/trend/DMA/DMA.ts
1497
+ /**
1498
+ * Dual Moving Average (DMA)
1499
+ * Type: Trend
1500
+ *
1501
+ * The DMA consists of two moving averages: Short-term & long-term.
1502
+ *
1503
+ * Dual Moving Average Crossover:
1504
+ * A short-term MA crossing above a long-term MA indicates a bullish buying opportunity.
1505
+ * A short-term MA crossing below a long-term MA indicates a bearish selling opportunity.
1506
+ *
1507
+ * @see https://faculty.fuqua.duke.edu/~charvey/Teaching/BA453_2002/CCAM/CCAM.htm#_Toc2634228
1508
+ */
1509
+ var DMA = class extends TechnicalIndicator {
1510
+ short;
1511
+ long;
1512
+ constructor(short, long, SmoothingIndicator = SMA) {
1513
+ super();
1514
+ this.short = new SmoothingIndicator(short);
1515
+ this.long = new SmoothingIndicator(long);
1516
+ }
1517
+ get isStable() {
1518
+ return this.long.isStable;
1519
+ }
1520
+ getRequiredInputs() {
1521
+ return this.long.getRequiredInputs();
1522
+ }
1523
+ update(price, replace) {
1524
+ this.short.update(price, replace);
1525
+ this.long.update(price, replace);
1526
+ if (this.isStable) return this.result = {
1527
+ long: this.long.getResultOrThrow(),
1528
+ short: this.short.getResultOrThrow()
1529
+ };
1530
+ return null;
1531
+ }
1532
+ };
1533
+
1534
+ //#endregion
1535
+ //#region src/trend/LINREG/LinearRegression.ts
1536
+ /**
1537
+ * Linear Regression (LINREG)
1538
+ * Type: Trend
1539
+ *
1540
+ * It fits a straight line to price data over a chosen period using the least-squares method. The slope of the line shows the trend direction and strength. It’s similar in use to moving averages but mathematically more precise, since it minimizes the squared distance between price points and the fitted line.
1541
+ */
1542
+ var LinearRegression = class extends TechnicalIndicator {
1543
+ prices = [];
1544
+ constructor(interval) {
1545
+ super();
1546
+ this.interval = interval;
1547
+ }
1548
+ getRequiredInputs() {
1549
+ return this.interval;
1550
+ }
1551
+ #calculateRegression(prices) {
1552
+ const n = prices.length;
1553
+ if (prices.every((price, i) => {
1554
+ if (i === 0) return true;
1555
+ return Math.abs(price - prices[i - 1] - 1) < 1e-10;
1556
+ })) {
1557
+ const slope$1 = 1;
1558
+ const intercept$1 = prices[0] - slope$1;
1559
+ return {
1560
+ intercept: intercept$1,
1561
+ prediction: slope$1 * n + intercept$1,
1562
+ slope: slope$1
1563
+ };
1564
+ }
1565
+ const sumX = (n - 1) * n / 2;
1566
+ const sumY = prices.reduce((a, b) => a + b, 0);
1567
+ let sumXY = 0;
1568
+ let sumXX = 0;
1569
+ for (let i = 0; i < n; i++) {
1570
+ sumXY += i * prices[i];
1571
+ sumXX += i * i;
1572
+ }
1573
+ const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
1574
+ const intercept = (sumY - slope * sumX) / n;
1575
+ return {
1576
+ intercept,
1577
+ prediction: slope * n + intercept,
1578
+ slope
1579
+ };
1580
+ }
1581
+ update(price, replace) {
1582
+ pushUpdate(this.prices, replace, price, this.interval);
1583
+ if (this.prices.length < this.interval) return null;
1584
+ return this.result = this.#calculateRegression(this.prices);
1585
+ }
1586
+ get isStable() {
1587
+ try {
1588
+ this.getResultOrThrow();
1589
+ return true;
1590
+ } catch {
1591
+ return false;
1592
+ }
1593
+ }
1594
+ };
1595
+
1596
+ //#endregion
1597
+ //#region src/trend/PSAR/PSAR.ts
1598
+ /**
1599
+ * Parabolic SAR
1600
+ * Type: Trend
1601
+ *
1602
+ * The Parabolic SAR (Stop and Reverse) is a technical indicator used in trading to determine the direction of an asset's price and potential points of trend reversal. It was developed by J. Welles Wilder Jr., who also created indicators like the RSI.
1603
+ *
1604
+ * Interpretation:
1605
+ * The indicator places dots above or below the price. If the dots are below the price, it signals an uptrend. If the dots are above the price it signals a downtrend. It "stops and reverses" when the trend is likely to change, hence the name. Its logic says to stay in a trend as long as the dots stay on the same side of the price. Exit or reverse positions when the dots flip to the opposite side.
1606
+ *
1607
+ * Note:
1608
+ * It's particularly useful in trending markets, but less reliable in sideways or choppy markets.
1609
+ *
1610
+ */
1611
+ var PSAR = class extends IndicatorSeries {
1612
+ accelerationStep;
1613
+ accelerationMax;
1614
+ acceleration = 0;
1615
+ extreme = null;
1616
+ lastSar = null;
1617
+ isLong = null;
1618
+ previousCandle = null;
1619
+ prePreviousCandle = null;
1620
+ constructor(config) {
1621
+ super();
1622
+ this.accelerationStep = config.accelerationStep;
1623
+ this.accelerationMax = config.accelerationMax;
1624
+ if (this.accelerationStep <= 0) throw new Error("Acceleration step must be greater than 0");
1625
+ if (this.accelerationMax <= this.accelerationStep) throw new Error("Acceleration max must be greater than acceleration step");
1626
+ }
1627
+ get isStable() {
1628
+ return this.lastSar !== null;
1629
+ }
1630
+ getRequiredInputs() {
1631
+ return 2;
1632
+ }
1633
+ update(candle, replace) {
1634
+ const { high, low } = candle;
1635
+ const notEnoughData = !this.previousCandle || this.lastSar === null;
1636
+ if (replace && notEnoughData) {
1637
+ this.previousCandle = candle;
1638
+ return null;
1639
+ }
1640
+ if (!this.previousCandle) {
1641
+ this.previousCandle = candle;
1642
+ return null;
1643
+ }
1644
+ if (this.lastSar === null) {
1645
+ this.isLong = (high + low) / 2 >= (this.previousCandle.high + this.previousCandle.low) / 2;
1646
+ if (this.isLong) {
1647
+ this.extreme = high;
1648
+ this.lastSar = this.previousCandle.low;
1649
+ } else {
1650
+ this.extreme = low;
1651
+ this.lastSar = this.previousCandle.high;
1652
+ }
1653
+ this.acceleration = this.accelerationStep;
1654
+ this.prePreviousCandle = this.previousCandle;
1655
+ this.previousCandle = candle;
1656
+ return this.setResult(this.lastSar, replace);
1657
+ }
1658
+ let sar = (this.extreme - this.lastSar) * this.acceleration + this.lastSar;
1659
+ if (this.isLong) {
1660
+ if (this.prePreviousCandle != null && low < sar) {
1661
+ if (this.prePreviousCandle.low < sar) sar = this.prePreviousCandle.low;
1662
+ sar = this.previousCandle.low < sar ? this.previousCandle.low : sar;
1663
+ } else if (this.previousCandle.low < sar) sar = this.previousCandle.low;
1664
+ if (high > this.extreme) {
1665
+ this.extreme = high;
1666
+ if (this.acceleration < this.accelerationMax) {
1667
+ this.acceleration += this.accelerationStep;
1668
+ if (this.acceleration > this.accelerationMax) this.acceleration = this.accelerationMax;
1669
+ }
1670
+ }
1671
+ if (low < sar) {
1672
+ this.isLong = false;
1673
+ sar = this.extreme;
1674
+ this.extreme = low;
1675
+ this.acceleration = this.accelerationStep;
1676
+ }
1677
+ } else {
1678
+ if (this.prePreviousCandle != null && high > sar) {
1679
+ if (this.prePreviousCandle.high > sar) sar = this.prePreviousCandle.high;
1680
+ sar = this.previousCandle.high > sar ? this.previousCandle.high : sar;
1681
+ } else if (this.previousCandle.high > sar) sar = this.previousCandle.high;
1682
+ if (low < this.extreme) {
1683
+ this.extreme = low;
1684
+ this.acceleration += this.accelerationStep;
1685
+ if (this.acceleration > this.accelerationMax) this.acceleration = this.accelerationMax;
1686
+ }
1687
+ if (high > sar) {
1688
+ this.isLong = true;
1689
+ sar = this.extreme;
1690
+ this.extreme = high;
1691
+ this.acceleration = this.accelerationStep;
1692
+ if (sar >= low) sar = low - .01;
1693
+ }
1694
+ }
1695
+ this.lastSar = sar;
1696
+ this.prePreviousCandle = this.previousCandle;
1697
+ this.previousCandle = candle;
1698
+ return this.setResult(sar, replace);
1699
+ }
1700
+ getResultOrThrow() {
1701
+ return super.getResultOrThrow();
1702
+ }
1703
+ };
1704
+
1705
+ //#endregion
1706
+ //#region src/trend/RMA/RMA.ts
1707
+ /**
1708
+ * Relative Moving Average (RMA)
1709
+ * Type: Trend
1710
+ *
1711
+ * Use RMA to identify bullish or bearish trends. It provides a smoother curve compared to SMA and EMA, reacting more slowly to price changes.
1712
+ *
1713
+ * @see https://www.tradingcode.net/tradingview/ema-versus-rma/
1714
+ * @see https://www.tradingcode.net/tradingview/relative-moving-average/#calculation-process
1715
+ */
1716
+ var RMA = class extends MovingAverage {
1717
+ #pricesCounter = 0;
1718
+ #weightFactor;
1719
+ constructor(interval) {
1720
+ super(interval);
1721
+ this.interval = interval;
1722
+ this.#weightFactor = 1 / this.interval;
1723
+ }
1724
+ getRequiredInputs() {
1725
+ return this.interval;
1726
+ }
1727
+ update(price, replace) {
1728
+ if (!replace) this.#pricesCounter++;
1729
+ else if (replace && this.#pricesCounter === 0) this.#pricesCounter++;
1730
+ if (replace && this.previousResult !== void 0) return this.setResult(price * this.#weightFactor + this.previousResult * (1 - this.#weightFactor), replace);
1731
+ return this.setResult(price * this.#weightFactor + (this.result !== void 0 ? this.result : price) * (1 - this.#weightFactor), replace);
1732
+ }
1733
+ getResultOrThrow() {
1734
+ if (this.#pricesCounter < this.interval) throw new NotEnoughDataError(this.getRequiredInputs());
1735
+ return this.result;
1736
+ }
1737
+ get isStable() {
1738
+ try {
1739
+ this.getResultOrThrow();
1740
+ return true;
1741
+ } catch {
1742
+ return false;
1743
+ }
1744
+ }
1745
+ };
1746
+
1747
+ //#endregion
1748
+ //#region src/trend/SMA15/SMA15.ts
1749
+ /**
1750
+ * Spencer's 15-Point Moving Average
1751
+ * Type: Trend
1752
+ *
1753
+ * A specialized weighted moving average that uses 15 points with predefined weights
1754
+ * designed for optimal data smoothing. It’s a specific weighted moving average, designed to preserve the trend component in data while minimizing distortion from seasonal or irregular variations.
1755
+ *
1756
+ * The formula uses these specific weights:
1757
+ * [-3, -6, -5, 3, 21, 46, 67, 74, 67, 46, 21, 3, -5, -6, -3]
1758
+ *
1759
+ * @see https://www.stat.berkeley.edu/~aditya/Site/Statistics_153;_Spring_2012_files/Spring2012Statistics153LectureThree.pdf
1760
+ * @see https://mathworld.wolfram.com/Spencers15-PointMovingAverage.html
1761
+ */
1762
+ var SMA15 = class SMA15 extends MovingAverage {
1763
+ prices = [];
1764
+ static #WEIGHTS = [
1765
+ -3,
1766
+ -6,
1767
+ -5,
1768
+ 3,
1769
+ 21,
1770
+ 46,
1771
+ 67,
1772
+ 74,
1773
+ 67,
1774
+ 46,
1775
+ 21,
1776
+ 3,
1777
+ -5,
1778
+ -6,
1779
+ -3
1780
+ ];
1781
+ static #WEIGHT_SUM = 320;
1782
+ getRequiredInputs() {
1783
+ return SMA15.#WEIGHTS.length;
1784
+ }
1785
+ update(price, replace) {
1786
+ pushUpdate(this.prices, replace, price, this.getRequiredInputs());
1787
+ if (this.prices.length === this.getRequiredInputs()) {
1788
+ let weightedPricesSum = 0;
1789
+ for (let i = 0; i < this.getRequiredInputs(); i++) {
1790
+ const weightedPrice = this.prices[i] * SMA15.#WEIGHTS[i];
1791
+ weightedPricesSum += weightedPrice;
1792
+ }
1793
+ const weightedAverage = weightedPricesSum / SMA15.#WEIGHT_SUM;
1794
+ return this.setResult(weightedAverage, replace);
1795
+ }
1796
+ return null;
1797
+ }
1798
+ };
1799
+
1800
+ //#endregion
1801
+ //#region src/trend/VWAP/VWAP.ts
1802
+ /**
1803
+ * Volume-Weighted Average Price (VWAP)
1804
+ * Type: Trend
1805
+ *
1806
+ * The Volume-Weighted Average Price (VWAP) represents the average price a security has traded at throughout the day, weighted by both volume and price.
1807
+ *
1808
+ * Formula: VWAP = (Sum of (Price × Volume)) / Total Volume
1809
+ *
1810
+ * @see https://www.investopedia.com/terms/v/vwap.asp
1811
+ */
1812
+ var VWAP = class extends IndicatorSeries {
1813
+ #cumulativeTypicalPriceVolume = 0;
1814
+ #cumulativeVolume = 0;
1815
+ #lastCandle = null;
1816
+ constructor() {
1817
+ super();
1818
+ }
1819
+ #calculateTypicalPriceVolume(data) {
1820
+ return (data.high + data.low + data.close) / 3 * data.volume;
1821
+ }
1822
+ getRequiredInputs() {
1823
+ return 2;
1824
+ }
1825
+ update(candle, replace) {
1826
+ if (candle.volume === 0) return null;
1827
+ if (replace && this.#lastCandle !== null) {
1828
+ const lastTypicalPriceVolume = this.#calculateTypicalPriceVolume(this.#lastCandle);
1829
+ this.#cumulativeTypicalPriceVolume = this.#cumulativeTypicalPriceVolume - lastTypicalPriceVolume;
1830
+ this.#cumulativeVolume = this.#cumulativeVolume - this.#lastCandle.volume;
1831
+ }
1832
+ this.#lastCandle = candle;
1833
+ const typicalPriceVolume = this.#calculateTypicalPriceVolume(candle);
1834
+ this.#cumulativeTypicalPriceVolume = this.#cumulativeTypicalPriceVolume + typicalPriceVolume;
1835
+ this.#cumulativeVolume = this.#cumulativeVolume + candle.volume;
1836
+ const vwap = this.#cumulativeTypicalPriceVolume / this.#cumulativeVolume;
1837
+ return this.setResult(vwap, replace);
1838
+ }
1839
+ };
1840
+
1841
+ //#endregion
1842
+ //#region src/trend/WMA/WMA.ts
1843
+ /**
1844
+ * Weighted Moving Average (WMA)
1845
+ * Type: Trend
1846
+ *
1847
+ * Compared to SMA, the WMA puts more emphasis on the recent prices to reduce lag. Due to its responsiveness to price changes, it rises faster and falls faster than the SMA when the price is inclining or declining.
1848
+ *
1849
+ * @see https://corporatefinanceinstitute.com/resources/career-map/sell-side/capital-markets/weighted-moving-average-wma/
1850
+ */
1851
+ var WMA = class extends MovingAverage {
1852
+ prices = [];
1853
+ constructor(interval) {
1854
+ super(interval);
1855
+ this.interval = interval;
1856
+ }
1857
+ getRequiredInputs() {
1858
+ return this.interval;
1859
+ }
1860
+ update(price, replace) {
1861
+ pushUpdate(this.prices, replace, price, this.interval);
1862
+ if (this.prices.length === this.interval) {
1863
+ const weightedMa = this.prices.reduce((acc, price$1, index) => {
1864
+ return acc + price$1 * (index + 1);
1865
+ }, 0) / (this.interval * (this.interval + 1) / 2);
1866
+ return this.setResult(weightedMa, replace);
1867
+ }
1868
+ return null;
1869
+ }
1870
+ };
1871
+
1872
+ //#endregion
1873
+ //#region src/trend/ZIGZAG/ZigZag.ts
1874
+ /**
1875
+ * ZigZag Indicator (ZigZag)
1876
+ * Type: Trend
1877
+ *
1878
+ * The ZigZag indicator is a technical analysis tool used to identify price trends by filtering out smaller price movements. It works by identifying significant highs and lows in a price series and drawing lines between them. For a high or low to be considered significant, the price must reverse by at least a specified percentage (deviation) from the last extreme point.
1879
+ *
1880
+ * The indicator alternates between tracking highs and lows: after confirming a high, it searches for a significant low, and after confirming a low, it searches for a significant high.
1881
+ *
1882
+ * The Zig Zag indicator is considered to be a very lagging indicator because its values are plotted only after each time period closes, and it only forms a permanent new line once the price has moved significantly. Traders can use popular technical indicators like RSI, ADX, and the Stochastics oscillator to confirm the price of a security is overbought or oversold when the ZigZag line changes direction.
1883
+ *
1884
+ * @see https://www.investopedia.com/ask/answers/030415/what-zig-zag-indicator-formula-and-how-it-calculated.asp
1885
+ * @see https://www.investopedia.com/terms/z/zig_zag_indicator.asp
1886
+ * @see https://capex.com/en/academy/zigzag
1887
+ * @see https://corporatefinanceinstitute.com/resources/career-map/sell-side/capital-markets/zig-zag-indicator/
1888
+ */
1889
+ var ZigZag = class extends IndicatorSeries {
1890
+ #deviation;
1891
+ #isUp = false;
1892
+ #highestExtreme = null;
1893
+ #lowestExtreme = null;
1894
+ constructor(config) {
1895
+ super();
1896
+ this.#deviation = config.deviation;
1897
+ }
1898
+ getRequiredInputs() {
1899
+ return 1;
1900
+ }
1901
+ update(candle, replace) {
1902
+ const low = candle.low;
1903
+ const high = candle.high;
1904
+ if (this.#lowestExtreme === null) this.#lowestExtreme = low;
1905
+ if (this.#highestExtreme === null) this.#highestExtreme = high;
1906
+ if (this.#isUp) {
1907
+ const uptrendReversal = this.#lowestExtreme + (this.#highestExtreme - this.#lowestExtreme) * (100 - this.#deviation) / 100;
1908
+ if (high > this.#highestExtreme) this.#highestExtreme = high;
1909
+ else if (low < uptrendReversal) {
1910
+ this.#isUp = false;
1911
+ this.#lowestExtreme = low;
1912
+ return this.setResult(this.#highestExtreme, replace);
1913
+ }
1914
+ } else {
1915
+ const downtrendReversal = low + (this.#highestExtreme - low) * this.#deviation / 100;
1916
+ if (low < this.#lowestExtreme) this.#lowestExtreme = low;
1917
+ else if (high > downtrendReversal) {
1918
+ this.#isUp = true;
1919
+ this.#highestExtreme = high;
1920
+ return this.setResult(this.#lowestExtreme, replace);
1921
+ }
1922
+ }
1923
+ return null;
1924
+ }
1925
+ };
1926
+
1927
+ //#endregion
1928
+ //#region src/volatility/ABANDS/AccelerationBands.ts
1929
+ /**
1930
+ * Acceleration Bands (ABANDS)
1931
+ * Type: Volatility
1932
+ *
1933
+ * Acceleration bands created by Price Headley are set as an envelope around a moving average. The upper and lower bands are of equal distance from the middle band.
1934
+ *
1935
+ * Two consecutive closes outside Acceleration Bands suggest an entry point in the direction of the breakout (either bullish or bearish). A long position is usually kept till the first close back inside the bands.
1936
+ *
1937
+ * @param interval The interval that is being used for the three moving averages which create lower, middle and upper
1938
+ * bands
1939
+ * @param width A coefficient specifying the distance between the middle band and upper/lower bands
1940
+ * @param SmoothingIndicator Which moving average (SMA, EMA, ...) to use
1941
+ *
1942
+ * @see https://www.tradingtechnologies.com/xtrader-help/x-study/technical-indicator-definitions/acceleration-bands-abands/
1943
+ * @see https://www.motivewave.com/studies/acceleration_bands.htm
1944
+ * @see https://github.com/QuantConnect/Lean/blob/master/Indicators/AccelerationBands.cs
1945
+ * @see https://github.com/twopirllc/pandas-ta/blob/master/pandas_ta/volatility/accbands.py
1946
+ */
1947
+ var AccelerationBands = class extends TechnicalIndicator {
1948
+ #lowerBand;
1949
+ #middleBand;
1950
+ #upperBand;
1951
+ constructor(interval, width, SmoothingIndicator = SMA) {
1952
+ super();
1953
+ this.interval = interval;
1954
+ this.width = width;
1955
+ this.#lowerBand = new SmoothingIndicator(interval);
1956
+ this.#middleBand = new SmoothingIndicator(interval);
1957
+ this.#upperBand = new SmoothingIndicator(interval);
1958
+ }
1959
+ getRequiredInputs() {
1960
+ return this.#middleBand.getRequiredInputs();
1961
+ }
1962
+ update({ high, low, close }, replace) {
1963
+ const highPlusLow = high + low;
1964
+ const coefficient = highPlusLow === 0 ? 0 : (high - low) / highPlusLow * this.width;
1965
+ this.#lowerBand.update(low * (1 - coefficient), replace);
1966
+ this.#middleBand.update(close, replace);
1967
+ this.#upperBand.update(high * (1 + coefficient), replace);
1968
+ if (this.isStable) return this.result = {
1969
+ lower: this.#lowerBand.getResultOrThrow(),
1970
+ middle: this.#middleBand.getResultOrThrow(),
1971
+ upper: this.#upperBand.getResultOrThrow()
1972
+ };
1973
+ return null;
1974
+ }
1975
+ get isStable() {
1976
+ return this.#middleBand.isStable;
1977
+ }
1978
+ };
1979
+
1980
+ //#endregion
1981
+ //#region src/volatility/BBANDS/BollingerBands.ts
1982
+ /**
1983
+ * Bollinger Bands (BBANDS)
1984
+ * Type: Volatility
1985
+ *
1986
+ * Bollinger Bands (BBANDS), developed by John A. Bollinger, are set as an envelope around a moving average. Narrow bands indicate a sideways trend (ranging markets). To determine a breakout direction, [Investopia.com suggests](https://www.investopedia.com/articles/technical/04/030304.asp) to use the relative strength index (RSI) along with one or two volume-based indicators such as the intraday intensity index (developed by David Bostian) or the accumulation/distribution index (developed by Larry William).
1987
+ *
1988
+ * When the upper and lower bands expand, there can be "M" and "W" formations. The "W" formation indicates a bullish movement and the "M" formation indicates a bearish movement.
1989
+ *
1990
+ * @see https://www.investopedia.com/terms/b/bollingerbands.asp
1991
+ */
1992
+ var BollingerBands = class extends TechnicalIndicator {
1993
+ prices = [];
1994
+ constructor(interval, deviationMultiplier = 2) {
1995
+ super();
1996
+ this.interval = interval;
1997
+ this.deviationMultiplier = deviationMultiplier;
1998
+ }
1999
+ getRequiredInputs() {
2000
+ return this.interval;
2001
+ }
2002
+ update(price, replace) {
2003
+ if (pushUpdate(this.prices, replace, price, this.interval)) {
2004
+ const middle = getAverage(this.prices);
2005
+ const standardDeviation = getStandardDeviation(this.prices, middle);
2006
+ return this.result = {
2007
+ lower: middle - standardDeviation * this.deviationMultiplier,
2008
+ middle,
2009
+ upper: middle + standardDeviation * this.deviationMultiplier
2010
+ };
2011
+ }
2012
+ return null;
2013
+ }
2014
+ };
2015
+
2016
+ //#endregion
2017
+ //#region src/volatility/BBW/BollingerBandsWidth.ts
2018
+ /**
2019
+ * Bollinger Bands Width (BBW)
2020
+ * Type: Volatility
2021
+ *
2022
+ * The Bollinger Bands Width (BBW) indicator, developed by John A. Bollinger, merges the information of Bollinger Bands into one definite number. It defines the narrowness of the underlying Bollinger Bands by representing the difference between the Upper Band and the Lower Band.
2023
+ *
2024
+ * @see https://www.tradingview.com/support/solutions/43000501972-bollinger-bands-width-bbw/
2025
+ */
2026
+ var BollingerBandsWidth = class extends IndicatorSeries {
2027
+ constructor(bollingerBands) {
2028
+ super();
2029
+ this.bollingerBands = bollingerBands;
2030
+ }
2031
+ getRequiredInputs() {
2032
+ return this.bollingerBands.getRequiredInputs();
2033
+ }
2034
+ update(price, replace) {
2035
+ const result = this.bollingerBands.update(price, replace);
2036
+ if (result) return this.setResult((result.upper - result.lower) / result.middle, replace);
2037
+ return null;
2038
+ }
2039
+ };
2040
+
2041
+ //#endregion
2042
+ //#region src/volatility/IQR/IQR.ts
2043
+ /**
2044
+ * Interquartile Range (IQR)
2045
+ * Type: Volatility
2046
+ *
2047
+ * The IQR is the difference between the 75th percentile (Q3) and the 25th percentile (Q1) of a data set. It is a measure of statistical dispersion and is robust to outliers.
2048
+ *
2049
+ * @see https://github.com/bennycode/trading-signals/discussions/752
2050
+ * @see https://en.wikipedia.org/wiki/Interquartile_range
2051
+ */
2052
+ var IQR = class extends IndicatorSeries {
2053
+ #values = [];
2054
+ constructor(interval) {
2055
+ super();
2056
+ this.interval = interval;
2057
+ }
2058
+ getRequiredInputs() {
2059
+ return this.interval;
2060
+ }
2061
+ update(value, replace) {
2062
+ if (replace) this.#values.pop();
2063
+ this.#values.push(value);
2064
+ if (this.#values.length > this.interval) this.#values.shift();
2065
+ if (this.#values.length < this.interval) return null;
2066
+ const q1 = getQuartile(this.#values, .25);
2067
+ const q3 = getQuartile(this.#values, .75);
2068
+ return this.setResult(q3 - q1, replace);
2069
+ }
2070
+ };
2071
+
2072
+ //#endregion
2073
+ export { AC, ADX, AO, ATR, AccelerationBands, BollingerBands, BollingerBandsWidth, CCI, CG, DEMA, DMA, DX, EMA, IQR, IndicatorSeries, LinearRegression, MACD, MAD, MOM, NotEnoughDataError, OBV, PSAR, Period, REI, RMA, ROC, RSI, SMA, SMA15, StochasticOscillator, StochasticRSI, TDS, TR, TechnicalIndicator, TradingSignal, TrendIndicatorSeries, VWAP, WMA, WSMA, WilliamsR, ZigZag, getAverage, getGrid, getMaximum, getMedian, getMinimum, getQuartile, getStandardDeviation, getStreaks, isFriday, isMonday, isSaturday, isSunday, isThursday, isTuesday, isWednesday, pushUpdate };