UNPKG

trading-signals

Version:

Technical indicators to run technical analysis with JavaScript / TypeScript.

61 lines 1.98 kB
import { TechnicalIndicator, TradingSignal } from '../../base/Indicator.js'; import { pushUpdate } from '../../util/pushUpdate.js'; export class MACD extends TechnicalIndicator { prices = []; #previousResult; short; long; signal; constructor(short, long, signal) { super(); this.short = short; this.long = long; this.signal = signal; } getRequiredInputs() { return this.long.getRequiredInputs(); } update(price, replace) { pushUpdate(this.prices, replace, price, this.long.interval); const short = this.short.update(price, replace); const long = this.long.update(price, replace); if (this.prices.length === this.long.interval) { const macd = short - long; const signal = this.signal.update(macd, replace); if (replace) { this.result = this.#previousResult; } this.#previousResult = this.result; return (this.result = { histogram: macd - signal, macd, signal, }); } return null; } calculateSignal(result) { const hasResult = result !== null && result !== undefined; const isBullish = hasResult && result.histogram > 0; const isBearish = hasResult && result.histogram < 0; switch (true) { case !hasResult: return TradingSignal.UNKNOWN; case isBullish: return TradingSignal.BULLISH; case isBearish: default: return TradingSignal.BEARISH; } } getSignal() { const previousState = this.calculateSignal(this.#previousResult); const state = this.calculateSignal(this.getResult()); const hasChanged = previousState !== state; return { hasChanged, state, }; } } //# sourceMappingURL=MACD.js.map