Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

so i have this code and there are problem with tp and sl for long can you ceck pls //…

  1. User

    so i have this code and there are problem with tp and sl for long can you ceck pls // This work is licensed under an Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) // © veryfid

    //@version=5 strategy("Demo GPT - Boom Hunter Pro 1.022", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=3)

    // Declare errorLabel variable var label errorLabel = na

    // Start and End Date Inputs startDate = input.time(defval=timestamp("01 Jan 2018"), title="Start Date", group="Backtest Period") endDate = input.time(defval=timestamp("31 Dec 2069"), title="End Date", group="Backtest Period") inDateRange = (time >= startDate) and (time <= endDate)

    // Input Settings theme = 'Dark' showfib = input.bool(defval=false, title='Show Fibonacci Lines?', group='Main Settings', inline='main2') showentry = input.bool(defval=true, title='Show Entry and Exit Points?', group='Main Settings') square = input.bool(true, title='Square Line?', group='Main Settings') showdboom = input.bool(true, title='Show Downward Boom Line?', group='Main Settings') showlongs = input.bool(true, title='Show Long Entries?', group='Main Settings') showshorts = input.bool(true, title='Show Short Entries?', group='Main Settings')

    // 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

    // Quotient Inputs LPPeriod = input.int(6, title='Quotient | LPPeriod', inline='quotient', group='EOT 1 (Main Oscillator)') K1 = input.float(0.0, title='K1', inline='quotient', group='EOT 1 (Main Oscillator)') K2 = 0.3 esize = 60 ey = 50 trigno = input.int(2, 'Trigger Length', group='EOT 1 (Main Oscillator)', inline='quotient2') osccol = input.color(color.blue, title='Oscillator Color:', group='EOT 1 (Main Oscillator)', inline='q2') trigcol = input.color(color.white, title='Trigger Color:', group='EOT 1 (Main Oscillator)', inline='q2')

    // EOT 2 Inputs LPPeriod2 = input.int(27, title='LPPeriod2', group='EOT 2 (Red Wave)', inline='q2') K12 = input.float(0.8, title='K1', group='EOT 2 (Red Wave)', inline='q2') K22 = input.float(0.3, title='K2', group='EOT 2 (Red Wave)', inline='q2') esize3 = 60 ey3 = 50 osccol2 = input.color(color.red, title='Line Color:', inline='quotient22', group='EOT 2 (Red Wave)') osccol22 = input.color(color.red, title='Fill Color:', inline='quotient22', group='EOT 2 (Red Wave)')

    // EOT 3 Inputs LPPeriod3 = input.int(11, title='LPPeriod3', group='EOT 3 (Yellow Line)', inline='q2') K13_input = input.float(0.99, title='K1', group='EOT 3 (Yellow Line)', inline='q2') esize2 = 60 ey2 = 50 osccol3 = input.color(color.yellow, title='Line Color:', group='EOT 3 (Yellow Line)', inline='quotient3')

    // Declare K13 and K33 float K13 = na float K33 = na

    // Assign K13 and K33 based on 'square' input if square K13 := 0.9999 K33 := -0.9999 else K13 := K13_input K33 := -K13_input

    // LSMAWT Inputs n1 = input.int(9, 'WT | master', inline='lsma', group='LSMA Wave Trend Settings') n2 = input.int(6, 'time 1', inline='lsma', group='LSMA Wave Trend Settings') n3 = input.int(3, '2', inline='lsma', group='LSMA Wave Trend Settings') n4 = input.int(21, 'LSMA | 1', inline='LSMA', group='LSMA Wave Trend Settings') n5 = input.int(0, '2', inline='LSMA', group='LSMA Wave Trend Settings') smalen = 2 lsmaline = input.int(200, title='LSMA Long', group='LSMA Wave Trend Settings', inline='LSMA')

    // 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)

    // Highpass filter cyclic components alpha1 := (math.cos(.707 * 2 * pi / 100) + math.sin(.707 * 2 * pi / 100) - 1) / math.cos(.707 * 2 * pi / 100) HP := (1 - alpha1 / 2) * (1 - alpha1 / 2) * (close - 2 * nz(close[1]) + nz(close[2])) + 2 * (1 - alpha1) * nz(HP[1]) - (1 - alpha1) * (1 - alpha1) * nz(HP[2])

    // SuperSmoother Filter a1 := math.exp(-1.414 * pi / LPPeriod) b1 := 2 * a1 * math.cos(1.414 * pi / LPPeriod) c2 := b1 c3 := -a1 * a1 c1 := 1 - c2 - c3 Filt := c1 * (HP + nz(HP[1])) / 2 + c2 * nz(Filt[1]) + c3 * nz(Filt[2])

    // Fast Attack - Slow Decay Algorithm Peak := .991 * nz(Peak[1]) if math.abs(Filt) > Peak Peak := math.abs(Filt) if Peak != 0.0 X := Filt / Peak else X := 0.0

    Quotient1 := (X + K1) / (K1 * X + 1) Quotient2 := (X + K2) / (K2 * X + 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

    alpha1222 := (math.cos(.707 * 2 * pi / 100) + math.sin(.707 * 2 * pi / 100) - 1) / math.cos(.707 * 2 * pi / 100) HP2 := (1 - alpha1222 / 2) * (1 - alpha1222 / 2) * (close - 2 * nz(close[1]) + nz(close[2])) + 2 * (1 - alpha1222) * nz(HP2[1]) - (1 - alpha1222) * (1 - alpha1222) * nz(HP2[2])

    // SuperSmoother Filter a12 := math.exp(-1.414 * pi / LPPeriod2) b12 := 2 * a12 * math.cos(1.414 * pi / LPPeriod2) c22_var := b12 c32 := -a12 * a12 c12 := 1 - c22_var - c32 Filt2 := c12 * (HP2 + nz(HP2[1])) / 2 + c22_var * nz(Filt2[1]) + c32 * nz(Filt2[2])

    // Fast Attack - Slow Decay Algorithm Peak2 := .991 * nz(Peak2[1]) if math.abs(Filt2) > Peak2 Peak2 := math.abs(Filt2) if Peak2 != 0.0 X2 := Filt2 / Peak2 else X2 := 0.0

    Quotient3 := (X2 + K12) / (K12 * X2 + 1) Quotient4 := (X2 + K22) / (K22 * X2 + 1)

    // 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

    alpha1333 := (math.cos(.707 * 2 * pi / 100) + math.sin(.707 * 2 * pi / 100) - 1) / math.cos(.707 * 2 * pi / 100) HP3 := (1 - alpha1333 / 3) * (1 - alpha1333 / 2) * (close - 2 * nz(close[1]) + nz(close[2])) + 2 * (1 - alpha1333) * nz(HP3[1]) - (1 - alpha1333) * (1 - alpha1333) * nz(HP3[2])

    // SuperSmoother Filter a13 := math.exp(-1.414 * pi / LPPeriod3) b13 := 2 * a13 * math.cos(1.414 * pi / LPPeriod3) c33_var := b13 c333 := -a13 * a13 c13 := 1 - c33_var - c333 Filt3 := c13 * (HP3 + nz(HP3[1])) / 2 + c33_var * nz(Filt3[1]) + c333 * nz(Filt3[2])

    // Fast Attack - Slow Decay Algorithm Peak3 := .991 * nz(Peak3[1]) if math.abs(Filt3) > Peak3 Peak3 := math.abs(Filt3) if Peak3 != 0.0 X3 := Filt3 / Peak3 else X3 := 0.0

    Quotient5 := (X3 + K13) / (K13 * X3 + 1) Quotient6 := (X3 + K33) / (K33 * X3 + 1)

    // LSMAWT Calculations tci(src) => ta.ema((src - ta.ema(src, n1)) / (0.025 * ta.ema(math.abs(src - ta.ema(src, n1)), n1)), n2) + 50

    mf(src) => 100.0 - 100.0 / (1.0 + math.sum(volume * (ta.change(src) <= 0 ? 0 : src), n3) / math.sum(volume * (ta.change(src) >= 0 ? 0 : src), n3))

    tradition(src) => math.avg(tci(src), mf(src), ta.rsi(src, n3))

    src5 = hlc3 wt1 = tradition(src5) wt2 = ta.sma(wt1, 6) wt3 = ta.linreg(wt1, n4, n5) wt4 = ta.ema((wt1 - wt2) * 2 + 50, n3) trig = ta.sma(wt3, smalen)

    // Quotient Calculations q1 = Quotient1 * esize + ey q2 = Quotient2 * esize + ey q3 = Quotient3 * esize + ey q4 = Quotient4 * esize + ey q5 = Quotient5 * esize2 + ey2 q6 = Quotient6 * esize2 + ey2 trigger = ta.sma(q1, trigno)

    // ======== New Section: EMA Exit Settings ======== ema1_length = input.int(defval=10, title="EMA 1 Length", group="EMA Exit") ema2_length = input.int(defval=20, title="EMA 2 Length", group="EMA Exit")

    ema1 = ta.ema(close, ema1_length) ema2 = ta.ema(close, ema2_length)

    // 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

    // Long Entry Conditions
    // Calculate Take Profit and Stop Loss Prices for Long and Short Positions
    

    tp1_price = strategy.position_size > 0 ? close * (1 + tp1_perc / 100) : close * (1 - tp1_perc / 100) sl_price = strategy.position_size > 0 ? close * (1 - sl_perc / 100) : close * (1 + sl_perc / 100)

    if inDateRange // Long Position Handling if strategy.position_size > 0 // Priority: Stop Loss Check if close <= sl_price strategy.close(id="Long Entry", comment="Stop Loss Hit (Long)") if showentry label.new(bar_index, low, "SL Hit (Long)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny) // Take Profit Check if SL not hit else if close >= tp1_price strategy.exit(id="TP1", from_entry="Long Entry", qty_percent=tp1_qty_perc, limit=tp1_price, stop=sl_price, comment="Take Profit 1 (Long)") // EMA-based Exit Strategy if neither SL nor TP is hit else if exit_long and bar_index > long_entry_bar strategy.close(id="Long Entry", comment="Exit Long (EMA Condition)") if showentry label.new(bar_index, high, "EMA Exit (Long)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)

    // Post-Exit Cleanup for Long Positions
    if strategy.position_size <= 0 and not na(longSLLine)
        line.delete(longSLLine)
        longSLLine := na
    long_entry_bar := na  // Reset entry bar
    
    // 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
    // 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
    // =======================================================
    
  2. Assistant

    Certainly! I'll help you identify and resolve the issues related to Take Profit (TP) and Stop Loss (SL) for long positions in your Pine Script strategy. Let's break down the potential problems and suggest appropriate fixes.

    1. TP and SL Calculation Based on Current Close

    Issue:

    Your current TP and SL prices are calculated based on the current close price rather than the entry price. This means that as the price moves, your TP and SL levels are continuously adjusted, which is not the intended behavior.

    tp1_price = strategy.position_size > 0 ? close * (1 + tp1_perc / 100) : close * (1 - tp1_perc / 100)
    sl_price  = strategy.position_size > 0 ? close * (1 - sl_perc / 100) : close * (1 + sl_perc / 100)
    

    Solution:

    Calculate TP and SL based on the entry price (strategy.position_avg_price) instead of the current close price. This ensures that TP and SL levels remain fixed relative to the entry price.

    Implementation:

    1. Calculate TP and SL Based on Entry Price:

      // Calculate TP and SL based on entry price
      entryPrice = strategy.position_avg_price
      tp1_price = entryPrice * (1 + tp1_perc / 100)
      sl_price  = entryPrice * (1 - sl_perc / 100)
      
    2. Set TP and SL Orders Upon Entry:

      Instead of recalculating TP and SL on every bar, set them once when the position is entered.

      // Example Long Entry Condition (Replace with your actual condition)
      longCondition = enter3 or enter5 or enter6 or enter7
      
      if (longCondition and inDateRange and strategy.position_size <= 0)
          strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
          // Set TP and SL for long position
          strategy.exit(id="TP1_Long", from_entry="Long Entry", limit=entryPrice * (1 + tp1_perc / 100), stop=entryPrice * (1 - sl_perc / 100), qty_percent=tp1_qty_perc, comment="Take Profit 1 (Long)")
      

    2. Conflicting Exit Conditions

    Issue:

    You're manually checking for close <= sl_price and close >= tp1_price to close positions and setting strategy.exit orders based on the same conditions. This can lead to conflicting orders and unintended behavior.

    if strategy.position_size > 0
        if close <= sl_price
            strategy.close(id="Long Entry", comment="Stop Loss Hit (Long)")
        else if close >= tp1_price
            strategy.exit(id="TP1", from_entry="Long Entry", ...)
    

    Solution:

    Rely solely on strategy.exit to handle TP and SL. Remove the manual condition checks to prevent conflicts and ensure that strategy.exit manages all exits related to TP and SL.

    Implementation:

    1. Remove Manual SL and TP Checks:

      // Remove these manual checks
      /*
      if strategy.position_size > 0
          if close <= sl_price
              strategy.close(id="Long Entry", comment="Stop Loss Hit (Long)")
          else if close >= tp1_price
              strategy.exit(id="TP1", from_entry="Long Entry", ...)
      */
      
    2. Use strategy.exit Effectively:

      By setting strategy.exit upon entering the position, you delegate the responsibility of managing TP and SL to Pine Script's built-in mechanisms.

      if (longCondition and inDateRange and strategy.position_size <= 0)
          strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
          // Set TP and SL
          strategy.exit(id="TP1_Long", from_entry="Long Entry", limit=tp1_price, stop=sl_price, qty_percent=tp1_qty_perc, comment="Take Profit 1 (Long)")
      

    3. Ensuring Proper Entry Bar Tracking

    Issue:

    The variable long_entry_bar is used to track the entry bar but is not being set upon entering a long position. Additionally, resetting it prematurely can interfere with exit conditions.

    var int long_entry_bar = na
    ...
    long_entry_bar := na  // Reset entry bar
    

    Solution:

    Set long_entry_bar when entering a long position to ensure that exit conditions (like EMA-based exit) are correctly referencing the entry point.

    Implementation:

    1. Set long_entry_bar Upon Entry:

      if (longCondition and inDateRange and strategy.position_size <= 0)
          strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
          long_entry_bar := bar_index
          // Set TP and SL
          strategy.exit(id="TP1_Long", from_entry="Long Entry", limit=tp1_price, stop=sl_price, qty_percent=tp1_qty_perc, comment="Take Profit 1 (Long)")
      
    2. Modify Exit Conditions to Reference long_entry_bar:

      if strategy.position_size > 0
          // EMA-based Exit Strategy if neither SL nor TP is hit
          if exit_long and bar_index > long_entry_bar
              strategy.close(id="Long Entry", comment="Exit Long (EMA Condition)")
              if showentry
                  label.new(bar_index, high, "EMA Exit (Long)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)
              long_entry_bar := na  // Reset after exit
      

    4. Additional Recommendations

    1. Consistent Naming Conventions: Ensure that all strategy.exit and strategy.entry IDs are consistently named and unique to prevent conflicts.

    2. Debugging with Labels: Use labels to debug entry and exit points. This can help visualize whether TP and SL levels are set correctly.

      if (longCondition and inDateRange and strategy.position_size <= 0)
          strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
          label.new(bar_index, high, "Long Entry", style=label.style_label_up, color=color.green, textcolor=color.white, size=size.tiny)
      
      // When setting TP and SL
      label.new(bar_index, tp1_price, "TP1", style=label.style_label_down, color=color.blue, textcolor=color.white, size=size.tiny)
      label.new(bar_index, sl_price, "SL", style=label.style_label_up, color=color.red, textcolor=color.white, size=size.tiny)
      
    3. Use Pine Script’s Built-in Features: Leverage Pine Script's built-in strategy.position_avg_price and other related functions to manage positions more effectively.

    4. Simplify Exit Logic: Relying on strategy.exit for managing exits (TP, SL, EMA-based) can simplify your code and reduce potential conflicts.

    Revised Code Snippet for Long Positions

    Here's a revised version of the relevant parts of your script focusing on long positions:

    //@version=5
    strategy("Demo GPT - Boom Hunter Pro 1.022", overlay=true, commission_type=strategy.commission.percent, commission_value=0.1, slippage=3)
    
    // ... [Other parts of your code]
    
    // 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 int long_entry_bar = na
    
    // ... [Indicator calculations]
    
    // === Long Entry Conditions ===
    // Replace `enter_condition` with your actual long entry conditions (e.g., enter3, enter5, etc.)
    longCondition = enter3 or enter5 or enter6 or enter7
    
    if (longCondition and inDateRange and strategy.position_size <= 0)
        strategy.entry(id="Long Entry", direction=strategy.long, comment="Long Entry")
        long_entry_bar := bar_index
        // Set TP and SL based on entry price
        entryPrice = strategy.position_avg_price
        tp1_price = entryPrice * (1 + tp1_perc / 100)
        sl_price  = entryPrice * (1 - sl_perc / 100)
        strategy.exit(id="TP1_Long", from_entry="Long Entry", limit=tp1_price, stop=sl_price, qty_percent=tp1_qty_perc, comment="Take Profit 1 (Long)")
        // Optionally set TP2 if needed
        // strategy.exit(id="TP2_Long", from_entry="Long Entry", limit=entryPrice * (1 + tp2_perc / 100), qty_percent=tp2_qty_perc, comment="Take Profit 2 (Long)")
    
    // === Handling Existing Long Positions ===
    if (strategy.position_size > 0)
        // EMA-based Exit Strategy
        if exit_long and bar_index > long_entry_bar
            strategy.close(id="Long Entry", comment="Exit Long (EMA Condition)")
            if showentry
                label.new(bar_index, high, "EMA Exit (Long)", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)
            long_entry_bar := na  // Reset after exit
    

    Summary of Changes

    1. TP and SL Based on Entry Price:

      • Calculated tp1_price and sl_price using strategy.position_avg_price.
    2. Setting strategy.exit Upon Entry:

      • Set TP and SL immediately after entering a long position.
    3. Removed Manual TP and SL Checks:

      • Eliminated manual if close <= sl_price and if close >= tp1_price conditions to prevent conflicts.
    4. Tracked long_entry_bar:

      • Set long_entry_bar upon entry to use in EMA-based exit conditions.
    5. Simplified Exit Logic:

      • Used strategy.exit for handling TP and SL, and separate logic for EMA-based exits.

    By implementing these changes, your strategy should handle TP and SL for long positions more reliably and as intended. Ensure that similar adjustments are made for short positions to maintain consistency across your strategy.

    If you encounter further issues or need additional assistance, feel free to ask!