I'm trying to create a quite simple MA-crossover strategy (long only) where I want to exit the trade either on a fixed stoploss level, or when my exitcondition is met. For this reason I'm using the strategy.order function to exit my trades. However, apparently something is wrong since also a couple of short trades are initiated... Here you can find the most important part of the code:
//strategy conditions & variables
ordersize=floor(strategy.equity/close)
trendfilter = RSI_w > i_RSI_TH ? 1 : 0
longCondition = crossover(shortMA,longMA)
exitCondition = crossover(longMA,shortMA)
stopLoss = float(na)
stopLoss := strategy.position_size[0]>strategy.position_size[1] ? strategy.position_avg_price - (i_atr_mult * atr) : strategy.position_size>0 ? stopLoss[1] : na
// strategy entry & exits
strategy.entry(id="going long", long=true, qty=ordersize, when=longCondition and TimeWindow and trendfilter>0)
strategy.order(id="stop loss", long=false, stop=stopLoss, oca_name='L', oca_type=strategy.oca.cancel, qty=strategy.position_size, when=strategy.position_size > 0 and TimeWindow)
strategy.order(id="exit long", long=false, oca_name='L', oca_type=strategy.oca.cancel, qty=strategy.position_size, when= exitCondition and strategy.position_size > 0 and TimeWindow)
So in my logic the first strategy.order function can only open trades when the strategy.position_size > 0. This should avoid taking short orders, but apparantly it is not. When the price hits the SL-level, even when not in an open trade, a short trade is initiated... Can someone explain me why this is??? And even better, how I can adapt my code to avoid these short entries? This would help me a lot!!
To recap: the line of code which is responsible for these short entries is:
strategy.order(id="stop loss", long=false, stop=stopLoss, oca_name='L', oca_type=strategy.oca.cancel, qty=strategy.position_size, when=strategy.position_size > 0 and TimeWindow)
First order is stop, second order is market order. When exitCondition is true and price satisfy stopLoss condition there are both order are executed at one time and broker emulator can not get in time to cancel other order. I suggest you explicitly cancel stop order when exitCondition will became true.