Update stop loss based on last entry price

纵饮孤独 提交于 2020-01-24 19:34:06

问题


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:


//@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.



来源:https://stackoverflow.com/questions/59233868/update-stop-loss-based-on-last-entry-price

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!