Kaipol
Kaipol

Reputation: 13

Wrong candle bar index in order block detection in Pine script

//@version=6
strategy("ICT Bullish Order Block", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=0.5)

length = 100  // Limit analysis to last 100 candles

// Determine candle type
isBullish = close > open
isBearish = close < open

// Step 1: Detect Bullish Displacement check for consecutive bullish
var int endDisplacement = na   // first bullish candle
var int startDisplacement = na     // last consecutive bullish candle  
var bool inDisplacement = false

for i = 0 to length by 1
    if isBullish[i]
        if na(endDisplacement)
            endDisplacement := i
        startDisplacement := i
        inDisplacement := true
    else
        if inDisplacement
            break
displacementLength = math.abs(endDisplacement - startDisplacement + 1) // number of consecutive bullish candles

// Step 2: Detect Bearish Manipulation look back to find the start of manipulation
var int startManipulation = na   // last consecutive bearish candle
var int endManipulation = na     // first bearish candle next to the Displacement
var bool inManipulation = false

if not na(endDisplacement)
    for i = startDisplacement + 1 to length - 1 by 1 // Iterate from AFTER Displacement
        if isBearish[i]
            if na(endManipulation) 
                endManipulation := i
            startManipulation := i  
            inManipulation := true
        else
            if inManipulation
                break // Stop when a bullish bar is encountered after manipulation


// plotshape(endDisplacement, location=location.abovebar, color=color.green, style=shape.triangledown)
// plotshape(startDisplacement, location=location.belowbar, color=color.green, style=shape.triangleup)   
// plotshape(endManipulation, location=location.belowbar, color=color.red, style=shape.triangleup)
// plotshape(startManipulation, location=location.abovebar, color=color.orange, style=shape.triangledown)

plot(bar_index[endDisplacement], color = color.green)
plot(bar_index[startDisplacement], color = color.green)
plot(bar_index[endManipulation], color = color.red)
plot(bar_index[startManipulation], color = color.orange)

This code check backward in history for consecutive bullish candles then consecutive bearish candles. The first and the last candles of each are endDisplcaement, startDisplacement endManipulation, startManipulation accordingly.

Then plot the candle index to check the correctness of those candles.

All marks correct candle except endManipulation should always be startDisplacement + 1 candle index by this logic. But It gives endDisplacement -1 index instead. What could be the problem?

Upvotes: 0

Views: 12

Answers (0)

Related Questions