trading-signals 7.2.0 → 7.4.3

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