//@version=5
strategy("Engulfing Candle Strategy with Signal-based Exit", overlay=true)
// Function to identify bullish engulfing candle
bullishEngulfing = ta.crossover(close[1], open[1]) and close > open and open <=
close[1] and close >= open[1]
// Function to identify bearish engulfing candle
bearishEngulfing = ta.crossunder(close[1], open[1]) and close < open and open >=
close[1] and close <= open[1]
// Generate long and short signals
longSignal = bullishEngulfing
shortSignal = bearishEngulfing
// Plot long and short signals on the chart
plotshape(longSignal, style=shape.labelup, color=color.green, text="Long",
location=location.belowbar, size=size.small)
plotshape(shortSignal, style=shape.labeldown, color=color.red, text="Short",
location=location.abovebar, size=size.small)
// Strategy entries and exits
if (longSignal)
// Close short position if open, then enter long
if (strategy.position_size < 0)
strategy.close("Short")
strategy.entry("Long", strategy.long)
if (shortSignal)
// Close long position if open, then enter short
if (strategy.position_size > 0)
strategy.close("Long")
strategy.entry("Short", strategy.short)