Indicator · Pine Script v6 · Own pane

Ehlers Automatic Gain Control (AGC)

by mihakralj

Ehlers Automatic Gain Control (AGC) detrends raw price data using a roofing filter—combining a two-pole high-pass filter and a Super Smoother—to generate a zero-mean oscillating signal.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code96
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

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

agc.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
// Indicator algorithm (C) 2015 John F. Ehlers
indicator("Ehlers Automatic Gain Control (AGC)", "AGC", overlay=false)

//@function Ehlers Automatic Gain Control — amplitude normalization via exponential peak tracking
//@param source Series to normalize (must oscillate around zero — use a filter output, not raw price)
//@param decay Peak decay factor per bar (controls adaptation speed; 0.991 ≈ 110-bar half-life)
//@returns Amplitude-normalized signal in [-1, +1] range
//@optimized O(1) per bar — single division + comparison, zero lookback
agc(series float src, simple float decay) =>
    var float peak = 0.0000001

    float ssrc = nz(src, 0.0)

    // Exponential peak decay — shrinks peak toward zero between excitations
    peak := decay * peak

    // Track running peak — ratchets up when signal exceeds decayed peak
    if math.abs(ssrc) > peak
        peak := math.abs(ssrc)

    // Guard against zero division (peak initialized to tiny positive value)
    float result = peak > 0.0 ? ssrc / peak : 0.0
    result

//@function Roofing filter — 2-pole HPF → Super Smoother bandpass for detrending raw price
//@param source Raw price series
//@param hpLength Highpass cutoff period (removes trend below this period)
//@param ssLength Super Smoother cutoff period (removes noise above this period)
//@returns Detrended, smoothed oscillation around zero
roofing(series float src, simple int hpLength, simple int ssLength) =>
    var float SQRT2_PI = math.sqrt(2.0) * math.pi

    // --- Stage 1: 2-pole Butterworth Highpass ---
    int safe_hp = math.max(hpLength, 1)
    var float hp_c1 = 0.0
    var float hp_c2 = 0.0
    var float hp_c3 = 0.0
    var int prev_hp = 0
    if prev_hp != safe_hp
        float hp_arg = SQRT2_PI / float(safe_hp)
        float hp_exp = math.exp(-hp_arg)
        hp_c2 := 2.0 * hp_exp * math.cos(hp_arg)
        hp_c3 := -hp_exp * hp_exp
        hp_c1 := (1.0 + hp_c2 - hp_c3) / 4.0
        prev_hp := safe_hp

    var float hp = 0.0
    float ssrc = nz(src, src[1])
    float src1 = nz(src[1], ssrc)
    float src2 = nz(src[2], src1)
    hp := hp_c1 * (ssrc - 2.0 * src1 + src2) + hp_c2 * nz(hp[1], 0.0) + hp_c3 * nz(hp[2], 0.0)

    // --- Stage 2: Super Smoother ---
    int safe_ss = math.max(ssLength, 1)
    var float ss_c1 = 0.0
    var float ss_c2 = 0.0
    var float ss_c3 = 0.0
    var int prev_ss = 0
    if prev_ss != safe_ss
        float ss_arg = SQRT2_PI / float(safe_ss)
        float ss_exp = math.exp(-ss_arg)
        ss_c2 := 2.0 * ss_exp * math.cos(ss_arg)
        ss_c3 := -ss_exp * ss_exp
        ss_c1 := 1.0 - ss_c2 - ss_c3
        prev_ss := safe_ss

    var float roof = 0.0
    roof := ss_c1 * hp + ss_c2 * nz(roof[1], hp) + ss_c3 * nz(roof[2], nz(hp[1], hp))
    roof

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

// Inputs
i_decay    = input.float(0.991, "Decay", minval=0.9, maxval=0.9999, step=0.001,
             tooltip="Peak decay factor per bar (0.991 ≈ 110-bar half-life)")
i_hpLength = input.int(48, "HP Length", minval=1,
             tooltip="Highpass cutoff period — removes trend cycles longer than this")
i_ssLength = input.int(10, "SS Length", minval=1,
             tooltip="Super Smoother cutoff — removes noise cycles shorter than this")
i_source   = input.source(close, "Source")

// Preprocessing: Roofing filter detrends raw price into zero-mean oscillation
filt = roofing(i_source, i_hpLength, i_ssLength)

// AGC normalization of the detrended signal
agc_val = agc(filt, i_decay)

// Plot
plot(agc_val, "AGC", color=color.new(color.blue, 0), linewidth=2)
plot(filt, "Filter", color=color.new(color.gray, 60), linewidth=1)
hline(1.0, "+1", color=color.gray, linestyle=hline.style_dotted)
hline(0, "Zero", color=color.gray, linestyle=hline.style_dotted)
hline(-1.0, "-1", color=color.gray, linestyle=hline.style_dotted)

Overview

Ehlers Automatic Gain Control (AGC) then applies an automatic gain control algorithm that tracks exponential peak decay to normalize amplitude scaling dynamically within a -1 to +1 range. Plotted in a separate pane, the output provides normalized oscillator values. Input settings allow adjustment of the peak decay rate, high-pass cutoff period, Super Smoother length, and source price.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Volatility & bands

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
Decayfloat0.991i_decay
HP Lengthint48i_hpLength
SS Lengthint10i_ssLength
Sourcesourceclosei_source
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

TTM Squeeze

by Alorse
330 stars

This indicator plots a TTM Squeeze momentum oscillator in a separate pane. It compares a Bollinger Band offset to a Keltner Channel offset and marks the zero line white when the difference is non-negative and black when the bands are inside the channel. A line

Indicator v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of TTM Squeeze

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V
218 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector
147 stars

This indicator generates trade entry signals and target levels optimized for 1-hour timeframes, designed for external signal extraction. It calculates 7-period and 16-period EMAs alongside 10-period RSI and ATR filters. Long signals occur when the fast EMA cro

Indicator v5 TrendOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of Signal Strategy 100 Candles of 1H Timeframe

Bubbles Indicator

by capissimo
114 stars

The Bubbles Indicator measures volatility squeezes and expansion bursts using Bollinger Bands combined with a sinusoid oscillator and RSI divergence. It processes price data through scaled Bollinger Bands to highlight volatility changes while confirming trend

Indicator v4 Volatility & bandsOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Bubbles Indicator

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