mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-08 05:57:43 +00:00
86fe32a682
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: aider (openrouter/anthropic/claude-sonnet-4) <aider@aider.chat> Co-authored-by: Warp <agent@warp.dev>
41 lines
1.2 KiB
Plaintext
41 lines
1.2 KiB
Plaintext
// The MIT License (MIT)
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Average True Range (ATR)", "ATR", overlay=false)
|
|
|
|
//@function Calculates the Average True Range (ATR)
|
|
//@param length The period length for the ATR calculation.
|
|
//@returns The ATR value.
|
|
//@optimized Beta precomputation for RMA warmup compensation
|
|
atr(simple int length) =>
|
|
if length <= 0
|
|
runtime.error("Period must be greater than 0")
|
|
var float prevClose = close
|
|
float tr1 = high - low
|
|
float tr2 = math.abs(high - prevClose)
|
|
float tr3 = math.abs(low - prevClose)
|
|
float trueRange = math.max(tr1, tr2, tr3)
|
|
prevClose := close
|
|
float alpha = 1.0 / float(length)
|
|
float beta = 1.0 - alpha
|
|
var float EPSILON = 1e-10
|
|
var float raw_rma = 0.0
|
|
var float e = 1.0
|
|
if not na(trueRange)
|
|
raw_rma := (raw_rma * (length - 1) + trueRange) / length
|
|
e *= beta
|
|
e > EPSILON ? raw_rma / (1.0 - e) : raw_rma
|
|
else
|
|
na
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
i_length = input.int(14, "Length", minval=1, tooltip="Number of bars used for the ATR calculation")
|
|
|
|
// Calculation
|
|
atrValue = atr(i_length)
|
|
|
|
// Plot
|
|
plot(atrValue, "ATR", color=color.yellow, linewidth=2)
|