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

//@version=5
indicator("Encapsulation Box", shorttitle = "Encapsulation Box", overlay = true)

// Input for the number of horizontal candles in the box and box lines color
boxWidth        = input.int     (5, title="Box Width", minval=1)
boxLineColor    = input.color   (color.rgb(220, 220, 8), title="Box Line Color")
boxLColor       = input.color   (color.rgb(181, 220, 8, 74), title="Box  Color")
line            = input.color   (color.rgb(237, 241, 4), title="Line Color")
lineWidth       = input.int     (2, title="Box Width", minval=1)
boxLine         = input.int     (1, title="Box Line", minval=1)


// Calculate rectangle coordinates
var float rectTop = na
var float rectBottom = na
var float rectLeft = na
var float rectRight = na
var float rectLine = na

// Update rectangle coordinates only when new max/min is reached
newHigh = high >= ta.highest(high, boxWidth)
newLow = low <= ta.lowest(low, boxWidth)
if newHigh or newLow
    rectTop := high
    rectBottom := low
    rectLeft := float(bar_index)
    rectRight := float(bar_index) + float(boxWidth)
    rectLine := rectRight + 20

// Initialize buy and sell signals
var bool buySignal = na
var bool sellSignal = na

// Draw rectangle lines 
if bar_index >= 3
   
    if high <= high[4] and high <= high[3] and high <= high[2] and high <= high[1] and high and  high[4] >= high[3]  and low[4] <= low and low[3] <= low[2] and low[3] <= low and low[4] <= low [3]
        // Draw the box using box.new for both border and fill
        box.new(left=int(rectLeft), right=int(rectRight), top=rectTop, bottom=rectBottom, border_width=boxLine, border_color=boxLineColor, bgcolor=boxLColor)

        // Calculate midpoint of the box
        midpointPrice = (rectTop + rectBottom) / 2
        line.new(x1=int(rectLeft), y1=midpointPrice, x2=int(rectLine), y2=midpointPrice, width=lineWidth, color=line)

        // Define the alert
        alert("Encapsulation Box: New box formed at bar " + str.tostring(bar_index))
