'Plot box on candle sticks patterns until price breaks the box

I'm developing an indicator that plots a box on engalfing candles in pine script. the problem I'm facing is that the box is drawn until a new engalfing is detected. If it's a bullish engalfing I would like for the box to extend to the right until price breaks the low of the bullish engalfing and with a bearish engalfing the line should extend until price breaks the high of the bearish engalfing. I have tried the following but it's not working as I would like it to.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mudau

//@version=5
indicator("Bullish & Bearish Engulfing", overlay=true)
// Make sure the shadow is bigger than previous candle
engulfShadow = high > high[1] and low < low[1]
// Check the Bullish Engulfing
bullEngulf = open[1] > close[1] and open < close and close >= open[1] and open <= close[1] and engulfShadow
// Check the Bearish Engulfing
bearEngulf = open[1] < close[1] and open > close and close <= open[1] and open >= close[1] and engulfShadow
// Plot the 'triangle'
plotshape(bullEngulf, title="Bullish Engulf", location=location.belowbar, transp=0, style=shape.triangleup, size=size.auto, color=color.blue)
plotshape(bearEngulf, title="Bearish Engulf", location=location.abovebar, transp=0, style=shape.triangledown, size=size.auto, color=color.red)

// Initialize variables on bar zero only, so they preserve their values across bars.
var hi = float(na)
var lo = float(na)
var line hiLine = na
var line loLine = na
var box hiLoBox = na

if bearEngulf
    // New bar; reset values and create new lines and box.
    hi := high[1] >= high ? high[1] : high
    lo := low[1]
    hiLoBox := box.new(bar_index - 1, hi, bar_index, lo, border_color = na, bgcolor = color.silver)
    int(na)
else if bullEngulf
    // New bar; reset values and create new lines and box.
    hi := high[1]
    lo := low[1] <= low ? low[1] : low
    hiLoBox := box.new(bar_index - 1, hi, bar_index, lo, border_color = na, bgcolor = color.silver)
    int(na)
else
    // On other bars, extend the right coordinate of the box.
    box.set_right(hiLoBox, bar_index)
    // Change the color of the box's background depending on whether high/low is higher/lower than the box.
    boxColor = high > hi ? color.silver : low < lo ? color.silver : color.silver
    box.set_bgcolor(hiLoBox, color.new(boxColor, 50))
    int(na)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source