Indicator · Pine Script v6 · On the chart

MA Envelope (MAE)

by mihakralj

The MA Envelope indicator calculates upper and lower channel bands shifted by a user-defined percentage around a baseline moving average.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code70
Settings4inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

70 lines of Pine Script v6 from lib/channels/maenv/maenv.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

maenv.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("MA Envelope (MAE)", "MAE", overlay=true)

//@function Calculates MA Envelope bands using a fixed percentage
//@param source Series to calculate moving average from
//@param length Lookback period for MA calculation
//@param percentage Distance of bands from MA as percentage
//@param ma_type Type of moving average (0:SMA, 1:EMA, 2:WMA)
//@returns tuple with [middle, upper, lower] band values
//@optimized SMA uses circular buffer O(1), EMA uses warmup O(1), WMA is O(n)
mae(series float source, simple int length, simple float percentage, simple int ma_type = 1) =>
    if length <= 0 or percentage <= 0.0
        runtime.error("Length and percentage must be greater than 0")
    float middle = na
    if ma_type == 0
        var int head = 0
        var int count = 0
        var array<float> buffer = array.new_float(length, na)
        var float sum = 0.0
        float oldest = array.get(buffer, head)
        if not na(oldest)
            sum -= oldest
            count -= 1
        float current = nz(source)
        sum += current
        count += 1
        array.set(buffer, head, current)
        head := (head + 1) % length
        middle := sum / count
    else if ma_type == 1
        var float alpha = 2.0 / (length + 1)
        var float sum = 0.0
        var float weight = 0.0
        if na(sum)
            sum := source
            weight := 1.0
        sum := sum * (1.0 - alpha) + source * alpha
        weight := weight * (1.0 - alpha) + alpha
        middle := sum / weight
    else if ma_type == 2
        float norm = 0.0
        float sum = 0.0
        for i = 0 to length - 1
            float w = float((length - i) * length)
            norm += w
            sum += nz(source[i]) * w
        middle := sum / norm
    else
        runtime.error("MA type must be 0 (SMA), 1 (EMA), or 2 (WMA)")
    float dist = middle * percentage / 100.0
    [middle, middle + dist, middle - dist]

// ---------- Main loop ----------

// Inputs
i_source = input.source(close, "Source")
i_length = input.int(20, "Length", minval=1)
i_percentage = input.float(1.0, "Percentage", minval=0.001)
i_ma_type = input.int(1, "MA Type", minval=0, maxval=2, tooltip="0:SMA, 1:EMA, 2:WMA")

// Calculation
[middle, upper, lower] = mae(i_source, i_length, i_percentage, i_ma_type)

// Plot
plot(middle, "Middle", color=color.yellow, linewidth=2)
p1 = plot(upper, "Upper", color=color.yellow, linewidth=2)
p2 = plot(lower, "Lower", color=color.yellow, linewidth=2)
fill(p1, p2, color=color.new(color.blue, 90), title="Band Fill")

Overview

MA Envelope (MAE) supports Simple Moving Average, Exponential Moving Average, and Weighted Moving Average calculation types. The script plots the central moving average line and envelope bands directly on the main price chart, shading the region between the bands. Input settings allow adjustments to the lookback period, source price, distance percentage, and baseline average type.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Moving averages, Support & resistance, Volatility & bands, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosei_source
Lengthint20i_length
Percentagefloat1.0i_percentage
MA Typeint1i_ma_type
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Trend Compass 4H

by chris-c-thomas
14 stars

Trend Compass 4H plots a multi-EMA ribbon (10/21/50) along with higher-timeframe reference levels on the price chart. It classifies trend phase into six states and calculates a composite weighted trend score. The script detects RSI and MACD divergences, analyz

Indicator v6 TrendMoving averages
Updated 6 months ago · MIT GitHub repository of Trend Compass 4H
10 stars

My Macro Cycle Indicator plots daily and weekly simple and exponential moving averages on the price chart, plus Pi Cycle and Mayer Multiple levels derived from the 200-day average. Optional toggles add support-band fills, a Keltner channel, CME futures gaps, a

Indicator v4 Moving averagesVolatility & bands
Updated 5 years ago · None stated GitHub repository of My Macro Cycle Indicator

VOIDRLM

by voidrlm
6 stars

The script VOIDRLM combines multiple technical analysis tools into a single overlay indicator on the price chart. It calculates multi-timeframe pivot points, volume-weighted average price (VWAP), customizable moving averages, moving average clouds, supply and

Indicator v5 TrendMoving averages Repaints
Updated 3 years ago · None stated GitHub repository of VOIDRLM
318 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers