Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SMT-CR Strategy

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

//@promuckaj

//@version=5
strategy("SMT-CR scalp [promuckaj]", "SMT-CR scalp [promuckaj]", overlay=true,
default_qty_type=strategy.cash, default_qty_value=15, initial_capital = 15,
max_labels_count = 500, max_lines_count = 500)

useHA = input(false, "Use HeikinAshi for indicators")

// HeikinAshi candles
ha_open =
request.security(ticker.heikinashi(syminfo.tickerid),timeframe.period,open,lookahea
d = barmerge.lookahead_off, gaps = barmerge.gaps_off)
ha_close =
request.security(ticker.heikinashi(syminfo.tickerid),timeframe.period,close,lookahe
ad = barmerge.lookahead_off, gaps = barmerge.gaps_off)
ha_high =
request.security(ticker.heikinashi(syminfo.tickerid),timeframe.period,high,lookahea
d = barmerge.lookahead_off, gaps = barmerge.gaps_off)
ha_low =
request.security(ticker.heikinashi(syminfo.tickerid),timeframe.period,low,lookahead
= barmerge.lookahead_off, gaps = barmerge.gaps_off)

_open = open
_close = close
_high = high
_low = low
if useHA
_open := ha_open
_close := ha_close
_high := ha_high
_low := ha_low

// Pivot points ---------------------------------------


HLsource = input.string(defval='Close', title='Source for H/L Points',
options=['Close', 'High/Low'],group="Swing points for divergences")
HLprd = input.int(defval=4, title='Pivot Period', minval=1, maxval=100,group="Swing
points for divergences")
showDiv = input(true, "Show divergences on chart", group="Swing points for
divergences")
LDivColor = input.color(color.silver, "Color of lines", group="Swing points for
divergences")

float ph = 0.
float pl = 0.

ph := ta.pivothigh(HLsource == 'Close' ? _close : _high, HLprd, HLprd)


pl := ta.pivotlow(HLsource == 'Close' ? _close : _low, HLprd, HLprd)

// Keep values and positions of pivot H/L points in the arrays


var ph_positions = array.new_int(20, 0)
var pl_positions = array.new_int(20, 0)
var ph_vals = array.new_float(20, 0.)
var pl_vals = array.new_float(20, 0.)

// add PHs to the array


if ph
array.unshift(ph_positions, bar_index-HLprd)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > 20
array.pop(ph_positions)
array.pop(ph_vals)

// add PLs to the array


if pl
array.unshift(pl_positions, bar_index-HLprd)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > 20
array.pop(pl_positions)
array.pop(pl_vals)

// RSI ------------------------------------------------
rsiLengthInput = input.int(11, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(ohlc4, "Source", group="RSI Settings")

rsiup = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)


rsidown = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = rsidown == 0 ? 100 : rsiup == 0 ? 0 : 100 - (100 / (1 + rsiup / rsidown))
// ----------------------------------------------------

// StochRSI -------------------------------------------
useStoch = input(false, "Use Stoch RSI instead of classic RSI", group = "Stoch
RSI")
smoothK = input.int(3, "K", minval=1, group = "Stoch RSI")
smoothD = input.int(3, "D", minval=1, group = "Stoch RSI")
lengthRSI = input.int(14, "RSI Length", minval=1, group = "Stoch RSI")
lengthStoch = input.int(14, "Stochastic Length", minval=1, group = "Stoch RSI")
stochsrc = input(close, title="RSI Source", group = "Stoch RSI")
rsi1 = ta.rsi(stochsrc, lengthRSI)
stochk = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
stochd = ta.sma(stochk, smoothD)
// ----------------------------------------------------

// Check for divergences


var BullDivergenceOK = false
var BearDivergenceOK = false
checkRSI = rsi
if useStoch
checkRSI := stochd

Ldiv = false
Hdiv = false

if array.get(pl_vals,0) < array.get(pl_vals,1) and checkRSI[bar_index -


array.get(pl_positions,0)] > checkRSI[bar_index - array.get(pl_positions,1)] and
checkRSI > checkRSI[bar_index - array.get(pl_positions,0)] and (checkRSI[HLprd] <
checkRSI[HLprd+1] or checkRSI[HLprd+1] < checkRSI[HLprd+2]) and pl
Ldiv := true
if showDiv
line.new(bar_index[(array.get(pl_positions,0)-array.get(pl_positions,1))]-
HLprd,array.get(pl_vals,1),bar_index[HLprd],array.get(pl_vals,0),color =
LDivColor,width = 1)
if array.get(ph_vals,0) > array.get(ph_vals,1) and checkRSI[bar_index -
array.get(ph_positions,0)] < checkRSI[bar_index - array.get(ph_positions,1)] and
checkRSI < checkRSI[bar_index - array.get(ph_positions,0)] and (checkRSI[HLprd] >
checkRSI[HLprd+1] or checkRSI[HLprd+1] > checkRSI[HLprd+2]) and ph
Hdiv := true
if showDiv
line.new(bar_index[(array.get(ph_positions,0)-array.get(ph_positions,1))]-
HLprd,array.get(ph_vals,1),bar_index[HLprd],array.get(ph_vals,0),color =
LDivColor,width = 1)

var LastDiv = ""


if Ldiv
LastDiv := "Bullish"
if Hdiv
LastDiv := "Bearish"

// Smoothed HeikinAshi --------------------------------


showSMHA = input(true, "Show Smoothed HA on the chart", group = "Smoothed
HeikinAshi")
smhalen=input(7, "Length", group = "Smoothed HeikinAshi")
smhalen2=input(12, "Length 2", group = "Smoothed HeikinAshi")
// SMHA 1
smhao=ta.ema(_open,smhalen)
smhac=ta.ema(_close,smhalen)
smhah=ta.ema(_high,smhalen)
smhal=ta.ema(_low,smhalen)

var smhahaopen = 0.
smhahaclose = (smhao+smhah+smhal+smhac)/4
smhahaopen := na(smhahaopen[1]) ? (smhao + smhac)/2 : (smhahaopen[1] +
smhahaclose[1]) / 2
smhahahigh = math.max (smhah, math.max(smhahaopen,smhahaclose))
smhahalow = math.min (smhal, math.min(smhahaopen,smhahaclose))

smhao2=ta.ema(smhahaopen, smhalen)
smhac2=ta.ema(smhahaclose, smhalen)
smhah2=ta.ema(smhahahigh, smhalen)
smhal2=ta.ema(smhahalow, smhalen)

// SMHA 2
smhao21=ta.ema(_open,smhalen2)
smhac21=ta.ema(_close,smhalen2)
smhah21=ta.ema(_high,smhalen2)
smhal21=ta.ema(_low,smhalen2)

var smhahaopen2 = 0.
smhahaclose2 = (smhao21+smhah21+smhal21+smhac21)/4
smhahaopen2 := na(smhahaopen2[1]) ? (smhao21 + smhac21)/2 : (smhahaopen2[1] +
smhahaclose2[1]) / 2
smhahahigh2 = math.max (smhah21, math.max(smhahaopen2,smhahaclose2))
smhahalow2 = math.min (smhal21, math.min(smhahaopen2,smhahaclose2))

smhao22=ta.ema(smhahaopen2, smhalen2)
smhac22=ta.ema(smhahaclose2, smhalen2)
smhah22=ta.ema(smhahahigh2, smhalen2)
smhal22=ta.ema(smhahalow2, smhalen2)

smhacol=smhao2>smhac2 ? color.red : color.lime


//plotcandle(showSMHA ? smhao2 : na, showSMHA ? smhah2 : na, showSMHA ? smhal2 :
na, showSMHA ? smhac2 : na, title="heikin smoothed", color=smhacol)

plot(showSMHA ? smhac2 : na, 'SMHA 1', linewidth=2, color=smhacol)


plot(showSMHA ? smhac22 : na, 'SMHA 2', linewidth=2, color=smhacol)

// SSL chanel -------------------------------


showSSL = input(false, "Show SSL channel on the chart", group = "SSL Channel")
ssllen = input.int(35, title='SSL Channel Length', minval=1, group = "SSL Channel")
smaHigh = ta.sma(_high, ssllen)
smaLow = ta.sma(_low, ssllen)
var float Hlv = na
Hlv := _close > smaHigh ? 1 : _close < smaLow ? -1 : nz(Hlv[1])
sslDown = Hlv < 0 ? smaHigh : smaLow
sslUp = Hlv < 0 ? smaLow : smaHigh

plot(showSSL ? sslDown : na, title='SSL Down', linewidth=2,


color=color.new(color.red, 0))
plot(showSSL ? sslUp : na, title='SSL Up', linewidth=2, color=color.new(color.lime,
0))
//--------------------------------------------

// Heatmap Volume -----------------------


thresholdHigh = input.float(2.5, title='High Volume Threshold', step = 0.1, group =
"Heatmap Volume")
thresholdMedium = input.float(1, title='Medium Volume Threshold', step = 0.1, group
= "Heatmap Volume")
volumeLength = input(20, title='Volume MA Length', group = "Heatmap Volume")

volumeMean = ta.sma(volume, volumeLength)


volumeStd = ta.stdev(volume, volumeLength)
stdBar = (volume - volumeMean) / volumeStd

// Define Volume Filter


volumeFilter = false
if stdBar > thresholdMedium or stdBar > thresholdHigh
volumeFilter := true
//---------------------------------------------

// Price Volume Trend --------------------------------------


//usePVTdiv = input(false, "Use PVT for divergence instead of RSI/StochRSI", group
= "Price Volume Trend")
PVTsignalType = input.string("SMA", "Signal Smoothing Type", options=["EMA",
"SMA"], group = "Price Volume Trend")
PVTsignalLength = input.int(21, "Signal Smoothing Length", group = "Price Volume
Trend")
PVTsrc = input(close,"Source", group = "Price Volume Trend")

pvtsignal = PVTsignalType == "EMA" ? ta.ema(ta.pvt, PVTsignalLength) :


ta.sma(ta.pvt, PVTsignalLength)

PVTbuyAlert = ta.crossover(ta.pvt, pvtsignal)


PVTsellAlert = ta.crossunder(ta.pvt, pvtsignal)

PVTbull = false
PVTbear = false

if ta.pvt > pvtsignal


PVTbull := true
if ta.pvt < pvtsignal
PVTbear := true
//----------------------------------------------------------

// BoS ------------------------------------------
showBOS = input(false, "Show BoS on the chart", group = "BoS (break of structure)")
var LastLowSWPoint = 0.
var LasthighSWPoint = 0.
var LastLowSWPoint1 = 0.
var LasthighSWPoint1 = 0.
var LastLowSWPointBroken = false
var LasthighSWPointBroken = false
var LastHighSWPointBar = 0
var LastLowSWPointBar = 0

BoSbull = false
BoSbear = false

if _high <= _high[2] and _high[1] < _high[2] and _high[3] <= _high[2] and _high[4]
<= _high[2]
LasthighSWPoint1 := LasthighSWPoint
LasthighSWPoint := _high[2]
LastHighSWPointBar := bar_index-2
LasthighSWPointBroken := false
if _low >= _low[2] and _low[1] > _low[2] and _low[3] >= _low[2] and _low[4] >=
_low[2]
LastLowSWPoint1 := LastLowSWPoint
LastLowSWPoint := _low[2]
LastLowSWPointBar := bar_index-2
LastLowSWPointBroken := false

if _close > LasthighSWPoint and LasthighSWPoint > 0 and LasthighSWPointBroken ==


false
LasthighSWPointBroken := true
if showBOS
line.new(LastHighSWPointBar,LasthighSWPoint,bar_index,LasthighSWPoint,
color = color.green, style = line.style_dotted)
if _close < LastLowSWPoint and LastLowSWPoint > 0 and LastLowSWPointBroken == false
LastLowSWPointBroken := true
if showBOS
line.new(LastLowSWPointBar,LastLowSWPoint,bar_index,LastLowSWPoint, color =
color.red, style = line.style_dotted)

if _close > LasthighSWPoint and LasthighSWPointBroken


BoSbull := true
if _close < LastLowSWPoint and LastLowSWPointBroken
BoSbear := true
//-------------------------------------------------------

//BACKTESTING inputs -------------------------


TakeProfit = input.float(2.3, title='Take Profit', minval=0.1, step=0.1,
group='Take Profit / Stop Loss')
sl0 = input.float(2, title='Stop loss', minval=0.1, step=0.1, group='Take Profit /
Stop Loss')

//DATE RANGE FILTER


i_tradeDirection = input.string(title='Trade Direction',
defval=strategy.direction.all, options=[strategy.direction.all,
strategy.direction.long, strategy.direction.short], group='Trade Filters')
strategy.risk.allow_entry_in(i_tradeDirection)
i_startTime = input.time(defval=timestamp('01 Jan 2020 00:00 +0000'), title='Start
Time', group='Trade Filters')
i_endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End
Time', group='Trade Filters')
inDateRange = time >= i_startTime and time <= i_endTime

//BACKTESTING inputs -----------


showLines = input(true, "Show TP/SL lines", group='BACKTEST')
ExtendTrailLines = input.int(5, 'Extend trail lines for bars:', minval=1,
group='BACKTEST')
StratVer = input.string("Ver 1", "Strategy algo", options = ["Ver 1","Ver 2","Ver
3"], group='BACKTEST', tooltip = "Ver 1 is original-default one, Ver 2 and 3 is
experimental, based some part on HeikinAshi candles in background, without some
parts for determination the signals (show better % of winrate in some cases with
more trades)")
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")

// STRATEGY ====================
L_Final_condt = false
S_Final_condt = false

if StratVer == "Ver 1"


L_Final_condt := LastDiv == "Bullish" and sslUp > sslDown and volumeFilter and
smhao2 < smhac2 and BoSbull and ta.crossover(smhac2,smhac22)
S_Final_condt := LastDiv == "Bearish" and sslUp < sslDown and volumeFilter and
smhao2 > smhac2 and BoSbear and ta.crossunder(smhac2,smhac22)
else
if StratVer == "Ver 2"
L_Final_condt := LastDiv == "Bullish" and BoSbull and LasthighSWPoint >
LasthighSWPoint1 and ha_close > ha_open and PVTbull
S_Final_condt := LastDiv == "Bearish" and BoSbear and LastLowSWPoint <
LastLowSWPoint1 and ha_close < ha_open and PVTbear
else
L_Final_condt := LastDiv == "Bullish" and volumeFilter and ha_close >
ha_open and (ha_low == ha_open or ha_low[1] == ha_open[1]) and smhao2 < smhac2
S_Final_condt := LastDiv == "Bearish" and volumeFilter and ha_close <
ha_open and (ha_high == ha_open or ha_high[1] == ha_open[1]) and smhao2 > smhac2

var bool longCond = na


var bool shortCond = na

longCond := L_Final_condt
shortCond := S_Final_condt

var float tplLevel = na


var float tpsLevel = na
var TrailTPstep = 0
var PlotTrailPos = false
var TrailSignal = false
var GoToPosL = false
var GoToPosS = false

// Backtest Long ===================


tplLevel := na
if long_ and inDateRange
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 - (sl0 / 100)))
tplLevel := strategy.position_avg_price * (1 + (TakeProfit/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
if short_ and inDateRange
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 + (sl0 / 100)))
tpsLevel := strategy.position_avg_price * (1 - (TakeProfit/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 ? tpsLevel : na, title='Short TP ',
style=plot.style_cross, color=color.new(#ff3b3b, 0), 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(tplLevel and useTrailSL and strategy.position_size > 0 and (close >


strategy.position_avg_price * (1 + (TakeProfit/100))) ? TrailSLPrice : na,
title='Long TSL ', style=plot.style_circles, color=color.new(color.green, 0),
linewidth=1)
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(tpsLevel and useTrailSL and strategy.position_size < 0 and (close <


strategy.position_avg_price * (1 - (TakeProfit/100))) ? TrailSLPrice : na,
title='Short TSL ', style=plot.style_circles, color=color.new(color.red, 0),
linewidth=1)
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)

You might also like