I have a strategy that opens a long position with 100% of my capital if the last candle closes above the 4 MA. I set a stop loss at 1% below the average entry price, in this case the entry was at 1152 so the stop loss is set at 1152 * 0.99 which is 1140.48.
Desired behavior is that I enter at 1152 with a stop loss that triggers as soon as price goes down past 1140.48.
I get stopped out at the next candle open price at 1005.5 for a 12.72% loss. I have tried reducing order size but it makes no difference, the position is exited at the same place. Is this something to do with the time that Pine calculates the script? It seems to be a problem when the very next candle opens at more distance from entry than my stop loss distance.
//@version=4
strategy("Stoploss", overlay=true,
default_qty_type=strategy.percent_of_equity, default_qty_value=100)
sma_per = input(4, title='SMA Lookback Period', minval=1)
sl_inp = input(1.0, title='Stop Loss %', type=input.float) / 100
sma = sma(close, sma_per)
stop_level = strategy.position_avg_price * (1 - sl_inp)
strategy.entry("L", strategy.long, when=close > sma)
// Stop loss should trigger whenever we hit stop_level once we are in a position
strategy.exit("Stop Loss", "L", stop=stop_level)
plot(sma, color=color.orange, linewidth=2)
Note that I also tried using:
strategy.order("Stop Loss", long=strategy.short, qty=strategy.position_size, stop=stop_level)
for my stop loss instead of strategy.exit()
but I get the same result.
Here is the trade list, displaying our loss. note that the same thing happens with Trade 2 - we lose more than we should on the very next candle:
I understand that Pine calculates the script after each candle close and if I set calc_on_order_fills
to true then the script will also be ran after an order is filled. This seems to fix the problem since once I enter a long position, the script is ran again on the current candle and triggers the stop loss if price moves against me enough. However, this also results in the whole script being ran every time an order is filled. Is there any way to simply have the following behavior?
- Enter position according to last candle close if entry condition is met
- Set stop loss according to entry position
- Stop loss is triggered any time after entering the position if price hits stop loss level