Moving Average Envelopes in Pine Script
A moving average with lines a fixed percentage above and below it, the simplest band: the width does not adapt to volatility, so you choose it for the instrument and timeframe.
Definition
Moving average envelopes are two lines drawn a fixed percentage above and below a moving average. With a 20-bar average and a 2 percent setting, the upper envelope is the average times 1.02 and the lower the average times 0.98. They are the oldest and simplest member of the bands and channels family, and the fixed width is the point: the envelope states how far price is from its average in percentage terms, a measure that does not change when volatility does. Everything else in the family replaced the percentage with an adaptive unit.
Price oscillates around its average, and a percentage distance from the average is a natural way to say how stretched it is. A stock 10 percent above its 200-day average is extended by a standard traders have used for decades. Because the width is fixed, envelopes carry a stable meaning across time: a touch this year means the same stretch as a touch last year. That is also their weakness. In a volatile period price lives outside them for weeks, and in a quiet one it never reaches them, so the width has to be chosen for the instrument and the timeframe.
Envelopes predate Bollinger Bands and were among the first trading bands drawn on charts, so no single attribution stands. The common settings are a 20-bar average with 2 to 5 percent on daily charts of stocks and indices, and the 200-day average with 5 to 10 percent for long-term stretch. The library script draws a simple moving average, 20 by default, with 2 percent envelopes, offers an exponential basis as a switch, and marks a long when the close crosses back inside the lower envelope and a short when it crosses back inside the upper.
On the chart the envelope is a corridor whose width in price grows with the price level, so on a log scale it looks constant. In a range price bounces between the lines and returns to the average, which is the reversion trade the script marks. In a trend price walks outside one envelope and the average follows, and the return inside then marks the end of the thrust rather than a reversal. When volatility changes regime the envelope stops fitting: touches become constant or disappear, and the percentage needs to be reset. A trader who watches touch frequency knows when that has happened.
Reading the chart
Calibrate the width before reading anything, because a percentage that fits one instrument is meaningless on another.
- Look back over a few hundred bars and count how often the lines were touched. A good width is touched at swing extremes only, a few times a month on daily bars, not every week and not once a year.
- Read the slope of the average. A rising basis is a bullish bias, and reversion trades against the trend are taken only toward the average, never through it.
- Locate the close. Outside the upper envelope price is stretched above its average by more than the set percentage; outside the lower, stretched below by the same amount.
- Wait for the return inside. The library's trigger is the close crossing back inside the envelope on a confirmed bar: back above the lower line for a long, back below the upper line for a short.
- Check for a walk. Several closes outside one envelope with the average steepening is a trend, and the return inside marks a pause, not the fade.
- Recalibrate when the regime changes. If price has lived outside the lines for weeks, or has not touched them in months, the percentage no longer describes this market.
The maths
The envelope is the moving average scaled up and down by a fixed percentage.
The lines are symmetric in percent, so the distance in price is the same above and below, basis × p / 100, and it grows with the price level.
An exponential basis turns sooner than a simple one, so touches and returns come a bar or two earlier; the library script switches between them with one input.
Tying the percentage to volatility, for example p equal to a multiple of ATR divided by the basis, turns the envelope into an ATR band, which is the adaptive form in the library's ATR Bands template.
Some traders use asymmetric widths, a wider upper envelope in an uptrend, to reflect the skew of the move; the library keeps them symmetric.
Inputs that matter
| Input | Typical | What changing it does |
|---|---|---|
| MA length | 20 | Shorter makes the envelope wrap tightly around swings and touch often; longer turns it into a slow corridor that only big moves leave. |
| Envelope % | 2 | Wider means fewer and more extreme touches; the right value depends on the instrument's volatility and the timeframe, so calibrate by touch frequency. |
| Use EMA basis | off | On, the basis turns earlier and touches come sooner; off, the simple average is steadier and the envelope moves less. |
In practice
- As a reversion trigger in a range: the close back inside an envelope is the entry the library script marks, the average is the target, and a stop sits beyond the recent extreme.
- As a long-term stretch gauge: a 5 to 10 percent envelope on the 200-day average shows when a stock or index has run far from its mean, a level long-term buyers and sellers watch.
- As a trend strength read: price walking outside the upper envelope with a rising basis is a strong trend, and the first close back inside is a pause, not the top.
- As a percentage alert: an alert on the cross of the upper envelope is an alert that price is a set percentage above its average, useful for scanning a watchlist for extended names.
- As a consistent measure across time: because the width is fixed, envelope touches on one chart mean the same stretch every year, which helps when comparing episodes.
- As a simple regime flag: when touches become constant or vanish, volatility has changed, and that is a prompt to review stops and sizes elsewhere.
Where it goes wrong
- Using one percentage for every instrument. A 2 percent envelope suits a slow index and sits inside the daily noise of a volatile stock; calibrate each chart.
- Leaving the width unchanged through a volatility regime change. Touches that were monthly become daily; reset the percentage or switch to an adaptive band.
- Fading the envelope in a trend. A walk outside the upper line with a rising basis is strength; wait for the return inside and read it as a pause.
- Confusing envelopes with Bollinger Bands. The envelope does not know about volatility; a touch means a fixed percentage stretch, not a statistical extreme.
Compared with
Bollinger Bands. Bollinger Bands set their width from the standard deviation of closes, so they breathe with volatility. Envelopes hold a fixed percentage, which keeps their meaning constant across time and makes them wrong when volatility shifts.
Keltner Channels. Keltner channels set their width from average true range around an EMA. An envelope uses a percentage of the average, so its width scales with price level rather than with how much the market moves each bar.
Average True Range. ATR bands are envelopes whose width is a multiple of ATR instead of a percentage of the average. They adapt to volatility automatically, and they are the natural upgrade when a fixed envelope stops fitting the market.
Moving Average. A single moving average gives a line and a side. The envelope adds a tolerance around it, so a small overshoot is not a signal and only a stretch beyond the set percentage counts as an extreme.
Build it in Quant
Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.
Questions
What percentage should I use?
The one that puts touches at swing extremes on your chart, not a universal number. Start at 2 percent for a 20-bar average on daily index or large-cap charts, 5 to 10 percent for the 200-day, and less than 1 percent on intraday charts, then look back over a few hundred bars and adjust until touches are rare but not absent.
Simple or exponential basis?
The simple average is the traditional basis and gives a steadier envelope. The exponential average turns sooner, so returns inside are marked a bar or two earlier, at the cost of a few more false signals. The library script switches with one input; test both on the instrument rather than assuming one is better.
Why use envelopes instead of Bollinger Bands?
For a fixed, comparable measure. A percentage stretch from the average means the same thing every year and on every chart with the same setting, while a 2-deviation band changes width daily. Long-term traders who think in percent from the 200-day average prefer the envelope; short-term traders usually prefer adaptive bands.
What does a close outside the envelope mean in a trend?
That the trend is strong enough to hold price a set percentage from its average. It is not a fade. The useful event is the first close back inside, which marks the end of the thrust; if the average keeps rising and price holds above it, the trend continues and the next walk outside is likely.
Can I use the envelope as a stop?
Loosely. In an uptrend the lower envelope rises with the average and sits a fixed percentage below it, so a close under it is a reasonable exit for a slow trend trade. It is not ratcheted and it does not adapt to volatility, so an ATR trailing stop or a Chandelier exit is a better stop for most trades.
Do envelopes work on intraday charts?
They do, with a small percentage tuned to the instrument, often a fraction of 1 percent on 5 to 15-minute bars. Intraday volatility changes across the session, so the fixed width fits the open worse than the middle of the day. Most intraday traders use an ATR band instead, which is the same idea with an adaptive width.