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
Assistant
// 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
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
code
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)
Sure! Here's the converted strategy code based on your original indicator script:
pine
//@version=5
strategy("Candles Not Touching EMA 5 with Overlap and Size Check (Strategy)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// 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
// --- Trading Logic ---
// Entry conditions
long_entry_condition = (all_conditions_met_below or signal_below or distance_only_signal_below) and strategy.position_size <= 0 // Only enter long if not in long position
short_entry_condition = (all_conditions_met_above or signal_above or distance_only_signal_above) and strategy.position_size >= 0 // Only enter short if not in short position
// Stop loss levels
var float long_stop_loss_level = na
var float short_stop_loss_level = na
// Entry and Stop Loss for Long Positions
if long_entry_condition
// Calculate stop loss level
if enable_stop_loss_feature
long_stop_loss_level := low - ((atr_percent / 100.0) * daily_atr)
else
long_stop_loss_level := na
// Enter Long
strategy.entry("Long", strategy.long)
// Set Stop Loss
if enable_stop_loss_feature and not na(long_stop_loss_level)
strategy.exit("Exit Long", from_entry="Long", stop=long_stop_loss_level)
// Entry and Stop Loss for Short Positions
if short_entry_condition
// Calculate stop loss level
if enable_stop_loss_feature
short_stop_loss_level := high + ((atr_percent / 100.0) * daily_atr)
else
short_stop_loss_level := na
// Enter Short
strategy.entry("Short", strategy.short)
// Set Stop Loss
if enable_stop_loss_feature and not na(short_stop_loss_level)
strategy.exit("Exit Short", from_entry="Short", stop=short_stop_loss_level)
// Maintain Stop Loss Levels while in Position
if strategy.position_size > 0
if enable_stop_loss_feature and not na(long_stop_loss_level)
strategy.exit("Exit Long", from_entry="Long", stop=long_stop_loss_level)
else
long_stop_loss_level := na
if strategy.position_size < 0
if enable_stop_loss_feature and not na(short_stop_loss_level)
strategy.exit("Exit Short", from_entry="Short", stop=short_stop_loss_level)
else
short_stop_loss_level := na
// 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)
// Plot Stop Loss Levels
plot(long_stop_loss_level, title="Long Stop Loss Level", color=color.red, linewidth=2)
plot(short_stop_loss_level, title="Short Stop Loss Level", color=color.green, linewidth=2)
// Alert Conditions (Optional, can be kept for informational purposes)
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.")
Explanation of the Conversion:
Indicator to Strategy: Changed indicator to strategy to convert the script into a strategy that can backtest trading signals.
Entry Conditions:
Long Entry: When signal_below, distance_only_signal_below, or all_conditions_met_below is true, the strategy enters a long position.
Short Entry: When signal_above, distance_only_signal_above, or all_conditions_met_above is true, the strategy enters a short position.
Position Size Control: The strategy checks strategy.position_size to avoid entering new positions when already in one.
Stop Loss Feature:
Calculates stop loss levels based on ATR when enabled.
Uses strategy.exit to set stop loss levels for both long and short positions.
Maintains the stop loss level while in a position and resets it when the position is closed.
Plotting:
Plots the EMA 5 for reference.
Plots arrows and circles to highlight signals, maintaining the original visual indications.
Plots stop loss levels on the chart.
Alerts: Kept the original alert conditions for informational purposes; they can be removed if not needed.
How to Use the Strategy:
Add the Script to TradingView:
Copy the entire script.
Open TradingView and go to the Pine Editor.
Paste the script into the editor.
Click on the "Add to Chart" button.
Customize Inputs:
Adjust the user inputs in the settings to fit your trading preferences.
Backtesting:
The strategy will automatically backtest using historical data.
You can view the performance in the "Strategy Tester" tab.
Optimization:
Experiment with different input values to optimize the strategy's performance.
Use the "Strategy Tester" to analyze metrics like net profit, drawdown, and win rate.
Alerts and Notifications:
Set up alerts if you wish to receive notifications when signals occur.
The alerts are optional and can be configured based on the alert conditions provided.
Important Notes:
Risk Management: Always consider proper risk management practices when using trading strategies.
Historical Data: Backtesting results are based on historical data and do not guarantee future performance.
Further Customization: Feel free to modify the script to better suit your trading style or to add additional features.
Let me know if you need any further adjustments or explanations!