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

//@version=5
indicator("Volatility Compression Breakout", overlay=true)

// Volatility Compression Parameters
compressionPeriod = input(20, "Compression Period")
compressionMultiplier = input(1.5, "Compression Multiplier")

// Trend Filter Parameters
emaPeriod = input(50, "EMA Period")

// Calculate ATR and Keltner Channels
atr = ta.atr(14)
keltnerMiddle = ta.sma(close, compressionPeriod)
keltnerUpper = keltnerMiddle + (compressionMultiplier * atr)
keltnerLower = keltnerMiddle - (compressionMultiplier * atr)

// Calculate Standard Deviation
stdDev = ta.stdev(close, compressionPeriod)

// Calculate Trend Filter
ema = ta.ema(close, emaPeriod)

// Determine Breakout Conditions
breakoutUp = high > keltnerUpper + stdDev and close > ema and close[1] <= ema[1]
breakoutDown = low < keltnerLower - stdDev and close < ema and close[1] >= ema[1]

// Plot Breakout Shapes
plotshape(breakoutUp, "Long Entry", shape.triangleup, location.belowbar, color=color.green, size=size.large)
plotshape(breakoutDown, "Short Entry", shape.triangledown, location.abovebar, color=color.red, size=size.large)

// Color
kcColor = close > keltnerMiddle ? color.lime : color.fuchsia
emaColor = close > ema ? color.lime : color.fuchsia
barC = close > ema and close > keltnerMiddle ? color.lime : close > keltnerMiddle and close < ema ? color.yellow : close < keltnerMiddle and close > ema ? color.yellow : color.fuchsia

barcolor(barC)

// Plot Keltner Channels
plot(keltnerUpper, color=color.aqua, linewidth=2, title="Keltner Upper")
plot(keltnerLower, color=color.aqua, linewidth=2, title="Keltner Lower")
plot(keltnerMiddle, color=kcColor, linewidth=4, title="Keltner Middle")
plot(keltnerUpper + stdDev, color=color.aqua, linewidth=2, title="Keltner Upper StdDev")
plot(keltnerLower - stdDev, color=color.aqua, linewidth=2, title="Keltner Lower StdDev")

// Plot Trend Filter
plot(ema, color=emaColor, linewidth=4, title="Trend Filter")