Pine Script: SMAs on different timeframes

Viewed 17

Assume I'm on the 4h chart. What I would like to do is to calculate a few SMAs on the daily chart and plot them in the 4h chart. For example, I would like to calculate the 100 day SMA and draw it on the 4h chart. I would also like to do this for the 200 day SMA. Etc.

I know how to do this using request.security() (see "direct variant" in the code snippet below). However, if I want to plot 5 different SMAs, this would mean that I have to call request.security() 5 times. To me, this seems inefficient. I would rather like to call request.security() once to obtain the daily data and then calculate the SMAs on that. However, this doesn't seem to work. See this snippet:

//@version=5
indicator(title="test", shorttitle="test", overlay=true)

// initialize
smaPeriod = 1400

// direct variant
twoHundreedWeekSma = ta.sma(close, smaPeriod)
dailyChart200WSmaDirect = request.security(syminfo.tickerid, "D", twoHundreedWeekSma) 

// indirect variant
dailyChartClose = request.security(syminfo.tickerid, "D", close)
dailyChart200WSmaIndirect = ta.sma(dailyChartClose, smaPeriod)

// plotting
plot(dailyChart200WSmaDirect, color = color.red) // <- this is correct
plot(dailyChart200WSmaIndirect, color = color.blue) // <- this is wrong. It is the same as if I did plot(ta.sma(close, smaPeriod), color = color.yellow)

I should not be seeing two different lines, but two lines on top of one another

The "indirect variant" appears to have no effect. I get the same results if I just calculate the desired SMA on the current 4h close values (i.e., if I just did ta.sma(close, smaPeriod)). What am I not understanding?

1 Answers

You can use tuples and combine multiple expressions for the same timeframe.

sma_50 = ta.sma(close, 50)
sma_100 = ta.sma(close, 100)
sma_200 = ta.sma(close, 200)

[sma_daily_50, sma_daily,100, sma_daily_200] = request.security(syminfo.tickerid, "D", [sma_50, sma_100, sma_200])

plot(sma_daily_50, color = color.green)
plot(sma_daily_100, color = color.yellow)
plot(sma_daily_200, color = color.red)
Related