Convert to Strategy: //@version=5
indicator("Candles Not Touching EMA 5 with Overlap and Size Check (Updated)", overlay=true)

// User Inputs
enable_last_n_check = input.bool(true, title="Require last N candles to have touched EMA?")
N_candles_touched_ema = input.int(3, minval=1, title="Number of candles to check")
enable_stop_loss_feature = input.bool(true, title="Enable Stop Loss Levels")
atr_percent = input.float(2.0, title="ATR Percentage for Stop Loss (%)", minval=0, step=0.1)

// Overlap Method Inputs
enable_overlap_check = input.bool(true, title="Require N% of Current Candle to Overlap with Last Candle?")
overlap_percentage_required = input.float(50.0, minval=0.0, maxval=100.0, title="Required Overlap Percentage (%)")

// Candle Size Inputs
enable_percentage_check = input.bool(true, title="Require candle to be N% smaller than last candle?")
percentage_smaller_required = input.float(20.0, minval=0.01, title="Percentage smaller (%)")

// Distance from EMA Check Inputs
enable_distance_check = input.bool(false, title="Enable Distance from EMA Check?")
distance_atr_percent = input.float(2.0, minval=0.0, step=0.1, title="ATR Percentage for Distance from EMA (%)")

// Inputs to Ignore Checks when Distance Condition is Met (for blue circle only)
ignore_last_n_check = input.bool(false, title="Ignore Last N Candles Touching EMA Check when Distance Condition is Met?")
ignore_overlap_check = input.bool(false, title="Ignore Overlap Check when Distance Condition is Met?")
ignore_percentage_check = input.bool(false, title="Ignore Size Percentage Check when Distance Condition is Met?")

// Calculate EMA 5
ema5 = ta.ema(close, 5)

// Identify candles that do not touch EMA 5
candle_not_touching_ema = (low > ema5) or (high < ema5)

// Identify candles that touch EMA 5
candle_touching_ema = not candle_not_touching_ema

// Function to check if all of the last N candles touched the EMA
did_last_N_candles_touch_ema(N) =>
    result = true
    for i = 1 to N
        result := result and candle_touching_ema[i]
    result

// Conditions for last N candles touching EMA
last_N_candles_touched_ema_condition = true
if enable_last_n_check
    last_N_candles_touched_ema_condition := did_last_N_candles_touch_ema(N_candles_touched_ema)

// Overlap Method Logic
current_candle_overlaps_previous_by_N_percent_condition = true
if enable_overlap_check
    // Calculate current candle's range
    current_candle_range = high - low
    // Avoid division by zero
    if current_candle_range != 0
        // Calculate overlap between current candle and previous candle
        overlap_high = math.min(high, high[1])
        overlap_low = math.max(low, low[1])
        overlap_range = overlap_high - overlap_low
        // If overlap_range is negative or zero, set condition to false
        if overlap_range <= 0
            current_candle_overlaps_previous_by_N_percent_condition := false
        else
            // Calculate percentage of current candle's range that overlaps with previous candle's range
            percentage_of_current_overlapping = (overlap_range / current_candle_range) * 100.0
            // Check if percentage is greater than or equal to required percentage
            current_candle_overlaps_previous_by_N_percent_condition := percentage_of_current_overlapping >= overlap_percentage_required
    else
        // If current candle range is zero, set condition to false
        current_candle_overlaps_previous_by_N_percent_condition := false

// Candle Size Logic
current_candle_is_N_percent_smaller_condition = true
if enable_percentage_check
    // Calculate candle sizes
    prev_candle_size = high[1] - low[1]
    current_candle_size = high - low
    // Avoid division by zero
    if prev_candle_size != 0
        // Calculate size difference percentage
        size_difference_percent = ((prev_candle_size - current_candle_size) / prev_candle_size) * 100.0
        // Check if current candle is N% smaller than previous candle
        current_candle_is_N_percent_smaller_condition := size_difference_percent >= percentage_smaller_required
    else
        // If previous candle size is zero, set condition to false
        current_candle_is_N_percent_smaller_condition := false

// Distance from EMA Condition
// Calculate Daily ATR
daily_atr = request.security(syminfo.tickerid, 'D', ta.atr(14))

// Calculate ATR offset based on user-defined percentage
atr_offset = (distance_atr_percent / 100.0) * daily_atr

// Initialize Distance Condition
distance_from_ema_condition_met = false
distance_from_ema = 0.0

if enable_distance_check and candle_not_touching_ema
    if close > ema5
        distance_from_ema := low - ema5
    else if close < ema5
        distance_from_ema := ema5 - high
    else
        distance_from_ema := 0

    if distance_from_ema >= atr_offset
        distance_from_ema_condition_met := true

// -- Define conditions for ORANGE CIRCLE (All conditions met, not affected by ignore options)
// This signal represents candles where ALL conditions are met, including Distance from EMA
all_conditions_met_above = candle_not_touching_ema and close > ema5 and last_N_candles_touched_ema_condition and current_candle_overlaps_previous_by_N_percent_condition and current_candle_is_N_percent_smaller_condition and distance_from_ema_condition_met
all_conditions_met_below = candle_not_touching_ema and close < ema5 and last_N_candles_touched_ema_condition and current_candle_overlaps_previous_by_N_percent_condition and current_candle_is_N_percent_smaller_condition and distance_from_ema_condition_met

// -- Define conditions for BLUE CIRCLE (Distance condition met, other conditions adjusted based on ignore options)
// Adjusted conditions based on ignore options
adj_last_N_candles_touched_ema_condition = true
if enable_last_n_check and not ignore_last_n_check
    adj_last_N_candles_touched_ema_condition := last_N_candles_touched_ema_condition

adj_current_candle_overlaps_previous_by_N_percent_condition = true
if enable_overlap_check and not ignore_overlap_check
    adj_current_candle_overlaps_previous_by_N_percent_condition := current_candle_overlaps_previous_by_N_percent_condition

adj_current_candle_is_N_percent_smaller_condition = true
if enable_percentage_check and not ignore_percentage_check
    adj_current_candle_is_N_percent_smaller_condition := current_candle_is_N_percent_smaller_condition

distance_only_signal_above = candle_not_touching_ema and close > ema5 and adj_last_N_candles_touched_ema_condition and adj_current_candle_overlaps_previous_by_N_percent_condition and adj_current_candle_is_N_percent_smaller_condition and distance_from_ema_condition_met
distance_only_signal_below = candle_not_touching_ema and close < ema5 and adj_last_N_candles_touched_ema_condition and adj_current_candle_overlaps_previous_by_N_percent_condition and adj_current_candle_is_N_percent_smaller_condition and distance_from_ema_condition_met

// Exclude cases where all conditions are met (to prevent overlap with orange circle)
distance_only_signal_above := distance_only_signal_above and not all_conditions_met_above
distance_only_signal_below := distance_only_signal_below and not all_conditions_met_below

// -- Signals for GREEN/RED ARROWS (original signals without Distance from EMA condition)
signal_above = candle_not_touching_ema and close > ema5 and last_N_candles_touched_ema_condition and current_candle_overlaps_previous_by_N_percent_condition and current_candle_is_N_percent_smaller_condition
signal_below = candle_not_touching_ema and close < ema5 and last_N_candles_touched_ema_condition and current_candle_overlaps_previous_by_N_percent_condition and current_candle_is_N_percent_smaller_condition

// Combine all signals into signal_any
signal_any = signal_above or signal_below or distance_only_signal_above or distance_only_signal_below or all_conditions_met_above or all_conditions_met_below

// Plot EMA 5 for reference
plot(ema5, color=color.orange, linewidth=2, title="EMA 5")

// Plot arrows to highlight signals
// Arrow Down for candles entirely above EMA 5 (excluding cases where all conditions are met)
plotshape(signal_above and not all_conditions_met_above, title="Above EMA Signal", style=shape.arrowdown, location=location.abovebar, color=color.green, size=size.tiny)
// Arrow Up for candles entirely below EMA 5 (excluding cases where all conditions are met)
plotshape(signal_below and not all_conditions_met_below, title="Below EMA Signal", style=shape.arrowup, location=location.belowbar, color=color.red, size=size.tiny)

// Plot small blue circle to highlight candles where Distance Condition is met (adjusted conditions, ignoring selected checks)
plotshape(distance_only_signal_above, title="Distance Condition Met Above EMA (Adjusted Conditions)", style=shape.circle, location=location.abovebar, color=color.blue, size=size.tiny)
plotshape(distance_only_signal_below, title="Distance Condition Met Below EMA (Adjusted Conditions)", style=shape.circle, location=location.belowbar, color=color.blue, size=size.tiny)

// Plot small orange circle to highlight candles where Distance Condition and all other conditions are met
plotshape(all_conditions_met_above, title="All Conditions Met Above EMA", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny)
plotshape(all_conditions_met_below, title="All Conditions Met Below EMA", style=shape.circle, location=location.belowbar, color=color.orange, size=size.tiny)

// Alert Conditions
alertcondition(signal_any, title="Any Signal Alert", message="A signal has been triggered: 'Above EMA', 'Below EMA', 'Distance Condition Met', or 'All Conditions Met'.")
alertcondition(signal_above and not all_conditions_met_above, title="Above EMA Alert", message="Candle entirely above EMA 5, not touching it. Signal conditions met.")
alertcondition(signal_below and not all_conditions_met_below, title="Below EMA Alert", message="Candle entirely below EMA 5, not touching it. Signal conditions met.")
alertcondition(distance_only_signal_above or distance_only_signal_below, title="Distance Condition Met Alert", message="Candle met the Distance from EMA Condition with adjusted conditions.")
alertcondition(all_conditions_met_above or all_conditions_met_below, title="All Conditions Met Alert", message="Candle met ALL conditions including Distance from EMA.")

// --- Updated Stop Loss Feature ---

// Initialize variables for stop loss levels
float stop_loss_level = na
color stop_loss_color = na

// Compute and plot stop loss levels when the feature is enabled
if enable_stop_loss_feature
    if all_conditions_met_above or signal_above or distance_only_signal_above
        stop_loss_level := high + ((atr_percent / 100.0) * daily_atr)
        stop_loss_color := color.red
    else if all_conditions_met_below or signal_below or distance_only_signal_below
        stop_loss_level := low - ((atr_percent / 100.0) * daily_atr)
        stop_loss_color := color.green
    else
        stop_loss_level := na
        stop_loss_color := na

// Plot stop loss level
plot(stop_loss_level, title="Stop Loss Level", color=stop_loss_color, linewidth=2)