Search code examples
pine-scriptpine-script-v5

How to prevent entry if there is a bearish divergence prior to the entry point (Pine Script V.5)


I tried creating pullback strategy with the combination RSI, EMA7 and EMA30 but having a problem with;

  1. I want to enter trade only when EMA7 is above EMA30 and other conditions are met (which is working fine)
  2. I want to prevent entry if there is a bullish divergence prior to entry point.
  3. And the trade can be entered again after EMA7 crosses EMA30 down ----> and then crosses up again with other conditions met (don't worry about other conditions, I have it covered).
  4. (however, if there is a new bearish divergence, then loop back to 2.)

I don't even know where to begin, can anyone help me Thank you in advance,


Solution

  • Check this `

    //@version=5
    strategy("Pullback Strategy with RSI, EMA7, and EMA30", overlay=true)
    
    // Inputs
    rsiLength = input(14, title="RSI Length")
    ema7Length = input(7, title="EMA7 Length")
    ema30Length = input(30, title="EMA30 Length")
    divergenceThreshold = input(1.5, title="Divergence Threshold")
    
    // Calculate indicators
    rsiValue = ta.rsi(close, rsiLength)
    ema7 = ta.ema(close, ema7Length)
    ema30 = ta.ema(close, ema30Length)
    
    // Calculate bullish divergence
    divergenceCondition = low[2] < low[1] and low[1] < low and rsiValue[2] > rsiValue[1] and rsiValue[1] < rsiValue
    bullishDivergence = rsiValue < 70 and divergenceCondition
    
    // Entry conditions
    enterLong = ema7 > ema30 and not bullishDivergence and ta.crossover(ema7, ema30)
    enterShort = ema7 < ema30 and ta.crossunder(ema7, ema30)
    
    // Exit conditions
    exitLong = ta.crossunder(ema30, ema7)
    exitShort = ta.crossover(ema30, ema7)
    
    // Strategy logic
    if (enterLong)
        strategy.entry("Long", strategy.long)
    
    if (enterShort)
        strategy.entry("Short", strategy.short)
    
    if (exitLong)
        strategy.close("Long")
    
    if (exitShort)
        strategy.close("Short")
    
    // Plotting
    plot(ema7, color=color.blue, title="EMA7")
    plot(ema30, color=color.red, title="EMA30")
    plotshape(bullishDivergence, location=location.belowbar, color=color.green, style=shape.labelup, text="Bull Div")
    
    // Alert
    alertcondition(enterLong, title="Enter Long", message="Enter Long")
    alertcondition(enterShort, title="Enter Short", message="Enter Short")
    `