|
| 1 | +import { Indicator, IndicatorInput } from '@/indicator'; |
| 2 | +import { RollingWindow } from '@/utils/RollingWindow'; |
| 3 | + |
| 4 | +export interface WILLRInput extends IndicatorInput { |
| 5 | + high: number[]; |
| 6 | + low: number[]; |
| 7 | + close: number[]; |
| 8 | + |
| 9 | + /** |
| 10 | + * It's period. |
| 11 | + * @default 14 |
| 12 | + */ |
| 13 | + period?: number; |
| 14 | +} |
| 15 | + |
| 16 | +export type WILLROutput = number | undefined; |
| 17 | + |
| 18 | +export interface WILLRTick { |
| 19 | + high: number; |
| 20 | + low: number; |
| 21 | + close: number; |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * ### William's Percent R (WILLR) |
| 26 | + * |
| 27 | + * William's Percent R is a momentum oscillator similar to the Stochastic Oscillator. |
| 28 | + * It attempts to identify overbought and oversold conditions. |
| 29 | + * |
| 30 | + * **Calculation**: |
| 31 | + * |
| 32 | + * ``` |
| 33 | + * WILLR = 100 * ((close - LL) / (HH - LL) - 1) |
| 34 | + * ``` |
| 35 | + * |
| 36 | + * Where: |
| 37 | + * - `LL` is the lowest low for the look-back period. |
| 38 | + * - `HH` is the highest high for the look-back period. |
| 39 | + * |
| 40 | + * **Sources**: |
| 41 | + * |
| 42 | + * - https://www.tradingview.com/wiki/Williams_%25R_(%25R) |
| 43 | + */ |
| 44 | +export class WILLR extends Indicator<WILLROutput, WILLRTick> { |
| 45 | + period: number; |
| 46 | + |
| 47 | + protected override result: WILLROutput[] = []; |
| 48 | + protected override generator; |
| 49 | + |
| 50 | + constructor(input: WILLRInput) { |
| 51 | + super(input); |
| 52 | + |
| 53 | + this.period = input.period || 14; |
| 54 | + |
| 55 | + this.generator = this.willrGenerator(); |
| 56 | + this.generator.next(); |
| 57 | + |
| 58 | + input.high.forEach((high, index) => { |
| 59 | + this.nextValue({ |
| 60 | + high, |
| 61 | + low: input.low[index]!, |
| 62 | + close: input.close[index]!, |
| 63 | + }); |
| 64 | + }); |
| 65 | + } |
| 66 | + |
| 67 | + private *willrGenerator(): IterableIterator<WILLROutput, never, WILLRTick> { |
| 68 | + const highWindow = new RollingWindow(this.period); |
| 69 | + const lowWindow = new RollingWindow(this.period); |
| 70 | + |
| 71 | + let tick = yield; |
| 72 | + let output; |
| 73 | + |
| 74 | + while (true) { |
| 75 | + highWindow.push(tick.high); |
| 76 | + lowWindow.push(tick.low); |
| 77 | + |
| 78 | + if (highWindow.filled()) { |
| 79 | + const lowestLow = lowWindow.lowest(); |
| 80 | + const highestHigh = highWindow.highest(); |
| 81 | + |
| 82 | + output = 100 * ((tick.close - lowestLow) / (highestHigh - lowestLow) - 1); |
| 83 | + } |
| 84 | + |
| 85 | + tick = yield output; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + static calculate(input: WILLRInput): WILLROutput[] { |
| 90 | + return new WILLR(input).getResult(); |
| 91 | + } |
| 92 | +} |
0 commit comments