Multiple Timeframe Moving Averages

Multi-timeframe indicators: this lesson demonstrates how to display 4 moving averages from 4 different timeframes without repainting in Pine Script.

Check out my other free lessons!

Source Code

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// @version=5
indicator("www.PineScriptMastery.com", "EMA", overlay=true)

// Get user inputs
i_EMA   = input.int(30, "EMA Length")
i_TF1   = input.timeframe("5",   "Timeframe #1")
i_TF2   = input.timeframe("30",  "Timeframe #2")
i_TF3   = input.timeframe("60",  "Timeframe #3")
i_TF4   = input.timeframe("240", "Timeframe #4")

// Non-repainting security function
RequestSecurityNRP(_tf, _exp, _barmerge) =>
    request.security(syminfo.tickerid, _tf, _exp[barstate.isrealtime ? 1 : 0], _barmerge)[barstate.isrealtime ? 0 : 1]

// Get EMA expression
EMA_Value = ta.ema(close, i_EMA)

// Get EMAs on timeframes
EMA_TF1 = RequestSecurityNRP(i_TF1, EMA_Value, barmerge.gaps_on)
EMA_TF2 = RequestSecurityNRP(i_TF2, EMA_Value, barmerge.gaps_on)
EMA_TF3 = RequestSecurityNRP(i_TF3, EMA_Value, barmerge.gaps_on)
EMA_TF4 = RequestSecurityNRP(i_TF4, EMA_Value, barmerge.gaps_on)

// Draw EMAs
plot(EMA_TF1, "TF1", color.rgb(255, 0, 0, 0), linewidth=2)
plot(EMA_TF2, "TF2", color.rgb(220, 0, 0, 0), linewidth=2)
plot(EMA_TF3, "TF3", color.rgb(200, 0, 0, 0), linewidth=2)
plot(EMA_TF4, "TF4", color.rgb(180, 0, 0, 0), linewidth=2)