// TP/SL trail backtest system ---------------------------------------------
TakeProfit = input.float(2.3, title='Take Profit', minval=0.1, step=0.1,
group='Take Profit / Stop Loss')
StopLoss = input.float(2, title='Stop loss', minval=0.1, step=0.1, group='Take
Profit / Stop Loss')
//BACKTESTING inputs -----------
showLines = input(true, "Show TP/SL lines", group='BACKTEST')
ExtendTrailLines = input.int(5, 'Extend trail lines for bars:', minval=1,
group='BACKTEST')
long_ = input.bool(true, title='Longs', group='BACKTEST')
short_ = input.bool(true, title='Shorts', group='BACKTEST')
useTrailSL = input(false, "Use trail", group='Trail system', tooltip = "Main
parameter to activate trail function in general (SL by default, TP as optional)")
TrailSteps = input.int(3, "Trail SL steps (2-3)", minval = 2, maxval = 3,
group='Trail system', tooltip = "This will alow you to choose how many steps you
want for trail SL/TP before main take profit is hit. For example 2 means that first
trail SL will be on 50% of your main TP, 3 on each 33% of your main TP as one
trail. On each step that is passed strategy will close 1/3 of your position if you
activate trail TP to.")
LadderTrail = input(false, "Ladder trail", group='Trail system', tooltip = "Use
Trail must be activated, while this function will set SL one level lower after the
each level is reached. For example if step 1 is reached SL will be on break even,
if step 2 is reached SL will be on step 1 and so on...")
TrailSLContinue = input(false, "Continue with trail SL without main TP",
group='Trail system', tooltip = "Alert to close the position will be sent once that
trail SL level is broken. If you are using third party app via webhook pay
attention to disable TP there to.")
useTrailTP = input(false, "Trail TP", inline = "trailTP", group='Trail system',
tooltip = "If this option is activated it will close 1/3 of the position on each
trail steps. The last 1/3 will be closed according to trail settings")
useClosePriceForTrailTP = input(false, "Use candles close price to calc trail SL",
group='Trail system', tooltip = "This option will use candle close price that is
always above trail step to calculate trail SL, which means in most scenarios will
set higher SL step then initially set.")
useWicksSL = input(false, "Use wicks to calc and activate trail SL level (Work with
ladder)", group = "Trail system", tooltip = "This option will consider candles wick
as price that is over trail level if candle is not closed above the trail level but
just wick is")
usePBsecure = input(false, "Use secure for pullback after trail level is reached",
group='Trail system', tooltip = "This will consider to close the next position size
if price is get back above the trail level again")
PBThreshold = input.float(50, "Pullback threshold %", group='Trail system', step =
1, minval = 1, tooltip = "This threshold is between two trail levels")
//ALERTS Messages -----------------------
i_alert_txt_entry_long = input.text_area(defval = "", title = "Long Entry Message",
group = "Alerts")
i_alert_txt_entry_short = input.text_area(defval = "", title = "Short Entry
Message", group = "Alerts")
i_alert_txt_tp_long = input.text_area(defval = "", title = "Long Market Close
Message", group = "Alerts")
i_alert_txt_tp_short = input.text_area(defval = "", title = "Short Market Close
Message", group = "Alerts")
i_alert_txt_trailTP_long = input.text_area(defval = "", title = "Long trail TP 1
(close 33% of position) Message", group = "Alerts")
i_alert_txt_trailTP2_long = input.text_area(defval = "", title = "Long trail TP 2
(close 50% of position) Message", group = "Alerts")
i_alert_txt_trailTP_short = input.text_area(defval = "", title = "Short trail TP 1
(close 33% of position) Message", group = "Alerts")
i_alert_txt_trailTP2_short = input.text_area(defval = "", title = "Short trail TP 2
(close 50% of position) Message", group = "Alerts")
// BACKTEST ====================
var bool longCond = na
var bool shortCond = na
// Here is your input trigger conditions for long/short
longCond := YOUR LONG TRIGGER
shortCond := YOUR SHORT TRIGGER
var float tplLevel = na
var float tpsLevel = na
var float sllLevel = na
var float slsLevel = na
var TrailTPstep = 0
var PlotTrailPos = false
var TrailSignal = false
var GoToPosL = false
var GoToPosS = false
// Backtest Long ===================
tplLevel := na
sllLevel := na
if long_
if longCond
if strategy.position_size < 0
strategy.cancel_all()
strategy.close_all(comment = "Close short", alert_message =
i_alert_txt_tp_short)
GoToPosL := true
if strategy.opentrades == 0
strategy.entry('Long', strategy.long, alert_message =
i_alert_txt_entry_long)
TrailSignal := false
TrailTPstep := 0
PlotTrailPos := false
if strategy.position_size > 0
strategy.exit('TP_L', from_entry = 'Long',alert_message =
i_alert_txt_tp_long, comment_loss = "SL long" , comment_profit = "TP Long", limit =
TrailSLContinue ? na : strategy.position_avg_price * (1 + (TakeProfit/100)), stop =
strategy.position_avg_price * (1 - (StopLoss / 100)))
tplLevel := strategy.position_avg_price * (1 + (TakeProfit/100))
sllLevel := strategy.position_avg_price * (1 - (StopLoss / 100))
if GoToPosL and strategy.position_size > 0
GoToPosL := false
//if GoToPosL and (strategy.opentrades == 0 or strategy.position_size < 0)
// GoToPosL := false
// strategy.entry('Long', strategy.long, alert_message = i_alert_txt_entry_long)
// TrailSignal := false
// TrailTPstep := 0
// PlotTrailPos := false
// Backtest Short ===================
tpsLevel := na
slsLevel := na
if short_
if shortCond
if strategy.position_size > 0
strategy.cancel_all()
strategy.close_all(comment = "Close long", alert_message =
i_alert_txt_tp_long)
GoToPosS := true
if strategy.opentrades == 0
strategy.entry('Short', strategy.short, alert_message =
i_alert_txt_entry_short)
TrailSignal := false
TrailTPstep := 0
PlotTrailPos := false
if strategy.position_size < 0
strategy.exit('TP_S', from_entry = 'Short', alert_message =
i_alert_txt_tp_short,comment_loss = "SL Short" , comment_profit = "TP Short", limit
= TrailSLContinue ? na : strategy.position_avg_price * (1 - (TakeProfit/100)), stop
= strategy.position_avg_price * (1 + (StopLoss / 100)))
tpsLevel := strategy.position_avg_price * (1 - (TakeProfit/100))
slsLevel := strategy.position_avg_price * (1 + (StopLoss / 100))
if GoToPosS and strategy.position_size < 0
GoToPosS := false
//if GoToPosS and (strategy.opentrades == 0 or strategy.position_size > 0)
// GoToPosS := false
// strategy.entry('Short', strategy.short, alert_message =
i_alert_txt_entry_short)
// TrailSignal := false
// TrailTPstep := 0
// PlotTrailPos := false
//Price plots ----------------------
plot(strategy.position_size > 0 and showLines ? tplLevel : na, title='Long TP ',
style=plot.style_cross, color=color.new(color.lime, 0), linewidth=1)
plot(strategy.position_size > 0 and showLines and TrailSignal == false ? sllLevel :
na, title='Long main SL ', style=plot.style_cross, color=color.blue, linewidth=1)
plot(strategy.position_size < 0 and showLines ? tpsLevel : na, title='Short TP ',
style=plot.style_cross, color=color.new(#ff3b3b, 0), linewidth=1)
plot(strategy.position_size < 0 and showLines and TrailSignal == false ? slsLevel :
na, title='Short main SL ', style=plot.style_cross, color=color.blue, linewidth=1)
//plot
plotshape(longCond and (strategy.opentrades == 0 or strategy.position_size < 0),
title='Long', style=shape.triangleup, location=location.belowbar,
color=color.new(color.blue, 0), size=size.small, text='',
textcolor=color.new(color.white, 0))
plotshape(shortCond and (strategy.opentrades == 0 or strategy.position_size > 0),
title='Short', style=shape.triangledown, location=location.abovebar,
color=color.new(color.red, 0), size=size.small, text='',
textcolor=color.new(color.white, 0))
// Trail SL/TP =========================
var float TrailPricePart = 0.
var float TrailSLPrice = 0.
var float TrailSLLastPrice = 0.
var line TrailLine = na
WickSLcalc = false
PullbackSecure = false
var float SecureTrailPrice = 0.
//Long
if useTrailSL and strategy.position_size > 0
if TrailSteps == 2
TrailPricePart := (strategy.position_avg_price * (1 +
((TakeProfit/100)/2))) - strategy.position_avg_price
if TrailSignal == false
TrailSLPrice := strategy.position_avg_price * (1 +
((TakeProfit/100)/2))
if PlotTrailPos == false
if showLines
line.new(bar_index,TrailSLPrice,bar_index+ExtendTrailLines,TrailSLPrice,color =
color.green,width = 1)
PlotTrailPos := true
if TrailSteps == 3
TrailPricePart := (strategy.position_avg_price * (1 +
((TakeProfit/100)/3))) - strategy.position_avg_price
if TrailSignal == false
TrailSLPrice := strategy.position_avg_price * (1 +
((TakeProfit/100)/3))
if PlotTrailPos == false
if showLines
line.new(bar_index,TrailSLPrice,bar_index+ExtendTrailLines,TrailSLPrice,color =
color.green,width = 1)
line.new(bar_index,TrailSLPrice+TrailPricePart,bar_index+ExtendTrailLines,TrailSLPr
ice+TrailPricePart,color = color.green,width = 1)
PlotTrailPos := true
if close > (high - TrailPricePart)
WickSLcalc := true
if TrailSignal and usePBsecure
if low < (SecureTrailPrice - (((SecureTrailPrice - (SecureTrailPrice -
TrailPricePart))/100) * PBThreshold))
PullbackSecure := true
if PullbackSecure and close >= SecureTrailPrice and usePBsecure
strategy.close("Long", comment = "Secure TP long", alert_message =
i_alert_txt_tp_long)
if useWicksSL and WickSLcalc and LadderTrail ? high > TrailSLPrice : close >
TrailSLPrice
TrailSignal := true
if useWicksSL and WickSLcalc and LadderTrail ? high > TrailSLPrice : close >
TrailSLPrice
if LadderTrail
if useClosePriceForTrailTP
TrailSLLastPrice := useWicksSL ? high - TrailPricePart : close -
TrailPricePart
else
TrailSLLastPrice := useWicksSL ? high - TrailPricePart :
TrailSLPrice - TrailPricePart
else
TrailSLLastPrice := TrailSLPrice
strategy.cancel_all()
if useTrailTP
if TrailTPstep == 0
strategy.close("Long", comment = "trail TP long", qty_percent = 33,
alert_message = i_alert_txt_trailTP_long)
SecureTrailPrice := TrailSLPrice
TrailTPstep := 1
else
if TrailTPstep == 1 and TrailSteps == 3
strategy.close("Long", comment = "trail TP long", qty_percent =
50, alert_message = i_alert_txt_trailTP2_long)
SecureTrailPrice := TrailSLPrice
TrailTPstep := 2
TrailSLPrice := TrailSLPrice + TrailPricePart
strategy.exit('TSL_L', from_entry = 'Long', alert_message =
i_alert_txt_tp_long, comment_profit = "TP Long", comment_loss = "trail SL long",
limit = TrailSLContinue ? na : strategy.position_avg_price * (1 +
(TakeProfit/100)), stop = TrailSLLastPrice)
plot(strategy.position_size > 0 and TrailSignal and showLines ? TrailSLLastPrice :
na, title='Long trail SL ', style=plot.style_cross, color=color.new(color.blue, 0),
linewidth=1)
//Short
if useTrailSL and strategy.position_size < 0
if TrailSteps == 2
TrailPricePart := strategy.position_avg_price -
(strategy.position_avg_price * (1 - ((TakeProfit/100)/2)))
if TrailSignal == false
TrailSLPrice := strategy.position_avg_price * (1 -
((TakeProfit/100)/2))
if PlotTrailPos == false
if showLines
line.new(bar_index,TrailSLPrice,bar_index+ExtendTrailLines,TrailSLPrice,color =
color.red,width = 1)
PlotTrailPos := true
if TrailSteps == 3
TrailPricePart := strategy.position_avg_price -
(strategy.position_avg_price * (1 - ((TakeProfit/100)/3)))
if TrailSignal == false
TrailSLPrice := strategy.position_avg_price * (1 -
((TakeProfit/100)/3))
if PlotTrailPos == false
if showLines
line.new(bar_index,TrailSLPrice,bar_index+ExtendTrailLines,TrailSLPrice,color =
color.red,width = 1)
line.new(bar_index,TrailSLPrice-
TrailPricePart,bar_index+ExtendTrailLines,TrailSLPrice-TrailPricePart,color =
color.red,width = 1)
PlotTrailPos := true
if close < (low + TrailPricePart)
WickSLcalc := true
if TrailSignal and usePBsecure
if high > (SecureTrailPrice + ((((SecureTrailPrice + TrailPricePart) -
SecureTrailPrice)/100) * PBThreshold))
PullbackSecure := true
if PullbackSecure and close <= SecureTrailPrice and usePBsecure
strategy.close("Short", comment = "Secure TP short", alert_message =
i_alert_txt_tp_short)
if useWicksSL and WickSLcalc and LadderTrail ? low < TrailSLPrice : close <
TrailSLPrice
TrailSignal := true
if useWicksSL and WickSLcalc and LadderTrail ? low < TrailSLPrice : close <
TrailSLPrice
if LadderTrail
if useClosePriceForTrailTP
TrailSLLastPrice := useWicksSL ? low + TrailPricePart : close +
TrailPricePart
else
TrailSLLastPrice := useWicksSL ? low + TrailPricePart :
TrailSLPrice + TrailPricePart
else
TrailSLLastPrice := TrailSLPrice
strategy.cancel_all()
if useTrailTP
if TrailTPstep == 0
strategy.close("Short", comment = "trail TP short", qty_percent =
33, alert_message = i_alert_txt_trailTP_short)
SecureTrailPrice := TrailSLPrice
TrailTPstep := 1
else
if TrailTPstep == 1 and TrailSteps == 3
strategy.close("Short", comment = "trail TP short", qty_percent
= 50, alert_message = i_alert_txt_trailTP2_short)
SecureTrailPrice := TrailSLPrice
TrailTPstep := 2
TrailSLPrice := TrailSLPrice - TrailPricePart
strategy.exit('TSL_S', from_entry = 'Short', alert_message =
i_alert_txt_tp_short, comment_profit = "TP Short", comment_loss = "trail SL short",
limit = TrailSLContinue ? na : strategy.position_avg_price * (1 -
(TakeProfit/100)), stop = TrailSLLastPrice)
plot(strategy.position_size < 0 and TrailSignal and showLines ? TrailSLLastPrice :
na, title='Short trail SL ', style=plot.style_cross, color=color.new(color.blue,
0), linewidth=1)