Strategy · Pine Script v4 · On the chart

Breakout Trend Trading

by hasnocool· code credited to HeWhoMustNotBeNamed

This strategy trades breakouts, pullbacks, and reversals in the chosen direction on the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code366
Settings28inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

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

366 lines of Pine Script v4 from Breakout Trend Trading Strategy - V2.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Breakout Trend Trading Strategy - V2.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Breakout Trend Trading - V2", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
///////////////////////////////////////// Input ////////////////////////////////////////////////////////////////////
exitOnSignal = input(false)
exitStrategyOnRangingCondition = input(title="Exit Strategy when in Range", defval="Disabled", options=["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"])
allowImmediateCompound = input(false)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
tradeType = input(title="Trade Type", defval="all", options=["all", "pullback", "breakout", "reverse", "pullback + breakout"])
displayMode = input(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])
showTrailingStop = input(true)
showTargetLevels = input(true)
showPreviousLevels = input(false)
stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)
compoundMultiplyer = input(4, minval=1, maxval=10, step=0.5)
rangeBars = input(100, step=5)
backtestYears = input(10, minval=1, step=1)
considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")
shortHighLowPeriod = input(100, step=10)
longHighLowPeriod = input(200, step=10)
considerMaAlignment = input(true,"Check recent moving average alignment")
LookbackPeriod = input(300, step=10)
includePartiallyAligned = input(true)
MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
alignmentIndexThreshold = input(50, step=10)
LookbackPeriodPR = input(50, step=10)
considerWeeklySupertrend = input(false)
SupertrendWMult = input(1)
SupertrendWPd = input(26)
considerMonthlySupertrend = input(false)
SupertrendMMult = input(2)
SupertrendMPd = input(6)
//supertrendMult = input(6, minval=1, maxval=10, step=0.5)
//supertrendLength = input(22, minval=1)
//volumelength = input(title="Volume MA Length", defval=20, minval=10, step=10)
//reverseVolumeLength = input(title="Volume MA Length", defval=20, minval=10, step=10)
//volumeMaType = input(title="Volume MA Type", defval="hma", options=["ema", "sma", "hma", "rma", "swma", "vwma", "wma"])
//trendVolumeMarkup = input(15, minval=0, maxval=100, step=5)
//reverseVolumeMarkup = input(25, minval=0, maxval=100, step=5)
//highVolumeMultiplyer = input(5, minval=2, maxval=10, step=1)
//atrlength = input(22, minval=1)
//trendTargetMult = input(1, minval=1, maxval=10, step=0.5)
//reverseTargetMult = input(1, minval=1, maxval=10, step=0.5)
//highBreakoutMult = input(2, minval=2, maxval=10, step=1)
//trendValueMarkup = input(15, minval=0, maxval=100, step=5)
//reverseValueMarkup = input(30, minval=0, maxval=100, step=5)
//stopMultFactor = input(1, minval=0.5, maxval=10, step=0.5)
//considerMaSupertrend = input(true)
//source = input(ohlc4)
//MaTypeMa = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
//MaLengthMa = input(10, step=10)
//supertrendLengthMa = input(10, step=10)
//supertrendMultMa = input(1, step=1)
considerMaSupertrend = true
source = ohlc4
MaTypeMa = "sma"
MaLengthMa = 10
supertrendLengthMa = 10
supertrendMultMa = 1
ignoreReverseBreakout = true
considerYearlyHighLow = true
considerOpenCloseBreakout = false
supertrendMult = 6
supertrendLength = 22
volumelength = 20
reverseVolumeLength = 20
volumeMaType = "hma"
trendVolumeMarkup = 15
reverseVolumeMarkup = 25
highVolumeMultiplyer = 5
atrlength = 22
trendTargetMult = 1
reverseTargetMult = 1
highBreakoutMult = 2
trendValueMarkup = 15
reverseValueMarkup = 30
stopMultFactor = 1
///////////////////////////// Display mode calculation ////////////////////////////////////////////////
f_getDisplayModeVeriables(displayMode)=>
    bool showTargets = false
    bool showChannel = false
    bool showTargetStops = false
    bool showUpChannel = false
    bool showDownChannel = false
    if(displayMode == "Targets")
        showTargets := true
    if(displayMode == "Target Channel")
        showChannel := true
    if(displayMode == "Target with Stops")
        showTargetStops := true
    if(displayMode == "Up Channel")
        showUpChannel := true
    if(displayMode == "Down Channel")
        showDownChannel := true
    [showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel]
f_getRangeExitStrategy(exitStrategyOnRangingCondition)=>
    exitOnSignalWhenInRange = false
    exitOnTrailingStopWhenInRange = false
    exitOnBB = false
    if(exitStrategyOnRangingCondition == "ExitOnSignal")
        exitOnSignalWhenInRange := true
    if(exitStrategyOnRangingCondition == "TrailStopLoss")
        exitOnTrailingStopWhenInRange := true
    if(exitStrategyOnRangingCondition == "BollingerBands")
        exitOnBB := true
    [exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB]
    
///////////////////////////// Get Price breakout values ////////////////////////////////////////////////
f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)=>
    trendBreakout = false
    if(abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout)
        trendBreakout := true
    
    reverseBreakout = false
    if(abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout)
        reverseBreakout := true
        
    highBreakout = false
    if(abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout)
        highBreakout:=true
        
    [trendBreakout, reverseBreakout, highBreakout]
///////////////////////////// Get Volume breakout values ////////////////////////////////////////////////
f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMarkup)=>
    vmaMarkup = vma * (1+(trendVolumeMarkup/100))
    vmaReverseMarkup = vmareverse * (1+(reverseVolumeMarkup/100))
    vmaHighVolumeMarkup = vma * highVolumeMarkup
    trendVolumeBreakout = vmaMarkup <  volume or na(volume)
    stopVolumeBreakout = vmaReverseMarkup <  volume or na(volume)
    highVolumeBreakout = vmaHighVolumeMarkup < volume and not na(volume)
    [trendVolumeBreakout, stopVolumeBreakout, highVolumeBreakout]
//////////////////////////////////// Get Candle color //////////////////////////////////////////////////
f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout,  highVolumeBreakout)=>
    barState = 0
    if(close > close[1] and ( (dir == -1 and trendBreakout and trendVolumeBreakout) or (dir == 1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
        barState := 1
    if(close < close[1] and ( (dir == 1 and trendBreakout and trendVolumeBreakout) or (dir == -1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
        barState := -1
    barState
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)=>
    diff = max(high-low, max(abs(high-close[1]), abs(low-close[1])))
    upTarget = (barState == 1) ? high + ((dir==-1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
    downTarget = (barState == -1) ? low - ((dir==1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
    stopUpTarget = (barState == 1) ? low - atr * stopMultFactor : na
    stopDownTarget = (barState == -1) ? high + atr * stopMultFactor : na
    lastBreakout = barState
    lastBreakout:= lastBreakout == 0? nz(lastBreakout[1], 0): lastBreakout
    [upTarget,stopUpTarget,downTarget,stopDownTarget,lastBreakout]
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)=>
    upLine = upTarget
    downLine = downTarget
    stopUpLine = stopUpTarget
    stopDownLine = stopDownTarget
    upLine := na(upLine) ? nz(upLine[1],na) : upLine
    downLine := na(downLine) ? nz(downLine[1],na) : downLine
    stopUpLine := na(stopUpLine) ? nz(stopUpLine[1],na) : stopUpLine
    stopDownLine := na(stopDownLine) ? nz(stopDownLine[1],na) : stopDownLine
    [upLine,stopUpLine,downLine,stopDownLine]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
    yhigh = security(syminfo.tickerid, '12M', high[1]) 
    ylow = security(syminfo.tickerid, '12M', low[1]) 
    yhighlast = yhigh[365]
    ylowlast = ylow[365]
    yhighllast = yhigh[2 * 365]
    ylowllast = ylow[2 * 365]
    
    yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
    yearlyHighCondition = (  (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
    yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
    yearlyLowCondition = (  (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
    
    label_x = time+(60*60*24*1000*1)
    [yearlyHighCondition,yearlyLowCondition]
f_getMovingAverage(source, MAType, length)=>
    ma = sma(source, length)
    if(MAType == "ema")
        ma := ema(source,length)
    if(MAType == "hma")
        ma := hma(source,length)
    if(MAType == "rma")
        ma := rma(source,length)
    if(MAType == "vwma")
        ma := vwma(source,length)
    if(MAType == "wma")
        ma := wma(source,length)
    ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
    ma5 = f_getMovingAverage(close,MAType,5)
    ma10 = f_getMovingAverage(close,MAType,10)
    ma20 = f_getMovingAverage(close,MAType,20)
    ma30 = f_getMovingAverage(close,MAType,30)
    ma50 = f_getMovingAverage(close,MAType,50)
    ma100 = f_getMovingAverage(close,MAType,100)
    ma200 = f_getMovingAverage(close,MAType,200)
    upwardScore = 0
    upwardScore := close > ma5? upwardScore+1:upwardScore
    upwardScore := ma5 > ma10? upwardScore+1:upwardScore
    upwardScore := ma10 > ma20? upwardScore+1:upwardScore
    upwardScore := ma20 > ma30? upwardScore+1:upwardScore
    upwardScore := ma30 > ma50? upwardScore+1:upwardScore
    upwardScore := ma50 > ma100? upwardScore+1:upwardScore
    upwardScore := ma100 > ma200? upwardScore+1:upwardScore
    
    upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
    downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
    upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
f_supertrendOnMa(source, MaType, MaLength, supertrendLength, supertrendMult)=>
    supertrendDistance = supertrendMult * atr(supertrendLength)
    
    ma = f_getMovingAverage(source,MaType, MaLength)
    longStop = ma - supertrendDistance
    longStopPrev = nz(longStop[1], longStop)
    longStop := ma > longStopPrev ? max(longStop, longStopPrev) : longStop
    
    shortStop = ma + supertrendDistance
    shortStopPrev = nz(shortStop[1], shortStop)
    shortStop := ma < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
    
    dir = 1
    dir := nz(dir[1], dir)
    dir := dir == -1 and ma > shortStopPrev ? 1 : dir == 1 and ma < longStopPrev ? -1 : dir
    supertrend =  dir==1 ? longStop: shortStop
    [supertrend, ma, dir]
    
//////////////////////////////////// Calculate Buy Sell signals //////////////////////////////////////////////////
f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)=>
    greenBreakout = (lastBreakout > 0) or ignoreReverseBreakout
    redBreakout = (lastBreakout < 0) or ignoreReverseBreakout
    buySignal = dir==-1? false : (crossover(low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(low, stopDownLine[1]) and redBreakout) 
    stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1]))
    sellSignal = dir==1? false : (crossunder(high, downLine[1])  and redBreakout and close < upLine[1]) or (crossunder(high, stopUpLine[1]) and greenBreakout)
    stopSellSignal = (crossover(dir==1?close:high, upLine[1]) or crossover(dir==1?close:high, stopDownLine[1]))
    [buySignal,stopBuySignal,sellSignal,stopSellSignal]
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
    newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
    newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
    [newHigh,newLow]
    
//////////////////////////////////// Calculate Trade Flags /////////////////////////////////////////////////////
f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)=>
    buyPrerequisites = inDateRange and yearlyHighCondition and newHigh and maHigh
    sellPrerequisites = inDateRange and yearlyLowCondition and newLow and maLow
    buyEntry = buyPrerequisites? (dir == -1 and barState != 0) ? true : buySignal : false
    sellEntry = sellPrerequisites? dir == 1 and barState != 0 ? true : sellSignal : false
    stopBuyEntry = stopBuySignal and barState != 1 and inDateRange
    stopSellEntry = stopSellSignal and barState != -1 and inDateRange
    reverse = (buySignal or sellSignal and (buyPrerequisites or sellPrerequisites)) and (tradeType == "all" or tradeType == "reverse")
    breakout = ((buyPrerequisites and  dir == -1 and barState == 1) or (sellPrerequisites and dir == 1 and barState == -1)) and (tradeType == "all" or tradeType == "breakout" or tradeType == "pullback + breakout")
    pullback = ((buyPrerequisites and dir == -1 and barState == -1) or (sellPrerequisites and dir == 1 and barState == 1)) and (tradeType == "all" or tradeType == "pullback" or tradeType == "pullback + breakout")
    [buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse]
//////////////////////////////////// Calculate trailing stop //////////////////////////////////////////////////
f_calculateTrailingStop(stop)=>
    strategy.position_size > 0? (stop > stop[1]? stop : stop[1]) : strategy.position_size < 0 ? (stop < stop[1]? stop : stop[1]) : stop
//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////
f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)=>
    target = reverse ?  close: breakout and buyEntry ? upLine : breakout and sellEntry? downLine: buyEntry and pullback ? stopDownLine : sellEntry and pullback? stopUpLine : strategy.position_size > 0 ? low : strategy.position_size < 0? high : close
    buyStop = target - (stopMultiplyer * atr)
    sellStop = target + (stopMultiplyer * atr)
    range = false
    range := range[1] and exitOnBB? close > buyStop[1] and close < sellStop[1]:strategy.position_size != 0 and buyStop[1] == buyStop[rangeBars+1] and sellStop[1] == sellStop[rangeBars+1] 
    if(range and exitOnBB)
        buyStop := buyStop[1]
        sellStop := sellStop[1]
    else if(barState > 0 or strategy.position_size > 0)
        buyStop := target - (stopMultiplyer * atr)
        sellStop := target + (compoundMultiplyer * atr)
        buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop
        sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]): (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop
    else if(barState < 0 or strategy.position_size < 0)
        buyStop := target - (compoundMultiplyer * atr)
        sellStop := target + (stopMultiplyer * atr)
        sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]) : (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop
        buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop
    [target, buyStop, sellStop, range]
    
//////////////////////////////////// Draw Lines with labels //////////////////////////////////////////////////
f_drawLinesWithLabels(target, lbl, linecolor)=>
    line_x1 = time+(60*60*24*1000*1)
    line_x2 = time+(60*60*24*1000*7)
    label_x = time+(60*60*24*1000*4)
    targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time)
    targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal)
    [targetLine,targetLabel]
//////////////////////////////////// Delete Lines with labels //////////////////////////////////////////////////
f_deleteLinesWithLabels(targetLine, targetLabel, last)=>
    line.delete(id=last?targetLine[1]:targetLine)
    label.delete(id=last?targetLabel[1]:targetLabel)
/////////////////////////////////////////////////// Calculate Trend //////////////////////////////////////////////////////
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel] = f_getDisplayModeVeriables(displayMode)
vma = f_getMovingAverage(volume, volumeMaType, volumelength)
vmareverse = f_getMovingAverage(volume, volumeMaType, reverseVolumeLength)
[superTrend, dir] = supertrend(supertrendMult, supertrendLength)
atr = atr(atrlength)
[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)
[trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout] = f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMultiplyer)
barState = f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)
[upTarget,stopUpTarget,downTarget,stopDownTarget, lastBreakout] = f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)
[upLine,stopUpLine,downLine,stopDownLine] = f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
alignedMaIndex = sum(maAlignment,LookbackPeriod)
maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignment
maLow = alignedMaIndex < -alignmentIndexThreshold or not considerMaAlignment
[newHigh, newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
[supertrendMa, ma, dirMa] =  f_supertrendOnMa(source, MaTypeMa, MaLengthMa, supertrendLengthMa, supertrendMultMa)
//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////
[exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB] = f_getRangeExitStrategy(exitStrategyOnRangingCondition)
[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)
[buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)
[target, buyStop, sellStop, range] = f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)
//crossedCompound = (strategy.position_size > 0 ? strategy.position_avg_price < buyStop : strategy.position_size < 0 ? strategy.position_avg_price > sellStop : true) or allowImmediateCompound
crossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompound
percentRank = percentrank(source, LookbackPeriodPR)
[SupertrendW, DirW] = security(syminfo.tickerid, 'W', supertrend(SupertrendWMult, SupertrendWPd), lookahead = true)
[SupertrendM, DirM] = security(syminfo.tickerid, 'M', supertrend(SupertrendMMult, SupertrendMPd), lookahead = true)
buyEntry := buyEntry and (((dirMa == 1 or not considerMaSupertrend) and percentRank > 50) or strategy.netprofit >= 0) and (DirW == -1 or not considerWeeklySupertrend) and (DirM == -1 or not considerMonthlySupertrend)
sellEntry := sellEntry and (((dirMa == -1 or not considerMaSupertrend) and percentRank < 50) or strategy.netprofit >= 0) and (DirW == 1 or not considerWeeklySupertrend) and (DirM == 1 or not considerMonthlySupertrend)
[middle, upper, lower] = bb(close, 100, 2.5)
rangeBuyEntry = range and crossover(close, lower) and exitOnBB
rangeSellEntry = range and crossunder(close, upper) and exitOnBB
//////////////////////////////////////// Plot //////////////////////////////////////////////////////
plot(showChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showChannel?downLine:na, title="downChannel", color=color.red, linewidth=2, style=plot.style_line)
plotshape(showTargets or showTargetStops?upTarget:na, title="UpTarget", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)
plotshape(showTargets or showTargetStops?downTarget:na, title="DownTarget", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)
plotshape(showTargetStops?stopUpTarget:na, title="UpStop", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)
plotshape(showTargetStops?stopDownTarget:na, title="DownStop", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)
plot(showUpChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showUpChannel?stopUpLine:na, title="StopUpChannel", color=color.red, linewidth=2, style=plot.style_line)
plot(showDownChannel?stopDownLine:na, title="StopDownChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showDownChannel?downLine:na, title="DownChannel", color=color.red, linewidth=2, style=plot.style_line)
channelview = showChannel or showUpChannel or showDownChannel
buyStopLineColor = range ? color.purple : strategy.position_size > 0 ?color.red:strategy.position_size < 0 ?color.green:color.blue
sellStopLineColor = range ? color.purple : strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue
showStopCompound = showTrailingStop and (range or strategy.position_size != 0) and not channelview
plot(showStopCompound? buyStop : na, title="DownStop", color=buyStopLineColor, linewidth=2, style=plot.style_stepline)
plot(showStopCompound? sellStop : na, title="UpStop", color=sellStopLineColor, linewidth=2, style=plot.style_stepline)
barcolor(barState==1?color.lime:barState==-1?color.orange:color.silver)
//////////////////////////////////////// Plot Trade //////////////////////////////////////////////////////
if(buyEntry or sellEntry) and (showTargetLevels) and (breakout or pullback or reverse)
    [targetLine, targetLabel] = f_drawLinesWithLabels(target,buyEntry?"Long":"Short",color.blue)
    if(not showPreviousLevels)
        f_deleteLinesWithLabels(targetLine, targetLabel, true)
if(buyEntry or sellEntry or strategy.position_size != 0)
    [stopLine, stopLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?buyStop:sellStop,"Stop",color.red)
    [compoundLine, compoundLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?sellStop:buyStop,"Compound",color.green)
    f_deleteLinesWithLabels(stopLine, stopLabel, true)
    f_deleteLinesWithLabels(compoundLine, compoundLabel, true)
//////////////////////////////////////// Trade //////////////////////////////////////////////////////
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.entry("Buy", strategy.long, when=rangeBuyEntry, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range))) or rangeSellEntry)
strategy.exit("ExitBuy", "Buy", stop = buyStop)
strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)
strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)
strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range)))
strategy.exit("ExitSell", "Sell", stop = sellStop)
Expand (432 lines)

Overview

Entries can require new long-term highs or lows and recent moving-average alignment, with optional weekly or monthly Supertrend filters. Exits can follow an opposite signal, a trailing stop, or Bollinger Bands when ranging, controlled by multipliers and range settings. Display modes plot targets, channels, or stops. It sizes each position as a percentage of equity and allows only one open entry in a direction.

Details

Published by

hasnocool on GitHub

Code credit

HeWhoMustNotBeNamed, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, Breakout, Moving averages, Volatility & bands

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.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
exitOnSignalboolfalseexitOnSignal
Exit Strategy when in RangestringDisabledexitStrategyOnRangingCondition
allowImmediateCompoundboolfalseallowImmediateCompound
Trade Directioninputstrategy.direction.longtradeDirection
Trade TypestringalltradeType
Display ModestringTargetsdisplayMode
showTrailingStopbooltrueshowTrailingStop
showTargetLevelsbooltrueshowTargetLevels
showPreviousLevelsboolfalseshowPreviousLevels
stopMultiplyerint6stopMultiplyer
compoundMultiplyerint4compoundMultiplyer
rangeBarsint100rangeBars
Show all 28 settings
SettingTypeDefaultVariable
backtestYearsint10backtestYears
Filter Highs/Lows for entrybooltrueconsiderNewLongTermHighLows
shortHighLowPeriodint100shortHighLowPeriod
longHighLowPeriodint200longHighLowPeriod
Check recent moving average alignmentbooltrueconsiderMaAlignment
LookbackPeriodint300LookbackPeriod
includePartiallyAlignedbooltrueincludePartiallyAligned
Moving Average TypestringsmaMAType
alignmentIndexThresholdint50alignmentIndexThreshold
LookbackPeriodPRint50LookbackPeriodPR
considerWeeklySupertrendboolfalseconsiderWeeklySupertrend
SupertrendWMultint1SupertrendWMult
SupertrendWPdint26SupertrendWPd
considerMonthlySupertrendboolfalseconsiderMonthlySupertrend
SupertrendMMultint2SupertrendMMult
SupertrendMPdint6SupertrendMPd
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

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统
16 stars

This strategy plots Donchian channels, trailing stops, and profit targets directly on the price chart. It enters breakout trades using a 55-bar Donchian channel and sizes positions according to an ATR-based risk percentage per unit. The system adds units as pr

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 10: Profit Targets
4 stars

This strategy executes trend-following trades based on Bollinger Band breakouts confirmed by a long-term moving average filter. A long position opens when the price crosses above the upper Bollinger Band, provided the band spread meets a minimum threshold and

Strategy v5 Volatility & bandsTrend
Updated 2 years ago · None stated GitHub repository of Bollinger Trend - Strategy V1
4 stars

The Keltner Channel Strategy is a breakout system plotted directly on the main price chart. It calculates upper and lower channel bands around an exponential or simple moving average using ATR, True Range, or bar range multiplied by a specified factor. A long

Strategy v5 TrendVolatility & bands
Updated 5 months ago · None stated GitHub repository of Keltner Channel Strategy

This strategy combines Bollinger Bands and Bollinger Band Width to trigger breakout trades during periods of low volatility. It opens long positions when price crosses above the upper band while band width is below its 100-period moving average, and opens shor

Strategy v5 TrendVolatility & bands
Updated 4 years ago · CC0-1.0 GitHub repository of Greeffer's Bolinger Band Hedge Strategy

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