Search code examples
pine-scripttradingtradingview-apiindicator

Want to restrict a part of my indicator to certain timeframes than other parts


I was just making a combination of indicators i use - vwap, 50ema and imbalance.

I want it to show vwap only on 5minutes and below timeframes, whereas Ema on 15minutes and above.

Thanks in advance 👍🏼


Solution

  • You can do it in two ways, first one is to check if the timeframe is intraday and multiplier is 5 or less, like this:

    vwap = ta.vwap(close)
    ema_50 = ta.ema(close, 50)
    
    plot(timeframe.isintraday and timeframe.multiplier <= 5 ? vwap: na, 
    color=color.red)
    plot(timeframe.isintraday and timeframe.multiplier <= 5 ? na: ema_50, 
    color=color.yellow)
    

    Second way is to specify an array of timeframes, here you have more flexibility

    display_vwap_timeframe = array.new_string(3)
    array.push(display_vwap_timeframe, "1")
    array.push(display_vwap_timeframe, "3")
    array.push(display_vwap_timeframe, "5")
    
    
    plot(array.includes(display_vwap_timeframe, timeframe.period) ? vwap: na, color=color.red)
    plot(array.includes(display_vwap_timeframe, timeframe.period) ? na: ema_50, color=color.yellow)
    

    eventually you could even use two arrays of timeframes for vwap and ema 50, in this case you can just use an "if" clause (because when you show the vwap you don't want the ema 50)

    EDIT

    Code with the changing color as requested:

    vwap = ta.vwap(close)
    ema_50 = ta.ema(close, 50)
    
    vwap_color = vwap > vwap[1] ? color.green : color.red
    ema_color = ema_50 > ema_50[1] ? color.green : color.red
    
    plot(timeframe.isintraday and timeframe.multiplier <= 5 ? vwap: na, color=vwap_color)
    plot(timeframe.isintraday and timeframe.multiplier <= 5 ? na: ema_50, color=ema_color)