I am using the below code for the 5 EMA sell strategy - POS backtesting. When i see the list of trades, i feel there are some exits which were taken randomly and other were ok. I dont understand where the problem is in the code or trading veiw. Can someone please help?
//@version=5
strategy('5 EMS sell Strategy', overlay=true)
// Input: EMA Length
emaLength = input(5, title='EMA Length')
// start_d = input.time(timestamp('2019-01-01'))
// end_d = input.time(timestamp('2021-01-01'))
// time_cond = time >= start_d and time <= end_d
// Calculate Exponential Moving Average (EMA)
ema = ta.ema(close, emaLength)
// Identify Trigger Candle
lowDoesNotTouchEMA = low[1] > ema[1]
isTriggerCandle = lowDoesNotTouchEMA
// Entry Condition: Candle Breaks Low of Trigger Candle
shouldSell = low < low[1] and isTriggerCandle and open > close
// Calculate Stop Loss and Take Profit Levels
stopLoss = math.max(high, high[1])
// takeProfit = close - ((stopLoss-close)*3)
takeProfit = close - ((stopLoss - close)*3)
// Plot EMA
plot(ema, title='5 EMA', color=color.new(color.blue, 0))
// Plot Trigger Candle Markers
plotshape(series=isTriggerCandle, style=shape.triangleup, location=location.belowbar, color=color.rgb(82, 183, 255), size=size.small, offset=-1)
// Backtest Range
// startYear = year - 5
// testRange = time <= timestamp(year, 1, 1, 0, 0) and time >= timestamp(startYear , 12, 31, 23, 59)
// Strategy Sell Condition
if shouldSell
strategy.entry('Sell', strategy.short)
// Strategy Exit Condition
strategy.exit('Take Profit/Stop Loss', from_entry='Sell', stop=stopLoss, limit=takeProfit)
if session.islastbar_regular
strategy.close_all(immediately = true)