UNPKG

@sunrise1002/tats

Version:

Techincal Indicators written in javascript

63 lines (62 loc) 1.96 kB
import { Indicator, IndicatorInput } from '../indicator/indicator'; export class AvgGainInput extends IndicatorInput { } export class AverageGain extends Indicator { constructor(input) { super(input); let values = input.values; let period = input.period; let format = this.format; this.generator = (function* (period) { var currentValue = yield; var counter = 1; var gainSum = 0; var avgGain; var gain; var lastValue = currentValue; currentValue = yield; while (true) { gain = currentValue - lastValue; gain = gain > 0 ? gain : 0; if (gain > 0) { gainSum = gainSum + gain; } if (counter < period) { counter++; } else if (avgGain === undefined) { avgGain = gainSum / period; } else { avgGain = ((avgGain * (period - 1)) + gain) / period; } lastValue = currentValue; avgGain = (avgGain !== undefined) ? format(avgGain) : undefined; currentValue = yield avgGain; } })(period); this.generator.next(); this.result = []; values.forEach((tick) => { var result = this.generator.next(tick); if (result.value !== undefined) { this.result.push(result.value); } }); } nextValue(price) { return this.generator.next(price).value; } ; } AverageGain.calculate = averagegain; export function averagegain(input) { Indicator.reverseInputs(input); var result = new AverageGain(input).result; if (input.reversedInput) { result.reverse(); } Indicator.reverseInputs(input); return result; } ;