Indicator · Pine Script v5 · On the chart

Color Changing Moving Average

by g-moe· code credited to goodgains

This indicator calculates a simple or exponential moving average and dynamically colors its plot based on the slope angle of the average line.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code58
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 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

58 lines of Pine Script v5 from Tradingview/color-changing-moving-average.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

color-changing-moving-average.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5
indicator(title="Color Changing Moving Average", shorttitle="Colored MA", overlay=true)

// @keywords: moving-average, simple-moving-average, exponential-moving-average, ema-sma-toggle, ma-slope, slope-angle, atr-normalized-angle, trend-direction, bullish-trend, bearish-trend, neutral-trend, trend-reversal, trend-alerts, bull-bear-alerts, angle-lookback, atr-period, custom-ma-length, price-source-input, angle-based-ma, dual-trend-plot

//inputs
i_lookback   = input.int(2,     "Angle Period", minval = 1)
i_atrPeriod  = input.int(10,    "ATR Period",  minval = 1)
i_angleLevel = input.int(6,     "Angle Level",  minval = 1)

len = input.int(21, minval=1, title="Length")
src = input.source(close, title="Source")
offset = 0
type=input.bool(true, "Use EMA? (Off=SMA)")

out=type? ta.ema(src, len) : ta.sma(src, len)

//color change
f_angle(_src, _lookback, _atrPeriod) =>
    rad2degree = 180 / 3.141592653589793238462643  //pi 
    ang = rad2degree * math.atan((_src[0] - _src[_lookback]) / ta.atr(_atrPeriod)/_lookback)
    ang

f_ma(type, _src, _len) =>
    float result = 0
    if type=="SMA" // Simple
        result := ta.sma(_src, _len)
    if type=="EMA" // Exponential
        result := ta.ema(_src, _len)

    result

_ma_type = type ? "EMA" : "SMA"
_ma    = f_ma(_ma_type, src, len)
_angle = f_angle(_ma, i_lookback, i_atrPeriod)
color_H = _angle > 0 ? color.lime : _angle < 0 ? color.red : color.gray

//trend color change
colsh= _angle>0 ? #00ff00 : na
colsh2= _angle<0? #ff0000 : na

//no trend color change
colsh3= _angle==0 ? #9598a1 : na
colsh4= _angle==0 ? #9598a1 : na

//plots
// //trend line plot
plot(out, color=colsh, linewidth=3, offset=offset)
plot(out, color=colsh2, linewidth=3, offset=offset)


alertcondition(_angle>0 and _angle[1]<0, "Now Bull Color", "Now Bull Color")
alertcondition(_angle<0 and _angle[1]>0, "Now Bear Color", "Now Bear Color")
alertcondition( (_angle<0 and _angle[1]>0) or (_angle>0 and _angle[1]<0), "ANY Color Change", "ANY Color Change")

Overview

The angle is calculated using an ATR-normalized arctangent formula over a user-defined lookback period. Green indicates an upward slope, while red represents a downward slope. Traders can switch between EMA and SMA types, customize period lengths, and configure alert conditions for bullish or bearish trend directional shifts directly on the main price chart.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Draws

On the price chart

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.

Settings

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

SettingTypeDefaultVariable
Angle Periodint2i_lookback
ATR Periodint10i_atrPeriod
Angle Levelint6i_angleLevel
Lengthint21len
Sourcesourceclosesrc
Use EMA? (Off=SMA)booltruetype
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

947 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 12 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
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

NVDA Trend Ribbon

by longsurf-ai
280 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 3 days ago · MIT GitHub repository of NVDA Trend Ribbon
257 stars

Donald SPX - Options Trading is an overlay indicator designed for intraday SPX analysis. It plots a 200-period Weighted Moving Average (WMA) on the price chart while evaluating multi-timeframe market structure across Daily, 15-minute, 5-minute, and 2-minute ba

Indicator v5 Moving averagesTrend Repaints
Updated 7 weeks ago · None stated GitHub repository of Donald SPX - Options Trading
228 stars

This indicator computes moving average and RSI bias signals across the current timeframe and four higher timeframes. It sums biases from the MA and RSI to derive an overall bullish or bearish signal. The results appear in a configurable table that displays eac

Indicator v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Template

More Moving averages scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers