// Take Profit and Stop Loss Inputs
tp1_perc = input.float(defval=1.5, title="Take Profit 1 (%)", minval=0.0, step=0.1, group="Trade Settings")
tp2_perc = input.float(defval=3.0, title="Take Profit 2 (%)", minval=0.0, step=0.1, group="Trade Settings")
sl_perc = input.float(defval=5.0, title="Stop Loss (%)", minval=0.0, step=0.1, group="Trade Settings")
// Take Profit Percentages for Position Size
tp1_qty_perc = input.float(defval=25.0, title="TP1 Close Position (%)", minval=0.0, maxval=100.0, step=1.0, group="Trade Settings")
tp2_qty_perc = 100.0 - tp1_qty_perc // Automatically set TP2 to close the remaining position
// Initialize variables
var float alpha1 = na
var float HP = 0.0
var float a1 = na
var float b1 = na
var float c1 = na
var float c2 = na
var float c3 = na
var float Filt = 0.0
var float Peak = 0.0
var float X = na
var float Quotient1 = na
var float Quotient2 = na
pi = 2 * math.asin(1)
// EOT 2 Calculations
var float alpha1222 = na
var float HP2 = 0.0
var float a12 = na
var float b12 = na
var float c12 = na
var float c22_var = na
var float c32 = na
var float Filt2 = 0.0
var float Peak2 = 0.0
var float X2 = na
var float Quotient3 = na
var float Quotient4 = na
// EOT 3 Calculations
var float alpha1333 = na
var float HP3 = 0.0
var float a13 = na
var float b13 = na
var float c13 = na
var float c33_var = na
var float c333 = na
var float Filt3 = 0.0
var float Peak3 = 0.0
var float X3 = na
var float Quotient5 = na
var float Quotient6 = na
// Optional: Plot EMAs (Uncomment if you set overlay=true in strategy)
plot(ema1, color=color.blue, title="EMA 1")
plot(ema2, color=color.orange, title="EMA 2")
// ===============================================
// Entry and Exit Conditions
sma200 = ta.sma(close, 200)
line1 = -0.9
over = ta.cross(Quotient5, Quotient6) and (Quotient5 > 0.5)
over3 = ta.cross(Quotient3, Quotient4) and (Quotient3 > 0)
crossover_trigger = ta.crossover(q1, trigger)
crossunder_trigger = ta.crossunder(q1, trigger)
// ======== New Exit Conditions Based on EMA Cross ========
// Use crossover and crossunder functions for precise event detection
exit_long = ta.crossunder(ema1, ema2) // Exit long when EMA1 crosses below EMA2
exit_short = ta.crossover(ema1, ema2) // Exit short when EMA1 crosses above EMA2
// ==========================================================
// Additional Conditions
warn = ta.crossover(Quotient3, -0.9)
warn2 = ta.crossover(Quotient1, -0.9)
warn3 = ta.crossunder(Quotient1, 0.9)
enter3 = (Quotient3 <= -0.9) and crossover_trigger and (ta.barssince(warn2) <= 7) and (q1 <= 20) and (ta.barssince(ta.crossover(q1, 20)) <= 21)
enter5 = (ta.barssince((q1 <= 0) and crossunder_trigger) <= 5) and crossover_trigger
enter6 = (ta.barssince((q1 <= 20) and crossunder_trigger) <= 11) and crossover_trigger
enter7 = (Quotient3 <= -0.9) and crossover_trigger
// Short Conditions
senter3 = (Quotient3 >= -0.9) and crossunder_trigger and (ta.barssince(warn3) <= 7) and (q1 >= 99) and (ta.barssince(ta.crossover(q1, 80)) <= 21)
// Initialize SL Line Variables
var line longSLLine = na
var line shortSLLine = na
// Variables to track entry bars
var int long_entry_bar = na
var int short_entry_bar = na
// Trade Execution Logic
if inDateRange
// Long Entry Conditions
longCondition = showlongs and ((enter6 and (q1 <= 60)) or enter7 or enter5 or enter3)
if longCondition and strategy.position_size <= 0
if strategy.position_size < 0
strategy.close(id="Short Entry", comment="Close Short")
strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
if showentry
label.new(bar_index, low, "Buy", style=label.style_label_up, color=color.new(color.green, 0), textcolor=color.white, size=size.tiny)
// Record the entry bar for long position
long_entry_bar := bar_index
short_entry_bar := na // Reset short entry bar
// Calculate Take Profit and Stop Loss Prices
tp1_price = close * (1 + tp1_perc / 100)
sl_price = close * (1 - sl_perc / 100)
// Set Take Profit and Stop Loss Orders
strategy.exit(id="TP1", from_entry="Long Entry", qty_percent=tp1_qty_perc, limit=tp1_price, stop=sl_price, comment="Take Profit 1")
// Draw Stop Loss Line for Long Position
if not na(longSLLine)
line.delete(longSLLine)
longSLLine := line.new(x1=bar_index, y1=sl_price, x2=bar_index + 1, y2=sl_price, color=color.red, width=1, extend=extend.right, style=line.style_dashed)
// Short Entry Conditions
shortCondition = showshorts and senter3
if shortCondition and strategy.position_size >= 0
if strategy.position_size > 0
strategy.close(id="Long Entry", comment="Close Long")
strategy.entry(id="Short Entry", direction=strategy.short, comment="Short Entry")
if showentry
label.new(bar_index, high, "Sell", style=label.style_label_down, color=color.new(color.red, 0), textcolor=color.white, size=size.tiny)
// Record the entry bar for short position
short_entry_bar := bar_index
long_entry_bar := na // Reset long entry bar
// Calculate Take Profit and Stop Loss Prices for Short Position
tp1_price = close * (1 - tp1_perc / 100)
sl_price = close * (1 + sl_perc / 100)
// Set Take Profit and Stop Loss Orders
strategy.exit(id="TP1_Short", from_entry="Short Entry", qty_percent=tp1_qty_perc, limit=tp1_price, stop=sl_price, comment="Take Profit 1 Short")
// Draw Stop Loss Line for Short Position
if not na(shortSLLine)
line.delete(shortSLLine)
shortSLLine := line.new(x1=bar_index, y1=sl_price, x2=bar_index + 1, y2=sl_price, color=color.red, width=1, extend=extend.right, style=line.style_dashed)
// ======== Updated Exit Conditions Based on EMA Cross ========
// Exit Long Position based on EMA condition
if strategy.position_size > 0 and exit_long and bar_index > long_entry_bar
strategy.close(id="Long Entry", comment="Exit Long (EMA1 crossed below EMA2)")
if showentry
label.new(bar_index, high, "Sell", style=label.style_label_down, color=color.new(color.red, 0), textcolor=color.white, size=size.tiny)
// Remove Stop Loss Line for Long Position
if not na(longSLLine)
line.delete(longSLLine)
longSLLine := na
long_entry_bar := na // Reset the entry bar
// Exit Short Position based on EMA condition
if strategy.position_size < 0 and exit_short and bar_index > short_entry_bar
strategy.close(id="Short Entry", comment="Exit Short (EMA1 crossed above EMA2)")
if showentry
label.new(bar_index, low, "Buy", style=label.style_label_up, color=color.new(color.green, 0), textcolor=color.white, size=size.tiny)
// Remove Stop Loss Line for Short Position
if not na(shortSLLine)
line.delete(shortSLLine)
shortSLLine := na
short_entry_bar := na // Reset the entry bar
// =======================================================
// Note: All plotting functions have been removed as per your request. The labels indicate entry and exit points.
Hi! I understand you're experiencing issues with your stop loss not activating at the intended 5% level, causing trades to continue until the opposite take profit (TP) is hit. Let's analyze your script and identify potential causes and solutions to ensure your stop loss functions correctly.
Primary Issue: Calculation of Take Profit (TP) and Stop Loss (SL) Prices
Current Implementation:
// Calculate Take Profit and Stop Loss Prices (Long Position)
tp1_price = close * (1 + tp1_perc / 100)
sl_price = close * (1 - sl_perc / 100)
Problem:
Base Price for Calculation: You're calculating tp1_price and sl_price based on the current close price, which might not accurately represent the entry price of the trade. This can lead to discrepancies, especially if the entry occurs at a different price than the current close.
Execution Timing: In Pine Script, strategy.entry and strategy.exit are processed within the same bar. If the bar's close price changes, the SL may not be accurately placed relative to the actual entry price.
Solution: Use Entry Price for Calculations
Instead of using the close price to calculate TP and SL, use the average entry price of the position. This ensures that TP and SL are correctly based on where the trade was actually entered.
How to Implement:
Calculate TP and SL Based on Entry Price:
Replace the current TP and SL calculations with ones based on strategy.position_avg_price. This variable represents the average price of your open position.
Update strategy.exit Calls:
Ensure that the strategy.exit uses the newly calculated TP and SL based on strategy.position_avg_price.
// Long Position Exit
strategy.exit(id="TP1", from_entry="Long Entry", qty_percent=tp1_qty_perc, limit=tp1_price, stop=sl_price, comment="Take Profit 1")
// Short Position Exit
strategy.exit(id="TP1_Short", from_entry="Short Entry", qty_percent=tp1_qty_perc, limit=tp1_price_short, stop=sl_price_short, comment="Take Profit 1 Short")
Revised Code Snippet:
Here's how you can modify the relevant sections of your script:
// Inside the Long Entry Condition
if longCondition and strategy.position_size <= 0
if strategy.position_size < 0
strategy.close(id="Short Entry", comment="Close Short")
strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
if showentry
label.new(bar_index, low, "Buy", style=label.style_label_up, color=color.new(color.green, 0), textcolor=color.white, size=size.tiny)
// Record the entry bar for long position
long_entry_bar := bar_index
short_entry_bar := na // Reset short entry bar
// Calculate Take Profit and Stop Loss Prices based on Entry Price
tp1_price = strategy.position_avg_price * (1 + tp1_perc / 100)
sl_price = strategy.position_avg_price * (1 - sl_perc / 100)
// Set Take Profit and Stop Loss Orders
strategy.exit(id="TP1", from_entry="Long Entry", qty_percent=tp1_qty_perc, limit=tp1_price, stop=sl_price, comment="Take Profit 1")
// Draw Stop Loss Line for Long Position
if not na(longSLLine)
line.delete(longSLLine)
longSLLine := line.new(x1=bar_index, y1=sl_price, x2=bar_index + 1, y2=sl_price, color=color.red, width=1, extend=extend.right, style=line.style_dashed)
// Inside the Short Entry Condition
if shortCondition and strategy.position_size >= 0
if strategy.position_size > 0
strategy.close(id="Long Entry", comment="Close Long")
strategy.entry(id="Short Entry", direction=strategy.short, comment="Short Entry")
if showentry
label.new(bar_index, high, "Sell", style=label.style_label_down, color=color.new(color.red, 0), textcolor=color.white, size=size.tiny)
// Record the entry bar for short position
short_entry_bar := bar_index
long_entry_bar := na // Reset long entry bar
// Calculate Take Profit and Stop Loss Prices based on Entry Price
tp1_price_short = strategy.position_avg_price * (1 - tp1_perc / 100)
sl_price_short = strategy.position_avg_price * (1 + sl_perc / 100)
// Set Take Profit and Stop Loss Orders
strategy.exit(id="TP1_Short", from_entry="Short Entry", qty_percent=tp1_qty_perc, limit=tp1_price_short, stop=sl_price_short, comment="Take Profit 1 Short")
// Draw Stop Loss Line for Short Position
if not na(shortSLLine)
line.delete(shortSLLine)
shortSLLine := line.new(x1=bar_index, y1=sl_price_short, x2=bar_index + 1, y2=sl_price_short, color=color.red, width=1, extend=extend.right, style=line.style_dashed)
Additional Recommendations
Ensure Proper Placement of strategy.exit:
It's crucial to place strategy.exit calls afterstrategy.entry to ensure they reference the correct position.
Avoid placing multiple strategy.exit calls without distinct identifiers to prevent conflicts.
Use Unique Identifiers for Multiple Exits:
If you have multiple exit conditions (like multiple TPs or dynamic exits), ensure each has a unique id.
Monitor Position Size and Entry Status:
Before setting an exit, ensure that a position exists. You can use strategy.position_size to verify.
Example:
if strategy.position_size > 0
// Set exits for long
if strategy.position_size < 0
// Set exits for short
Debugging with plot Statements:
Use plot to visualize tp1_price and sl_price to confirm they are calculated correctly.
Ensure these settings align with your broker's actual slippage and commission structure.
Final Thoughts
By recalculating TP and SL based on the actual entry price (strategy.position_avg_price), you ensure that your stop loss and take profit levels are accurately set relative to where the trade was entered. This change should help in correctly triggering your stop loss when the price moves against your position by the specified percentage.
Additionally, always test your strategy on historical data and in a simulated environment to ensure that SL and TP are behaving as expected before deploying it in a live trading scenario.
Feel free to reach out if you need further assistance or have additional questions!