Search code examples
pine-scripttrading

How to get a previous value of a serie (SMA) regardless of the timeframe selected?


I'm trying to do the following :

  • generate 4 SMA (SMA7 / 20 / 50 / 100) on a MTF (multi-timeframe) : for example for the hourly and daily timeframes

[S1, S7, S13, S19] = request.security(syminfo.tickerid, "60", [ma7, ma20, ma50, ma100], lookahead=barmerge.lookahead_on)

[S2, S8, S14, S20] = request.security(syminfo.tickerid, "D", [ma7, ma20, ma50, ma100], lookahead=barmerge.lookahead_on)

--> I checked that the values are ok by setting them on a table : it seems to work correctly, and even if I change the timeframe on Tradingview the values are stills (so it should be regarding I fixes the timeframe on each serie).

  • comparing the current value of the SMA with one in the past (5 periods in the example below), so I can determine if its increasing or decreasing, for example below by setting in a variable the result :

sma7direction = if S1[0] > S1[5] "Up" else "Down"

It works but only when I'm on the same timeframe as the serie, so in my example if I'm on the hourly timeframe. Once I set TradingView on another timeframe, I get an incorrect value on S1[5] so I think the behavior is that the 5 periods in the past are not on the hourly timeframe but in the one I've selected on Tdw ...

How can I get 5 periods in the past with a fix timeframe ?

Thanks in advance for any help you can provide :)


Solution

    1. As a general rule, do NOT use lookahead with request.security() as you are then introducing future leak in your scripts. See here for more information.
    2. The reason it's not working when the chart's TF is not the same as that of the request.security() call is because you are referring to previous values of the HTF when reported at the chart's TF, so they will be the same value on all chart bars until the HTF changes­.
    3. If you want to refer to past values in the HTF's context, you need to evaluate them inside your request.security() call, so you could use:
    [S1, S7, S13, S19, S1Rising] = request.security(syminfo.tickerid, "60", [ma7, ma20, ma50, ma100, ma7 > ma7[5])