1
votes

I want to set stop loss order based on price changing for each new entry order. The problem is that stop loss is executed only for the first order. I wrote the code this way:

//@version=4
strategy("Mutual funds RSI Index",
 "MF_RSI_IDX",
 default_qty_type=strategy.percent_of_equity,
 default_qty_value=10,
 initial_capital=1000,
 calc_on_order_fills=true,
 currency=currency.USD,
 commission_type=strategy.commission.percent,
 commission_value=0.29,
 process_orders_on_close=true)


if (rsi(close, 14) < 30)
    strategy.entry("buy", strategy.long)
stopLoss = strategy.position_avg_price * 0.80
lastPeak = close * 0.80

sellSignal0 = rsi(close, 14) > 70
sellSignal1 = falling(close, 5)
sellSignal2 = stopLoss >= close
sellSignal3 = lastPeak >= close

strategy.close("buy", when = sellSignal2 or sellSignal3)
plotchar(lastPeak, char="x", location=location.absolute)
plot(strategy.equity)

Can someone explain to me what is wrong with this code?

1
Few questions: 1) Are you trying to implement tracking stop-loss? Like if the price goes up - you increase draw the stop-level, closer to the current price? 2) What the exact problem you encounter? You can't exit your position or what? 3) What symbol+resolution for the testing? 4) The variable sellSignal0 isn't defined. Could you provide minimal working snippet? - Michel_T.
1) Yes, I'm trying to implement a tracking stop loss. However, I got to know that conditions in strategy.exit function are working simultaneously, not as alternatives (so it's not like in my statement either "stop" or "when" conditions are met). 2) The order is executed twice, and the second entry is never closed. 3) ONCY (Oncolytics Biotech); 1 day resolution. 4) sellSignal0 = rsi(close, 14) > 70 - Maciej Ziolkowski
I think it's worth to mention that I am trying to implement tracking stop loss estimated in percentage of latest high, not based on ticks. - Maciej Ziolkowski
what are the params in the strategy() function? - Michel_T.
The order is executed twice, and the second entry is never closed entry order or exit? Could you post minimal working script which could be applied to the chart and I could see the problem? - Michel_T.

1 Answers

1
votes
//@version=4
strategy("Mutual funds RSI Index",
 "MF_RSI_IDX",
 overlay=true,
 default_qty_type=strategy.percent_of_equity,
 default_qty_value=10,
 initial_capital=1000,
 currency=currency.USD,
 commission_type=strategy.commission.percent,
 commission_value=0.29)


strategy.entry("buy", strategy.long, when=rsi(close, 14) < 30)

stopLoss = 0.0
if strategy.position_avg_price != 0
    stopLoss := max(strategy.position_avg_price * 0.9, nz(stopLoss[1]))

limitPrice = float(na)
// force exit
if rsi(close, 14) > 70
    limitPrice := 0.0

strategy.exit("buy", stop=stopLoss, limit=limitPrice)

Is that what you are looking for? I think it's better to close the position by exit here and note, that I removed calc_on_order_fills and process_orders_on_close, because they are pretty controversial.