'Moving Average Lengths that Change Depending on Timeframe
I'd like to modify Tradingview's moving average ribbon indicator to automatically switch between different moving averages depending on the timeframe. For low timeframes <= 5m I like to use 60, 120 and 180-period moving averages which equates to 1, 2, 3 hours in the case of the 1m timeframe, while for higher timeframes I like to use 50, 100 and 200-period moving averages as they are the most followed averages by other traders.
In the code below I'd like to automate the indicator to plot ma3Scalp (60 period) when using a timeframe 5 minutes or under and switch to ma3Swing (50 period) when using all higher timeframes. I've tried using timeframe.multiplier and timeframe.period but with no luck. Basically I want "if (timeframe <=5m) plot Scalp, else plot Swing.
show_ma3 = input(true , "MA №3", inline="MA #3")
ma3_type = input.string("EMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma3_source = input(close , "" , inline="MA #3")
ma3Scalp_length = input.int(60 , "Scalp" , minval=1)
ma3Swing_length = input.int(50 , "Swing" , minval=1)
ma3_color = input(color.new(#4caf50, 40), "" , inline="MA #3")
ma3Scalp = ma(ma3_source, ma3Scalp_length, ma3_type)
ma3Swing = ma(ma3_source, ma3Swing_length, ma3_type)
plot(show_ma3 ? ma3Scalp : na, color = ma3_color, title="MA №3")
plot(show_ma3 ? ma3Swing : na, color = ma3_color, title="MA №3")
Solution 1:[1]
Here is an example for you so you can use multiple conditions and timeframes in your code.
The idea is converting chart's timeframe into minutes and using that to set your length.
//@version=5
indicator("My Script", overlay=true)
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
f_getLen(t) =>
l = 0
if (t >= 120) // 2h and above
l := 100
else if (t >= 60) // 1h and above
l := 50
else if (t >= 15) // 15min and above
l := 25
else
l := 5
t_in_min = f_resInMinutes()
len = f_getLen(t_in_min)
_ema = ta.ema(close, len)
plot(_ema, color=color.yellow)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vitruvius |
