1Branch0Tags
typescript
import type { Bar } from "../types";
export function computeAtr(bars: Bar[], period = 14): number | null {
if (bars.length < period + 1) return null;
const ranges: number[] = [];
for (let i = 1; i < bars.length; i += 1) {
const current = bars[i];
const prev = bars[i - 1];
const rangeHighLow = current.high - current.low;
const rangeHighClose = Math.abs(current.high - prev.close);
const rangeLowClose = Math.abs(current.low - prev.close);
ranges.push(Math.max(rangeHighLow, rangeHighClose, rangeLowClose));
}
if (ranges.length < period) return null;
const slice = ranges.slice(-period);
const sum = slice.reduce((total, value) => total + value, 0);
return sum / period;
}