ATR (Average True Range)
ATR measures market volatility by averaging the true range over a period. True Range accounts for gaps between bars, making it more accurate than simple high-low range.
Declaration
function init(ctx) { ctx.indicator('atr', 'ATR', { period: 14 }); }
Options
| Option | Type | Default | Description |
|---|---|---|---|
period | number | 14 | Smoothing period |
Output
Returns a single number[] series (always positive, in price units).
Accessing Values
function onBar(ctx, i) { const atrValue = ctx.ind.atr[i]; }
Use Cases
ATR-Based Stop Loss
function onBar(ctx, i) { const atr = ctx.ind.atr[i]; const close = ctx.series.close[i]; // Place stop 2 ATR below entry const stopLoss = close - (2 * atr); if (q.crossOver(ctx.ind.fast, ctx.ind.slow, i)) { ctx.order.market('ASSET', 1, { signal: 'buy', reason: 'entry', stopLoss: stopLoss }); } }
Position Sizing by Volatility
function onBar(ctx, i) { const atr = ctx.ind.atr[i]; const close = ctx.series.close[i]; // Risk 1% of capital per ATR const riskPerUnit = 2 * atr; const capitalRisk = 1000 * 0.01; // 1% of $1000 const positionSize = capitalRisk / riskPerUnit; }
Volatility Filter
function onBar(ctx, i) { const atr = ctx.ind.atr[i]; const close = ctx.series.close[i]; const atrPercent = (atr / close) * 100; // Only trade when volatility is moderate if (atrPercent > 1 && atrPercent < 5) { // Good trading conditions } }
Calculation
True Range = max(High - Low, |High - prevClose|, |Low - prevClose|)
$ATR = EMA(TrueRange, period)$
Related
- Bollinger Bands - Volatility-based bands
- Keltner Channels - Uses ATR for band width
- Donchian - Price range channel
indicatoratrvolatilitytrue-rangeqsl