Strategy · Pine Script v6 · On the chart

Strategy Template

by rubenterlouw· code credited to rubenter

A blank strategy template where the author's own entry conditions are meant to be added, with risk controls already coded.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code675
Settings20inputs
LicenceNone statedfile: MPL-2.0
Last update6 months ago21 Apr 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

675 lines of Pine Script v6 from template_v1.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

template_v1.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rubenter

//@version=6

// Welcome trader 
// this is my strategy template that i use for most of my own strategy's.
// place you user settings after line 40
// place your own trade conditions after line 171

//user settings {
//streak loss control 

onoffswitch = input.bool(defval = false, title = "ON/OFF Streak Loss Control", group = "===========⬜STREAK LOSS CONTROL ⬜ ===========",
 tooltip = "ON to switch on Streak Loss Control")
onoffswitchtimeframe = input.timeframe(defval = "1W", title = "Streak Loss Control", group = "===========⬜STREAK LOSS CONTROL ⬜ ===========",
 tooltip = "Skips the (set timeframe) after predeterminant continuous losses")
Streaknr= input.int(defval = 1, title = "Streak Nr.", group = "===========⬜STREAK LOSS CONTROL ⬜ ===========", 
 tooltip = "Stops trading after this many continues losses")

//MAX DRAWDOWN
Maxdrawdown = input.int(defval = 10000, title = "Max Drawdown", group = "===========⬛MAX DRAWDOWN ⬛===========",
 tooltip ="Max loss to be set, based on the graph" , step = 50)

//LONG AND SHORT POSITIONS
onofflong= input.bool(defval = true, title = "ON/OFF Long Position", inline = "onoffpositions", 
 group = "===========🔶LONG AND SHORT POSITIONS🔶=========== ")
onoffshort= input.bool(defval = true, title = "ON/OFF Short Position", inline = "onoffpositions",
 group = "===========🔶LONG AND SHORT POSITIONS🔶=========== ", tooltip = "ON/OFF Long/Short Positions")
allowedhourslong = input.session(defval = "0000-0000", title = "Allowed Hours Long", group =  "===========🔶LONG AND SHORT POSITIONS🔶=========== ", tooltip = "TIME ALLOWED FOR LONG TRADE ENTRIES")
allowedhoursshort = input.session(defval = "0000-0000", title = "Allowed Hours Short", group =  "===========🔶LONG AND SHORT POSITIONS🔶=========== ", tooltip = "TIME ALLOWED FOR SHORT TRADE ENTRIES")




//// insert script inputs 




// end script inputs 

// 1st target [%]
onofflongpartialexit = false
onoffshortpartialexit = false
// stoploss : swing trail percentage 

longexitoptions = input.string(defval= "Percentage Trail", title = "Long Exit Options", options = ["Swing Trail","Percentage Trail","ATR Trail"], tooltip = "Exit options : Swing Trail │ Percentage Trail",group = "======🔷STOPLOSS : SWING TRAIL │ PERCENTAGE │ ATR🔷======")
shortexitoptions = input.string(defval= "Percentage Trail", title = "Short Exit Options", options = ["Swing Trail","Percentage Trail", "ATR Trail"], tooltip = "Exit options : Swing Trail │ Percentage Trail",group = "======🔷STOPLOSS : SWING TRAIL │ PERCENTAGE │ ATR🔷======")
stoptrail =  input.string(defval = "TRAIL STOP", title = "Stop [Static/Trail]", options = ["TRAIL STOP","STATIC STOP"], group = "======🔷STOPLOSS : SWING TRAIL │ PERCENTAGE │ ATR🔷======", tooltip = " Stop Options : TRAIL / STATIC")
// STOP TRAILED[%]
trailintraclosed = input.string(defval = "CLOSED BAR TRAIL", title = "Trail[Intra-Bar / Closed Bar]", options = ["CLOSED BAR TRAIL","INTRA BAR TRAIL"], group = "===========🔷STOP LOSS/TRAILED[%]🔷===========", tooltip = "Trail Options : INTRA BAR / CLOSED BAR")
traillongperc = input.float(defval = 1.5, title = "Trail Long [%]", group = "===========🔷STOP LOSS/TRAILED[%]🔷===========", step = 0.1 )
trailshortperc = input.float(defval = 1.5, title = "Trail Short [%]", group = "===========🔷STOP LOSS/TRAILED[%]🔷===========", step = 0.1)

//STOPLOSS ATR
stoplossatrintraclosed =  input.string(defval = "CLOSED BAR TRAIL", title = "Trail[Intra-Bar / Closed Bar]", options = ["CLOSED BAR TRAIL","INTRA BAR TRAIL"], group = "===========🔷STOP LOSS/TRAILED ATR🔷===========", tooltip = "Trail Options : INTRA BAR / CLOSED BAR")
traillongatr = input.int(defval = 4, title = "Trail Long ATR", group = "===========🔷STOP LOSS/TRAILED ATR🔷===========")
trailshortatr = input.int(defval = 4, title = "Trail Short ATR", group = "===========🔷STOP LOSS/TRAILED ATR🔷===========")


// STOPLOSS SWING Exit
stoplossintraclosed = input.string(defval = "CLOSED BAR STOP", title = "TARGET [Intra-Bar / Closed Bar]", options = ["INTRA-BAR STOP","CLOSED BAR STOP"], group = "===========🟥STOP LOSS/TRAIL SWING EXIT🟥===========", tooltip = "Trail Options : INTRA-BAR / CLOSED")
longexit = input.int(defval = 2, title = "Long Exit : Swing Low Trail", group = "===========🟥STOP LOSS/TRAIL SWING EXIT🟥===========")
shortexit = input.int(defval = 2, title = "Short Exit : Swing High Trail", group = "===========🟥STOP LOSS/TRAIL SWING EXIT🟥===========")
// end user settings}
//strategy settings 










// end position sizing }

//strategy settings 
strategy("Strategy template ", overlay=true, fill_orders_on_standard_ohlc = true, calc_on_every_tick = false, initial_capital = 5000, margin_long = 0, margin_short = 0, default_qty_type = strategy.cash)


// end strategy settings 
// end user inputs 
// 1. costum function for getting arrays 
// getarrays
// define costum function for safely retrieving array value without index OOB errors 
getarrayvalue(float[] array, int idx) =>
    if array.size(array) > idx
        array.get(array, idx)
    else 
        na


getboolarrayvalue(bool[] array, int idx) =>
    if array.size(array) > idx
        array.get(array, idx)
    else 
        false

//2. detecting timeframe for higher and lower timeframes 
// detecting timeframes{

//tfsec1 = timeframe.in_seconds(smapricelongtimeframe) // for SMA price long 
//charttfsec = timeframe.in_seconds("")
//var int tf1highorlow = na 
//if charttfsec > tfsec1 
  //  tf1highorlow := 0 
//if charttfsec <= tfsec1 
  //  tf1highorlow := 1 
 


//timelow1 = tf1highorlow == 0 
//timehigh1 = tf1highorlow == 1 



// 3. counting losing trades{
var cannottrade = 0
var losstreak = 0 
countingcannot = timeframe.in_seconds(onoffswitchtimeframe)
charttfclock = timeframe.in_seconds("")

is_loss = strategy.losstrades > strategy.losstrades[1]
is_win = strategy.wintrades > strategy.wintrades[1]

if is_loss
    losstreak := losstreak + 1 
if is_win
    losstreak := 0 

if losstreak >= Streaknr and losstreak[1] < Streaknr and  onoffswitch == true 
    cannottrade := countingcannot
if cannottrade >0 and barstate.isconfirmed
    cannottrade := cannottrade - charttfclock
cantrade = cannottrade == 0 
// end counting losing trades}


// 4.  max drawdown 
strategy.risk.max_drawdown(value =  Maxdrawdown, type = strategy.cash )
// 5. allowed hours to trade 
InSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
    not na(time(timeframe.period, sessionTime, sessionTimeZone))

isinsessionlong = InSession(allowedhourslong)
isinsessionshort = InSession(allowedhoursshort)



// insert your own conditions and parameters 






// end your own parameters
// Long conditions 

longCondition = close > ta.ema(close,100) and strategy.position_size == 0 

// Shortconditions 
shortCondition = close < ta.ema(close,100) and strategy.position_size == 0 


//trail conditions {
// sell signal 
sellsignallong = false 
sellsignalshort = false 
var partialexitlong = true 
var partialexitshort = true 
var partiallonghit = false 
var partialshorthit = false 
partiallonghitbar = partiallonghit == true 
partialshorthitbar = partialshorthit == true 

// trail % long 
stoptrailconlong = trailintraclosed ==   "CLOSED BAR TRAIL"? close : trailintraclosed ==  "INTRA BAR TRAIL" ? low : na 

float traildislongperc =  1 - (traillongperc /100)

var float percentagetraillong = na 
t_percentagetraillong = open * traildislongperc

if longCondition[1] 
    percentagetraillong := t_percentagetraillong


if partiallonghitbar == true and partiallonghitbar[1] == false
    percentagetraillong := t_percentagetraillong

if t_percentagetraillong > percentagetraillong and percentagetraillong >0 and stoptrail == "TRAIL STOP"
    percentagetraillong := t_percentagetraillong

if stoptrailconlong < percentagetraillong and longexitoptions == "Percentage Trail" and partiallonghit == true 
    sellsignallong := true 

if stoptrailconlong < percentagetraillong and longexitoptions == "Percentage Trail" and onofflongpartialexit == false
    sellsignallong := true 

if strategy.position_size <= 0
    percentagetraillong := na

//trail % short 
float traildisshortperc =  (trailshortperc /100)+1
stoptrailconshort = trailintraclosed ==   "CLOSED BAR TRAIL"? close : trailintraclosed ==  "INTRA BAR TRAIL" ? high : na 
var float percentagetrailshort = na 
t_percentagetrailshort = open * traildisshortperc

if shortCondition[1]
    percentagetrailshort := t_percentagetrailshort

if partialshorthitbar == true and partialshorthitbar[1] == false
    percentagetrailshort := t_percentagetrailshort

if t_percentagetrailshort < percentagetrailshort and percentagetrailshort > 0 and stoptrail == "TRAIL STOP" //and partialshorthit == true 
    percentagetrailshort := t_percentagetrailshort


if stoptrailconshort > percentagetrailshort and shortexitoptions == "Percentage Trail" and partialshorthit == true 
    sellsignalshort := true 

if stoptrailconshort > percentagetrailshort and shortexitoptions == "Percentage Trail" and onoffshortpartialexit == false
    sellsignalshort := true 

if strategy.position_size >= 0
    percentagetrailshort := na


// trail atr 
//Long atr 
var float atrtraillong = na 

t_atrtraillong = open - (ta.atr(traillongatr)[1])

if longCondition[1]
    atrtraillong := t_atrtraillong

if partiallonghitbar == true and partiallonghitbar[1] == false
    atrtraillong := t_atrtraillong

if t_atrtraillong > atrtraillong and atrtraillong >0 and stoptrail == "TRAIL STOP"
    atrtraillong := t_atrtraillong

stoptrailconatrlong = stoplossatrintraclosed ==   "CLOSED BAR TRAIL"? close : stoplossatrintraclosed ==  "INTRA BAR TRAIL" ? low : na 

if stoptrailconatrlong < atrtraillong and  longexitoptions == "ATR Trail" and partiallonghit == true 
    sellsignallong := true 

if stoptrailconatrlong < atrtraillong and  longexitoptions == "ATR Trail" and onofflongpartialexit == false
    sellsignallong := true

if strategy.position_size <= 0
    atrtraillong := na 


//ATR trail short 
var float atrtrailshort = na 

t_atrtrailshort = open + (ta.atr(trailshortatr)[1])

if shortCondition[1]
    atrtrailshort := t_atrtrailshort


if partialshorthitbar == true and partialshorthitbar[1] == false
    atrtrailshort := t_atrtrailshort

if t_atrtrailshort < atrtrailshort and atrtrailshort >0 and stoptrail == "TRAIL STOP"
    atrtrailshort := t_atrtrailshort

stoptrailconatrshort = stoplossatrintraclosed ==   "CLOSED BAR TRAIL"? close : stoplossatrintraclosed ==  "INTRA BAR TRAIL" ? high : na 

if stoptrailconatrshort > atrtrailshort and  shortexitoptions == "ATR Trail" and partialshorthit == true 
    sellsignalshort := true 

if stoptrailconatrshort > atrtrailshort and  shortexitoptions == "ATR Trail" and onoffshortpartialexit == false
    sellsignalshort := true 
 

if strategy.position_size >= 0
    atrtrailshort := na 


//entry price  
var tradeentry = 0.0

if longCondition[1] or shortCondition[1]
    tradeentry := open 

if sellsignallong == true or sellsignalshort == true 
    tradeentry := na 




//trail swing stop 
// trail swing  long 
stoptrailconswinglong = stoplossintraclosed ==   "CLOSED BAR STOP"? close : stoplossintraclosed ==  "INTRA-BAR STOP" ? low : na 
var pivotset = 0.0
T_pivot  = ta.pivotlow(leftbars = longexit, rightbars = longexit) 

if T_pivot > 0 
    pivotset := T_pivot

float traildislongswing =  pivotset//ta.lowest(longexit)

var float swingtraillong = na 
t_swingtraillong = traildislongswing

if longCondition[1] and (low[1] * 0.985) > t_swingtraillong  
    swingtraillong := t_swingtraillong

if longCondition[1] and (low[1] * 0.985) < t_swingtraillong 
    swingtraillong := (low[1] * 0.985)



if t_swingtraillong > swingtraillong and swingtraillong >0 and longexitoptions == "Swing Trail" and stoptrail == "TRAIL STOP" and not longCondition[1] and not longCondition[2]
    swingtraillong := t_swingtraillong



if stoptrailconswinglong < swingtraillong and  longexitoptions == "Swing Trail"
    sellsignallong := true 


if strategy.position_size == 0 and (low[1] * 0.985) > t_swingtraillong  and barstate.isconfirmed
    swingtraillong := t_swingtraillong

if strategy.position_size == 0 and (low[1] * 0.985) < t_swingtraillong  and barstate.isconfirmed
    swingtraillong := (low[1] * 0.985)

if strategy.position_size == 0 
    swingtraillong:= na

//trail swing short 
var pivotsetshort = 0.0
T_pivotshort  = ta.pivothigh(leftbars = shortexit, rightbars = shortexit) 

if T_pivotshort > 0 
    pivotsetshort := T_pivotshort

float traildisshortswing =  pivotsetshort//ta.highest(shortexit)
stoptrailconswingshort = stoplossintraclosed ==   "CLOSED BAR STOP"? close : stoplossintraclosed ==  "INTRA-BAR STOP" ? high : na 
var float swingtrailshort = na 
t_swingtrailshort = traildisshortswing

if shortCondition[1] and (high[1] * 1.015) < t_swingtrailshort  
    swingtrailshort := t_swingtrailshort

if shortCondition[1] and (high[1] * 1.015) > t_swingtrailshort  
    swingtrailshort := (high[1] * 1.015)



if t_swingtrailshort < swingtrailshort and swingtrailshort > 0 and shortexitoptions == "Swing Trail" and stoptrail == "TRAIL STOP" and not shortCondition[1] and not shortCondition[2]
    swingtrailshort := t_swingtrailshort

if stoptrailconswingshort > swingtrailshort and  shortexitoptions == "Swing Trail"
    sellsignalshort := true 

if strategy.position_size == 0 and (high[1] * 1.015) < t_swingtrailshort   and barstate.isconfirmed
    swingtrailshort := t_swingtrailshort

if strategy.position_size == 0 and (high[1] * 1.015) > t_swingtrailshort   and barstate.isconfirmed
    swingtrailshort := (high[1] * 1.015)

if strategy.position_size == 0 
    swingtrailshort:= na 


// other lines when trade 



bgcolor(color = strategy.position_size <0 ? color.new(#4b2323, 30): na )
bgcolor(color = strategy.position_size >0 ? color.new(#0c2b09, 30): na )

if strategy.position_size <= 0 
    swingtraillong := na  

    //longexitoptions := na 
if strategy.position_size >= 0 
    swingtrailshort := na 

   // shortexitoptions := na 
if strategy.position_size == 0 
    tradeentry := na 
// end trail settings }

plot(tradeentry, style = plot.style_linebr, color = color.yellow  )

plot(swingtrailshort, style = plot.style_linebr, color = color.red )

plot(swingtraillong, style = plot.style_linebr, color = color.red )


t_longtrail = longexitoptions == "Percentage Trail" ? percentagetraillong : longexitoptions == "ATR Trail" ? atrtraillong  : na // used to be partialshorthit[2] 
longtrail = partiallonghit[1] == false and onofflongpartialexit == true  ? na :t_longtrail < swingtraillong ? swingtraillong : t_longtrail //// used to be partiallonghit[2] 


t_shorttrail = shortexitoptions == "Percentage Trail" ? percentagetrailshort : shortexitoptions == "ATR Trail" ? atrtrailshort  : na
shorttrail = partialshorthit[1] == false and onoffshortpartialexit == true  ? na :t_shorttrail > swingtrailshort ? swingtrailshort : t_shorttrail


plot(shorttrail, style = plot.style_linebr, color = partialshorthit[1] == false and onoffshortpartialexit == true  ? color.new(color.red,100) : color.purple, linewidth = 2  ) // used to be partialshorthit[2] 

plot(longtrail , style = plot.style_linebr, color = partiallonghit[1] == false and onofflongpartialexit == true  ? color.new(color.green,100) :color.purple, linewidth = 2 )// used to be partiallonghit[2] 





if  high < swingtrailshort and strategy.position_size < 0 
    sellsignalshort := false 


shortswinghit = high > swingtrailshort
longswinghit = low < swingtraillong


// fast entry and swing 

var entryfast = 0.0
if shortCondition and barstate.isconfirmed or longCondition and barstate.isconfirmed
    entryfast := close 

//plot(entrytest)
var fastswinglong = 0.0
if longCondition and (low * 0.985) > t_swingtraillong 
    fastswinglong := t_swingtraillong

if longCondition and (low * 0.985) < t_swingtraillong 
    fastswinglong := (low * 0.985)



var fastswingshort = 0.0 

if shortCondition and (high * 1.015) < t_swingtrailshort  
    fastswingshort := t_swingtrailshort

if shortCondition and (high * 1.015) > t_swingtrailshort  
    fastswingshort := (high * 1.015)





//
float intraswingtrailong = na 
if stoplossintraclosed =="INTRA-BAR STOP"
    intraswingtrailong := swingtraillong

float intraswingtrailshort = na 
if stoplossintraclosed =="INTRA-BAR STOP"
    intraswingtrailshort := swingtrailshort


cantaketrade = false
if (strategy.position_size == 0 and barstate.isconfirmed)[1] //or strategy.position_size == 0 and barstate.isconfirmed
    cantaketrade := true 

//

// long entry/exit

if longCondition and strategy.position_size == 0 and onofflong == true and isinsessionlong and (strategy.closedtrades == 0 or strategy.closedtrades.entry_bar_index(strategy.closedtrades-1) < bar_index) and cantaketrade == true 
    strategy.entry(id ="Long Entry", direction =  strategy.long )//, qty =realpositionlong)
    //alert(message = "Long Entry", freq = alert.freq_all)



// percentagestoplong  
if close <longtrail and strategy.position_size >= 0 and longexitoptions == "Percentage Trail"  and not longCondition[1]  and partiallonghit == true and onofflongpartialexit == true and trailintraclosed =="CLOSED BAR TRAIL" or close <percentagetraillong and strategy.position_size >= 0 and longexitoptions == "Percentage Trail"   and not longCondition[1] and onofflongpartialexit == false and trailintraclosed =="CLOSED BAR TRAIL"
    strategy.close(id = "Long Entry", immediately = true, comment = "% Trail Hit")
    partialexitlong := true 
    partiallonghit := false 






// ATR stop long 
if close < longtrail and strategy.position_size >= 0 and  longexitoptions == "ATR Trail"  and not longCondition[1] and partiallonghit == true and onofflongpartialexit == true and stoplossatrintraclosed == "CLOSED BAR TRAIL" or close <atrtraillong and strategy.position_size >= 0 and  longexitoptions == "ATR Trail"  and not longCondition[1]  and onofflongpartialexit == false and stoplossatrintraclosed == "CLOSED BAR TRAIL"
    strategy.close(id = "Long Entry", immediately = true, comment = "ATR Trail Hit")
    partialexitlong := true 
    partiallonghit := false 



if swingtraillong > close and stoplossintraclosed =="CLOSED BAR STOP"  and not longCondition[1]
    strategy.close(id = "Long Entry", immediately = true, comment = "SL Hit")
    partialexitlong := true 
    partiallonghit := false 


//short entry/exit

if shortCondition and strategy.position_size == 0 and not longCondition and onoffshort == true and isinsessionshort and (strategy.closedtrades == 0 or strategy.closedtrades.entry_bar_index(strategy.closedtrades-1) < bar_index) and cantaketrade == true
    strategy.entry( id = "Short Entry", direction =  strategy.short , comment = "Short Entry")//realposition)






// percentagestoplong  
if close > shorttrail and strategy.position_size <= 0 and shortexitoptions == "Percentage Trail"   and not shortCondition[1] and partialshorthit == true and onoffshortpartialexit == true and trailintraclosed =="CLOSED BAR TRAIL" or close >percentagetrailshort and strategy.position_size <= 0 and shortexitoptions == "Percentage Trail"   and not shortCondition[1] and onoffshortpartialexit == false and trailintraclosed =="CLOSED BAR TRAIL"
    strategy.close(id = "Short Entry", immediately = true, comment = "% Trail Hit")





// ATR stop long 
if close > shorttrail and strategy.position_size <= 0 and  shortexitoptions == "ATR Trail"  and not shortCondition[1] and partialshorthit == true and onoffshortpartialexit == true and stoplossatrintraclosed == "CLOSED BAR TRAIL" or close >atrtrailshort and strategy.position_size <= 0 and  shortexitoptions == "ATR Trail"  and not shortCondition[1] and onoffshortpartialexit == false and stoplossatrintraclosed == "CLOSED BAR TRAIL"
    strategy.close(id = "Short Entry", immediately = true, comment = "ATR Trail Hit")
    partialexitshort := true 
    partialshorthit := false 



if swingtrailshort < close and stoplossintraclosed == "CLOSED BAR STOP" and not shortCondition[1]
    strategy.close(id = "Short Entry", immediately = true, comment = "SL Hit" )
    partialexitshort := true 
    partialshorthit := false 

// new trade entered 
newtrade = (strategy.opentrades > strategy.opentrades[1])


 

// first bar exit test 
var float firstbar1stclosed = na 
var float firstbar1stclosedshort = na 


c_swingexitlong = close < swingtraillong  ? close : not newtrade ? na : na  
c_swingexitshort = close > swingtrailshort  ? close : not newtrade ? na : na 
c_trailexitlong = close < longtrail ? close : not newtrade ? na : na 
c_trailexitshort = close > shorttrail ? close : not newtrade ? na : na 


var float firstbar1stintra = na 
var float firstbar1stintrashort = na 
// intra day 

i_swingexitlong = stoplossintraclosed =="INTRA-BAR STOP" ?  swingtraillong : na 
i_swingexitshort = stoplossintraclosed =="INTRA-BAR STOP" ?  swingtrailshort : na 
i_trailexitlong = trailintraclosed == "INTRA BAR TRAIL" ? longtrail : stoplossatrintraclosed == "INTRA BAR TRAIL" ? longtrail : na 
i_trailexitshort = trailintraclosed == "INTRA BAR TRAIL" ? shorttrail : stoplossatrintraclosed == "INTRA BAR TRAIL" ? shorttrail : na 




// close or intra day 

p_swingexitlong = stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitlong : i_swingexitlong
p_swingexitshort = stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitshort : i_swingexitshort
p_trailexitlongperc = trailintraclosed == "CLOSED BAR TRAIL" ? c_trailexitlong : i_trailexitlong
p_trailexitshortperc = trailintraclosed == "CLOSED BAR TRAIL" ? c_trailexitshort : i_trailexitshort
p_trailexitlongatr = stoplossatrintraclosed == "CLOSED BAR TRAIL" ?  c_trailexitlong : i_trailexitlong
p_trailexitshortatr = stoplossatrintraclosed == "CLOSED BAR TRAIL" ? c_trailexitshort : i_trailexitshort
p_trailexitlong = longexitoptions =="Percentage Trail" ? p_trailexitlongperc : longexitoptions =="ATR Trail" ? p_trailexitlongatr : na
p_trailexitshort = shortexitoptions == "Percentage Trail" ? p_trailexitshortperc : shortexitoptions == "ATR Trail" ? p_trailexitshortatr : na 

p_stoportraillong1stoffperc = 
     longexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_trailexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" ? i_trailexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and not na(c_trailexitlong)     ? c_trailexitlong ://math.max(c_trailexitlong, i_swingexitlong) :
     longexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP"  and na(c_trailexitlong) ? i_swingexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" ? i_trailexitlong : na


p_stoportraillong1stonperc =
     longexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitlong[1] == true ? i_swingexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitlong[1] == false ? i_trailexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" ? i_swingexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and newtrade ? c_swingexitlong :
     longexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and not newtrade ? i_trailexitlong : na 

p_stoportraillong1stoffatr =
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_trailexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" ? i_trailexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and not na(c_trailexitlong)     ? c_trailexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and na(c_trailexitlong) ? i_swingexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" ? i_trailexitlong : na


p_stoportraillong1stonatr =
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitlong[1] == true ? i_swingexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitlong[1] == false ? i_trailexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" ? i_swingexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and newtrade ? c_swingexitlong :
     longexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and not newtrade ? i_trailexitlong : na 

p_stoportrailswinglong = longexitoptions == "Swing Trail" ? i_swingexitlong : na 
trailorstopfirstonofflong =
     onofflongpartialexit == true and longexitoptions == "Percentage Trail" ? p_stoportraillong1stonperc :
     onofflongpartialexit == false and longexitoptions == "Percentage Trail" ? p_stoportraillong1stoffperc : 
     onofflongpartialexit == true and longexitoptions == "ATR Trail" ? p_stoportraillong1stonatr :
     onofflongpartialexit == false and longexitoptions == "ATR Trail" ? p_stoportraillong1stoffatr : 
     longexitoptions == "Swing Trail" ? p_stoportrailswinglong : na
    

// short 
p_stoportrailshort1stoffperc =
     shortexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_trailexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" ? i_trailexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and not na(c_trailexitshort)     ? c_trailexitshort ://and newtrade     ? math.min(c_trailexitshort, i_swingexitshort) :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and na(c_trailexitshort) ? i_swingexitshort ://and not newtrade ? i_swingexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" ? i_trailexitshort : na


p_stoportrailshort1stonperc =
     shortexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitshort[1] == true ? i_swingexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitshort[1] == false ? i_trailexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" ? i_swingexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and newtrade ? c_swingexitshort :
     shortexitoptions == "Percentage Trail" and trailintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and not newtrade ? i_trailexitshort : na 

p_stoportrailshort1stoffatr =
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_trailexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" ? i_trailexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and not na(c_trailexitshort)     ? c_trailexitshort ://and newtrade     ? math.min(c_trailexitshort, i_swingexitshort) :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSstoplossatrintraclosed$0ED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" and na(c_trailexitshort) ? i_swingexitshort ://and not newtrade ? i_swingexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" ? i_trailexitshort : na


p_stoportrailshort1stonatr =
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "CLOSED BAR STOP" ? c_swingexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitshort[1] == true ? i_swingexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "INTRA-BAR STOP" and partialexitshort[1] == false ? i_trailexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "CLOSED BAR TRAIL" and stoplossintraclosed == "INTRA-BAR STOP" ? i_swingexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and newtrade ? c_swingexitshort :
     shortexitoptions == "ATR Trail" and stoplossatrintraclosed == "INTRA BAR TRAIL"  and stoplossintraclosed == "CLOSED BAR STOP" and not newtrade ? i_trailexitshort : na 

p_stoportrailswingshort = shortexitoptions == "Swing Trail" ? p_swingexitshort : na 
//trailorstopfirstonoffshort = 
trailorstopfirstonoffshort = 
     onoffshortpartialexit == true and shortexitoptions == "Percentage Trail" ? p_stoportrailshort1stonperc :
     onoffshortpartialexit == false and shortexitoptions == "Percentage Trail" ? p_stoportrailshort1stoffperc : 
     onoffshortpartialexit == true and shortexitoptions == "ATR Trail" ? p_stoportrailshort1stonatr :
     onoffshortpartialexit == false and shortexitoptions == "ATR Trail" ? p_stoportrailshort1stoffatr :
     shortexitoptions == "Swing Trail" ? p_stoportrailswingshort : na






// intra and first bar close strategy.exit finale 
// long 
strategy.exit(id = "exit stoploss Long",from_entry = "Long Entry", stop = trailorstopfirstonofflong)//firstbarswingclosed)
// short 
strategy.exit(id = "exit stoploss short ",from_entry = "Short Entry", stop = trailorstopfirstonoffshort)//firstbarswingclosed)



// Extra check for backtest
if strategy.position_size > 0 and low <= trailorstopfirstonofflong and not newtrade
    strategy.close("Long Entry", comment="ForcedTrailStoplong")

if strategy.position_size < 0 and high >= trailorstopfirstonoffshort and not newtrade
    strategy.close("Short Entry", comment="ForcedTrailStopshort")

Overview

These include streak loss control that pauses trading for a timeframe after consecutive losses, a maximum drawdown halt, long and short switches, and allowed trading hours. Exits can be a swing, percentage or ATR stop, static or trailing, evaluated on closed bars or intrabar. It contains no entry logic of its own, so it does nothing until conditions are added.

Details

Published by

rubenterlouw on GitHub

Code credit

rubenter, as written in the script's header

Type

Strategy, Pine Script v6

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
ON/OFF Streak Loss Controlboolfalseonoffswitch
Streak Loss Controltimeframe1Wonoffswitchtimeframe
Streak Nr.int1Streaknr
Max Drawdownint10000Maxdrawdown
ON/OFF Long Positionbooltrueonofflong
ON/OFF Short Positionbooltrueonoffshort
Allowed Hours Longsession0000-0000allowedhourslong
Allowed Hours Shortsession0000-0000allowedhoursshort
Long Exit OptionsstringPercentage Traillongexitoptions
Short Exit OptionsstringPercentage Trailshortexitoptions
Stop [Static/Trail]stringTRAIL STOPstoptrail
Trail[Intra-Bar / Closed Bar]stringCLOSED BAR TRAILtrailintraclosed
Show all 20 settings
SettingTypeDefaultVariable
Trail Long [%]float1.5traillongperc
Trail Short [%]float1.5trailshortperc
Trail[Intra-Bar / Closed Bar]stringCLOSED BAR TRAILstoplossatrintraclosed
Trail Long ATRint4traillongatr
Trail Short ATRint4trailshortatr
TARGET [Intra-Bar / Closed Bar]stringCLOSED BAR STOPstoplossintraclosed
Long Exit : Swing Low Trailint2longexit
Short Exit : Swing High Trailint2shortexit
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA
440 stars

This script is an empty strategy template for Pine Script developers. It declares a version 4 strategy named Basic Strategy Boilerplate with the short title Strategy Boilerplate and sets overlay to true so any future plots would appear on the price chart. It d

Strategy v4
Updated 7 years ago · GPL-3.0 GitHub repository of Basic Strategy Boilerplate

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated yesterday · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated yesterday · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers