OPEN-SOURCE SCRIPT
Zaktualizowano

ATR Extension from Moving Average, with Robust Sigma Bands

349


# ATR Extension from Moving Average, with Robust Sigma Bands

**What it does**
This indicator measures how far price is from a selected moving average, expressed in **ATR multiples**, then overlays **robust sigma bands** around the long run central tendency of that extension. Positive values mean price is extended above the MA, negative values mean price is extended below the MA. The signal adapts to volatility through ATR, which makes comparisons consistent across symbols and regimes.

**Why it can help**

* Normalizes distance to an MA by ATR, which controls for changing volatility
* Uses the **bar’s extreme** against the MA, not just the close, so it captures true stretch
* Computes a **median** and **standard deviation** of the extension over a multi-year window, which yields simple, intuitive bands for trend and mean-reversion decisions

---

## Inputs

* **MA length**: default 50, options 200, 64, 50, 20, 9, 4, 3
* **MA timeframe**: Daily or Weekly. The MA is computed on the chosen higher timeframe through `request.security`.
* **MA type**: EMA or SMA
* **Years lookback**: 1 to 10 years, default 5. This sets the sample for the median and sigma calculation, `years * 365` bars.
* **Line width**: visual width of the plotted extension series
* **Table**: optional on-chart table that displays the current long run **median** and **sigma** of the extension, with selectable text size

**Fixed parameters in this release**

* **ATR length**: 20 on the daily timeframe
* **ATR type**: classic ATR. ADR percent is not enabled in this version.

---

## Plots and colors

* **Main plot**: “Extension from 50d EMA” by default. Value is in **ATR multiples**.
* **Reference lines**:

* `median` line, black dashed
* +2σ orange, +3σ red
* −2σ blue, −3σ green

---

## How it is calculated

1. **Moving average** on the selected higher timeframe: EMA or SMA of `close`.
2. **Extreme-based distance** from MA, as a percent of price:

* If `close > MA`, use `(high − MA) / close * 100`
* Else, use `(low − MA) / close * 100`
3. **ATR percent** on the daily timeframe: `ATR(20) / close * 100`
4. **ATR multiples**: extension percent divided by ATR percent
5. **Robust center and spread** over the chosen lookback window:

* Center: **median** of the ATR-multiple series
* Spread: **standard deviation** of that series
* Bands: center ± 1σ, 2σ, 3σ, with 2σ and 3σ drawn

This design yields an intuitive unit scale. A value of **+2.0** means price is about 2 ATR above the selected MA by the most stretched side of the current bar. A value of **−3.0** means roughly 3 ATR below.

---

## Practical use

* **Trend continuation**

* Sustained readings near or above **+1σ** together with a rising MA often signal healthy momentum.
* **Mean reversion**

* Spikes into **±2σ** or **±3σ** can identify stretched conditions for fade setups in range or late-trend environments.
* **Regime awareness**

* The **median** moves slowly. When median drifts positive for many months, the market spends more time extended above the MA, which often marks bullish regimes. The opposite applies in bearish regimes.

**Notes**

* The MA can be set to Weekly while ATR remains Daily. This is deliberate, it keeps the normalization stable for most symbols.
* On very short intraday charts, the extension remains meaningful since it references the session’s extreme against a higher-timeframe MA and a daily ATR.
* Symbols with short histories may not fill the lookback window. Bands will adapt as data accrues.

---

## Table overlay

Enable **Table → Show** to see:

* “ATR from \<MA>”
* Current **median** and **sigma** of the extension series for your lookback

---

## Recommended settings

* **Swing equities**: 50 EMA on Daily, 5 to 7 years
* **Index trend work**: 200 EMA on Daily, 10 years
* **Position trading**: 20 or 50 EMA on Weekly MA, 5 to 10 years

---

## Interpretation examples

* Reading **+2.7** with price above a rising 50 EMA, near prior highs

* Strong trend extension, consider pyramiding in trend systems or waiting for a pullback if you are a mean-reverter.
* Reading **−2.2** into multi-month support with flattening MA

* Stretch to the downside that often mean-reverts, size entries based on your system rules.

---

## Credits

The concept of measuring stretch from a moving average in ATR units has a rich community history. This implementation and its presentation draw on ideas popularized by **Jeff Sun**, **SugarTrader**, and **Steve D Jacobs**. Thanks to each for their contributions to ATR-based extension thinking.

---

## License

This script and description are distributed under **MPL-2.0**, consistent with the header in the source code.

---

## Changelog

* **v1.0**: Initial public release. Daily ATR normalization, EMA or SMA on D or W timeframe, robust median and sigma bands, optional table.

---

## Disclaimer

This tool is for educational use only. It is not financial advice. Always test on your own data and strategies, then manage risk accordingly.
Informacje o Wersji
# Extension — Release Notes

**Version:** 1.1.0
**Author:** BB\_9791
**What it does:** plots the distance of price from a chosen MA, normalized by ATR, with an EMA cloud and sigma bands

## What is new

* Robust on short histories, the script now detects how many bars exist on the selected timeframe, then defers calculations until the data is sufficient.
* Adaptive statistics, `mean` and `stdev` are computed on an effective window that never exceeds available history.
* Safe drawing, plots, fills, and table cells only render when inputs are valid, no more `na` leaks or partial bands.
* Non-repainting consistency, all `request.security` calls use `lookahead=barmerge.lookahead_off`.
* Cleaner table header, shows the chosen MA type and length.
* Title shortened to **Extension**, consistent with other tools in the set.

## Details of the change

1. **Core readiness checks**

* Count bars on the selected timeframe with `request.security(..., ta.cum(1))`.
* Require `max(MA length, ATR length + 1)` bars, plus non-`na` `MA` and `ATR`, before computing the core series.
* `gainfrommaATR3` is set to `na` until the requirement is met.

2. **Adaptive statistics**

* Convert `Years lookback` to bars based on timeframe, 252 per year for daily, 52 per year for weekly.
* Effective window `eff_len` equals `min(target_len, valid_samples)`, with a floor of 2.
* `ta.median` and `ta.stdev` are always called, results are then masked if `eff_len` is too small, this removes the Pine warning about conditional function calls.

3. **Drawing logic**

* EMA cloud uses gray while EMAs are warming up.
* Sigma lines and fills are created only when `mean` and `stdev` exist.
* Table shows `n/a` for stats until they are ready.

4. **Non-repainting**

* All `request.security` calls set `lookahead=barmerge.lookahead_off` for consistent historical behavior.

## User impact

* On tickers with short history, the script waits until it has enough bars, then starts plotting, no errors, no stray fills.
* On tickers with ample history, results are consistent with the old script, except for the statistics window, see note below.

## Notes on the statistics window

* The old script used calendar days for the window length, `years * 365`.
* The new script uses trading bars per year, 252 for daily, 52 for weekly, which is more appropriate for market data.
* If you need to approximate the old behavior, increase `Years lookback` to compensate, 365/252 is about 1.45 for daily.

## Inputs that matter

* **MA length, timeframe, type** control the baseline.
* **ATR length** is fixed at 20 internally, exposed as constant for stability.
* **Years lookback** sets the target statistical window, the script adapts down if history is shorter.
* **Absolute vs Relative** controls whether the series is `symbol` or `symbol/benchmark`.

## Compatibility

* No setting changes required.
* Plots can start later on young tickers, by design.
* Table header shows `EMA` or `SMA` explicitly.

## Changelog

* Added `core_ready` gating for MA and ATR.
* Replaced fixed `years * 365` with timeframe aware `years * per_year`.
* Added `valid_count` and `eff_len` to bound statistics by available data.
* Resolved Pine consistency warning by computing `mean_all` and `stdev_all` unconditionally, then masking.
* Standardized all `request.security` calls with `lookahead=barmerge.lookahead_off`.
* Retitled the main plot to **Extension** and updated the table header.

Wyłączenie odpowiedzialności

Informacje i publikacje przygotowane przez TradingView lub jego użytkowników, prezentowane na tej stronie, nie stanowią rekomendacji ani porad handlowych, inwestycyjnych i finansowych i nie powinny być w ten sposób traktowane ani wykorzystywane. Więcej informacji na ten temat znajdziesz w naszym Regulaminie.