本策略是一个利用分阶梯式止盈结合滑点止损的退出策略。它在达到第一个止盈点后会将止损移至盈亏平衡点,在达到第二个止盈点后会将止损移至第一个止盈点,从而实现了一个分阶梯式的止损滑点机制。这可以锁定部分利润的同时保持较大的利润空间。
本策略主要通过以下几个部分来实现分阶止盈滑点:
具体来说,它首先设置了100点的止损距离和100/200/300点的3个止盈距离。然后定义了基于当前价格和开仓价格来计算获利点数的函数curProfitInPts
,以及根据点数距离计算止损价格的函数calcStopLossPrice
。
关键逻辑在于getCurrentStage
函数,它判断当前是否有头寸,以及获利点数是否超过了某个止盈点,如果超过则进入下一阶段。例如达到100点止盈后进入第二阶段,达到200点止盈后进入第三阶段。
最后根据阶段不同修改止损价格,从而实现滑点止损。第一阶段止损保持原始设置,第二阶段移至盈亏平衡,第三阶段移至第一个止盈点。
这种分阶梯式止盈滑点策略具有以下几个优势:
该策略也存在一定的风险:
该策略可以从以下几个方向进行优化:
/*backtest
start: 2023-11-20 00:00:00
end: 2023-11-27 00:00:00
period: 3m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov
// @description
// when tp1 is reached, sl is moved to break-even
// when tp2 is reached, sl is moved to tp1
// when tp3 is reached - exit
//@version=4
strategy("Stepped trailing strategy example", overlay=true)
// random entry condition
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
// sl & tp in points
sl = input(100)
tp1 = input(100)
tp2 = input(200)
tp3 = input(300)
curProfitInPts() =>
if strategy.position_size > 0
(high - strategy.position_avg_price) / syminfo.mintick
else if strategy.position_size < 0
(strategy.position_avg_price - low) / syminfo.mintick
else
0
calcStopLossPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else
0
calcProfitTrgtPrice(OffsetPts) =>
calcStopLossPrice(-OffsetPts)
getCurrentStage() =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size != 0
stage := 1
else if stage == 1 and curProfitInPts() >= tp1
stage := 2
else if stage == 2 and curProfitInPts() >= tp2
stage := 3
stage
stopLevel = -1.
profitLevel = calcProfitTrgtPrice(tp3)
// based on current stage set up exit
// note: we use same exit ids ("x") consciously, for MODIFY the exit's parameters
curStage = getCurrentStage()
if curStage == 1
stopLevel := calcStopLossPrice(sl)
strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")
else if curStage == 2
stopLevel := calcStopLossPrice(0)
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")
else if curStage == 3
stopLevel := calcStopLossPrice(-tp1)
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")
else
strategy.cancel("x")
// this is debug plots for visulalize TP & SL levels
plot(stopLevel > 0 ? stopLevel : na, style = plot.style_linebr)
plot(profitLevel > 0 ? profitLevel : na, style = plot.style_linebr)