Filter Those Candles also that Below EMA and does not EMA Line from N Candles: //@version=5
indicator("EMA5 Break Strategy with Corrected Previous Candles Condition", overlay=true)

// Parameters
ema_length = input.int(5, minval=1, title="EMA Length")
atr_length = input.int(14, minval=1, title="ATR Length")

// Risk-Reward Ratio Input
risk_reward_ratio = input.float(2.5, minval=0.1, step=0.1, title="Risk-Reward Ratio")

// Time Filter Settings
use_time_filter = input.bool(true, title="Use Time Filter?")

session1 = input.session("0930-1600", "Session 1 Time", group="Time Filter Settings")
session2 = input.session("2000-2300", "Session 2 Time", group="Time Filter Settings")
timezone = "America/New_York"

// New Feature Inputs
use_preceding_candles_condition = input.bool(true, title="Require All Previous Candles Touch EMA?")
preceding_candles_count = input.int(5, minval=1, title="Number of Previous Candles (N)", group="Additional Conditions")

// Compute EMA
ema5 = ta.ema(close, ema_length)

// Compute Daily ATR
daily_atr = request.security(syminfo.tickerid, 'D', ta.atr(atr_length))

// Time filter logic
var bool is_in_time = true

if use_time_filter
    is_in_session1 = not na(time(timeframe.period, session1, timezone))
    is_in_session2 = not na(time(timeframe.period, session2, timezone))
    is_in_time := is_in_session1 or is_in_session2
else
    is_in_time := true

// Conditions
// First candle not touching EMA: Previous candle's low is above EMA, and the candle before that touches or crosses EMA
first_candle_not_touching_ema = low[1] > ema5[1] and low[2] <= ema5[2]

// Price is above EMA (on the previous candle)
price_above_ema = close[1] > ema5[1]

// Current candle breaks the low of the previous candle (the first candle not touching EMA)
breaks_prev_low = low < low[1]

// New Condition: All of the previous N candles must have touched the EMA (their lows are at or below EMA)
all_previous_candles_touched_ema = true

if use_preceding_candles_condition
    for i = 2 to preceding_candles_count + 1 by 1
        if low[i] > ema5[i]
            all_previous_candles_touched_ema := false
            break  // Exit loop early if any candle does not meet the condition
else
    all_previous_candles_touched_ema := true  // Condition passes if feature is disabled

// Signal when all conditions are met
signal = first_candle_not_touching_ema and price_above_ema and breaks_prev_low and is_in_time and all_previous_candles_touched_ema

// Entry, Stop Loss, and Take Profit Prices
entry_price = low[1]
stop_loss_price = high[1] + (daily_atr * 0.02)
risk = stop_loss_price - entry_price
take_profit_price = entry_price - (risk * risk_reward_ratio)

// Variables to track trade status
var bool in_trade = false
var bool trade_won = false
var float trade_entry_price = na
var float trade_stop_loss = na
var float trade_take_profit = na
var int trade_entry_bar = na
var int trade_exit_bar = na
var bool trade_closed_on_this_bar = false

if signal and not in_trade
    in_trade := true
    trade_won := false
    trade_entry_price := entry_price
    trade_stop_loss := stop_loss_price
    trade_take_profit := take_profit_price
    trade_entry_bar := bar_index
    trade_exit_bar := na
    trade_closed_on_this_bar := false

if in_trade
    // Check if the trade is exited on this bar
    if high >= trade_stop_loss and low <= trade_take_profit
        // Both levels were hit in the same bar; assume stop loss hit first for conservative approach
        trade_won := false
        in_trade := false
        trade_exit_bar := bar_index
        trade_closed_on_this_bar := true
    else if high >= trade_stop_loss
        // Stop loss was hit
        trade_won := false
        in_trade := false
        trade_exit_bar := bar_index
        trade_closed_on_this_bar := true
    else if low <= trade_take_profit
        // Take profit was hit
        trade_won := true
        in_trade := false
        trade_exit_bar := bar_index
        trade_closed_on_this_bar := true
    // Optional: Exit trade after a maximum number of bars
    else if bar_index - trade_entry_bar >= 100
        in_trade := false
        trade_won := false
        trade_exit_bar := bar_index
        trade_closed_on_this_bar := true
    else
        trade_closed_on_this_bar := false
else
    trade_closed_on_this_bar := false

// Plot EMA
plot(ema5, color=color.blue, linewidth=2)

// Plot signals
plotshape(signal, title="Short Entry", location=location.abovebar, color=color.red, size=size.small, style=shape.triangledown, text="Short", textcolor=color.white)

// Plot stop loss and take profit lines on the chart when trade is active
plot(in_trade or trade_closed_on_this_bar ? trade_stop_loss : na, title="Stop Loss", color=color.red, linewidth=1, style=plot.style_linebr)
plot(in_trade or trade_closed_on_this_bar ? trade_take_profit : na, title="Take Profit", color=color.green, linewidth=1, style=plot.style_linebr)

// Plot trade outcome marker
if trade_closed_on_this_bar
    if trade_won
        label.new(bar_index, low, text="Win", style=label.style_label_up, color=color.green, textcolor=color.white, size=size.tiny)
    else
        label.new(bar_index, high, text="Loss", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)