trading-signals
Version:
Technical indicators to run technical analysis with JavaScript / TypeScript.
43 lines • 1.35 kB
JavaScript
import { MovingAverage } from '../MA/MovingAverage.js';
import { NotEnoughDataError } from '../../error/index.js';
export class EMA extends MovingAverage {
#pricesCounter = 0;
#weightFactor;
interval;
constructor(interval) {
super(interval);
this.interval = interval;
this.#weightFactor = 2 / (this.interval + 1);
}
getRequiredInputs() {
return this.interval;
}
update(price, replace) {
if (!replace) {
this.#pricesCounter++;
}
else if (replace && this.#pricesCounter === 0) {
this.#pricesCounter++;
}
if (replace && this.previousResult !== undefined) {
return this.setResult(price * this.#weightFactor + this.previousResult * (1 - this.#weightFactor), replace);
}
return this.setResult(price * this.#weightFactor + (this.result !== undefined ? this.result : price) * (1 - this.#weightFactor), replace);
}
getResultOrThrow() {
if (this.#pricesCounter < this.interval) {
throw new NotEnoughDataError(this.getRequiredInputs());
}
return this.result;
}
get isStable() {
try {
this.getResultOrThrow();
return true;
}
catch {
return false;
}
}
}
//# sourceMappingURL=EMA.js.map