Search code examples
pine-scriptpine-script-v5tradingview-api

Entry and Exit based on the Engulfing candle


I am writing a Pine Script to back test a custom strategy. But, it is not working as expected.

Expected is as per the strategy below.

Strategy: Long

  1. LTP should be above EMA 200.
  2. RSI divergence should be more than 50
  3. Previous candle should be Bullish Engulfing candle

Exit

  1. Profit should be 4 times the size of the Engulfing candle
  2. Stop loss should be 2 times the Engulfing candle

Following is the code I have written

//@version=5
strategy("Bullish scalping")

ema200 = ta.ema(close, 200)
rsi = ta.rsi(close, 9)
bullishEngulfing = open[1] > close[1] ? close > open ? close >= open[1] ? close[1] >= open ? close - open > open[1] - close[1] ? true :false :false : false : false : false

BUY_VALUE = 0
DIFF = 0

global = array.new_float(2)

buy = ((close > ema200) and (rsi > 50) and bullishEngulfing)

if( buy == true )
    strategy.entry("Long", strategy.long, 20.0)
    array.set(global,BUY_VALUE,close)
    array.set(global,DIFF,(close[1]-open[1]))

if ((close - array.get(global,BUY_VALUE) >= (array.get(global,DIFF)*4)) or (array.get(global,BUY_VALUE) - close >= (array.get(global,DIFF)*2)))
    strategy.close("Long")

The entry points are correct, but the exit points are not correct. What am I doing wrong here?


Solution

  • You don't need to use arrays for this. Also, for stop loss and target, it is better to use the functionality in strategy.exit() which will work as intended for that purpose. The code is below:

    //@version=5
    strategy("Bullish scalping")
    
    ema200 = ta.ema(close, 200)
    rsi = ta.rsi(close, 9)
    bullishEngulfing = open[1] > close[1] ? close > open ? close >= open[1] ? close[1] >= open ? close - open > open[1] - close[1] ? true :false :false : false : false : false
    
    BUY_VALUE = 0.0
    DIFF = 0.0
    Stop = 0.0
    Target = 0.0
    
    global = array.new_float(2)
    
    buy = ((close > ema200) and (rsi > 50) and bullishEngulfing)
    
    if (buy)
        strategy.entry("Long", strategy.long, 20.0)
    
    if strategy.position_size > 0
        BUY_VALUE := strategy.position_avg_price
        DIFF := ta.valuewhen(buy, close[1]-open[1], 0)
        Stop := BUY_VALUE - (DIFF * 2)
        Target := BUY_VALUE + (DIFF * 4)
    
        strategy.exit("Exit", "Long", limit=Target, stop=Stop)