Search code examples
pine-scriptpine-script-v5

Only show 4hr fractals no matter the timeframe


I would like to show 4hr fractals on the 15 min timeframe. The following code will only show the fractals when I am actually on the 4hr but not on the 15 min as I hoped. I am using the request.security() but probably incorrectly. Not sure the right solution

//@version=5
indicator("4h fractals on 15m", overlay = true)

ticker = syminfo.tickerid

fourHourHigh = request.security(ticker, "240", high)
fourHourLow = request.security(ticker, "240", low)

filteredtopf = fourHourHigh[4] < fourHourHigh[2] and fourHourHigh[3] <= fourHourHigh[2] and fourHourHigh[2] >= fourHourHigh[1] and fourHourHigh[2] > fourHourHigh[0]
filteredbotf = fourHourLow[4] > fourHourLow[2] and fourHourLow[3] >= fourHourLow[2] and fourHourLow[2] <= fourHourLow[1] and fourHourLow[2] < fourHourLow[0]

plotshape(filteredtopf, title='Filtered Top Fractals', style=shape.triangledown, location=location.abovebar, color=color.new(color.green, 0), offset=-2)
plotshape(filteredbotf, title='Filtered Bottom Fractals', style=shape.triangleup, location=location.belowbar, color=color.new(color.red, 0), offset=-2)

Solution

  • The value of fourHourHigh will change when it is a new bar on the higher timeframe. Otherwise it will keep its value. So, if you are on the 15-min timeframe and requesting data from the 4h timeframe, its value will change every 15 bars.

    fourHourHigh[4] will NOT refer to fourHourHigh[4] on the higher timeframe. It will refer to fourHourHigh[4] on your chart's timeframe. And that value will change every 15 bars as I said.

    What you need to do is, together with the high, you should also request the value of high[1], high[2] etc. from the higher timeframe and use them in your calculations.

    [fourHourHigh, fourHourHigh_1, fourHourHigh_2, fourHourHigh_3, fourHourHigh_4] = request.security(ticker, "240", [high, high[1], high[2], high[3], high[4]])
    
    filteredtopf = fourHourHigh_4 < fourHourHigh_2 and fourHourHigh_3 <= fourHourHigh_2 and fourHourHigh_2 >= fourHourHigh_1 and fourHourHigh_2 > fourHourHigh