Zeal Terminal Open Zeal Terminal

Pine Script v5 · Strategy

Band-Zigzag - TrendFollower Strategy [Trendoscope]

A Pine Script v5 strategy built on Crossover or Crossunder (combinedTrend, 0). It has 7 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 10% of equity and pays 0.05% commission. 13 settings; defaults include Trade Type Any, Band Type Bollinger Bands and MA Type sma.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Band-Zigzag - TrendFollower Strategy [Trendoscope] repaint?
No
No repainting patterns were found in the source.
Does Band-Zigzag - TrendFollower Strategy [Trendoscope] run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L37:C0: no source was supplied for the library 'HeWhoMustNotBeNamed/ta/1'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
Does Band-Zigzag - TrendFollower Strategy [Trendoscope] use a stop loss?
Yes
strategy.exit sets a stop on line 198, 205.
Does Band-Zigzag - TrendFollower Strategy [Trendoscope] run in Zeal Terminal?
No
Not yet: it imports the library HeWhoMustNotBeNamed/ta/1 and the library HeWhoMustNotBeNamed/arrays/1 and the library HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6, whose source is not available here, so it does not run here
Does not run in Zeal Terminal yetIt imports the library HeWhoMustNotBeNamed/ta/1 and the library HeWhoMustNotBeNamed/arrays/1 and the library HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6, whose source is not available here, so it does not run here. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Note

    5 settings have no label

    In the settings dialog bandType (line 40), maType (line 41), maLength (line 42), multiplier (line 43), currentTrendInvalidationMultiplier (line 49) show an empty name. The labels on this page come from the variable names.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Trade Settings
Trade DirectionUse this to filter only long or short tradesstrategy.direction.allstring · options [strategy.direction.long, strategy.direction.short, strategy.direction.all]line 36
Trade TypePullback - On first pullback after trend confirmation\nBreakout - On first breakout of trend\Pullback-Breakout - On first pullback and breakout of trend\nAny - As soon as trend changeAnystring · options ['Pullback', 'Breakout', 'Pullback-Breakout', 'Any']tradeOnBreakout tradeOnPullback tradeOnRetest tradeOnAny
Use Stop LossIf set, initial stoploss is used for every trade. Otherwise, trade can only be closed by change of trend. Not required if using Recent Pivot Overridefalseboolexit ExitLong exit ExitShort line 197 line 204
Bands
Band Type (no label in the script)Bollinger Bandsstringline 83 line 88 line 93
MA Type (no label in the script)smastring · options ['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'highlow', 'linreg', 'median']bmiddle bupper blower kmiddle kupper klower
MA Length (no label in the script)20int · min 5 · step 5bmiddle bupper blower kmiddle kupper klower dmiddle dupper dlower
Multiplier (no label in the script)Band parameters let you select type of band/channel, moving average base, length and multiplier2.0float · min 0.5 · step 0.5bmiddle bupper blower kmiddle kupper klower
Use True Range (For KC only)Used only for keltener channel calculationtrueboolkmiddle kupper klower
StickySticky bands avoids changing the band unless there is breach. Meaning, band positions only change when price is outside the band.trueboolbmiddle bupper blower kmiddle kupper klower dmiddle dupper dlower
AdaptiveWhen selected, lower band will not decrease when pivot high is in motion and upper band will not increase when pivot low in motiontruebooluupper llower
Display BandsIf selected, displays bands on charttrueboolUpper Lower
Trend
Use Recent Pivot OverridetrueboolcombinedTrend
Current Trend Invalidation Multiplier (no label in the script)Trend calculation is done on last confirmed pivot. This option provides opportunity to also consider current unconfirmed pivot for defining trend on extreme moves. This will help in avoiding steep drawbacks1.618floatcurrentTrendForce

What it calculates

  • Crossover / CrossundercombinedTrend, 0allowEntry · line 191

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

closecloseprice datamaTypeMA Typesetting · smamaLengthMA Lengthsetting · 20multiplierMultipliersetting · 2.0currentTrendInvalidationMultiplierCurrent Trend Invalidat…setting · 1.618highhighprice datalowlowprice datatimetimeprice datatradeTypeTrade Typesetting · AnyallowEntryCrossover / Crossunder→ allowEntryupperuppervaluelowerlowervaluemiddlemiddlevaluelastPivot, llastPivot, recentPivotlastPivot · llastPivot …3 valuesdel, trend, currentTrend, currentDir, lastPivotDirection, lastDir, startDirection, endDirection, txtdel · trend +79 valuesbmiddle, bupper, blower, kmiddle, kupper, klowerbmiddle · bupper +46 valuesdmiddle, dupper, dlowerdmiddle · dupper +13 valuescurrentTrendForcecurrentTrendForcevalueuupperuuppervaluellowerllowervaluepercentBHighpercentBHighvaluepercentBLowpercentBLowvaluepricepricevaluepercentBpercentBvalueppvaluecount, removeLastcount · removeLast2 valuesiivaluestartPivot, endPivotstartPivot · endPivot2 valueslnlnvaluedrdrvaluecombinedTrendcombinedTrendvaluetradeOnBreakouttradeOnBreakoutconditiontradeOnPullbacktradeOnPullbackconditiontradeOnRetesttradeOnRetestconditiontradeOnAnytradeOnAnyconditionzigzag, zigzagDrawingszigzag · zigzagDrawings2 conditionspHighpHighconditionpLowpLowconditionlineColor, lbl, candleColorColourlineColor · lbl +1close:ShortClose Shortstrategy.closeentry:LongOpen Longstrategy.entryexit:ExitLongexit ExitLongstrategy.exitclose:LongClose Longstrategy.closeentry:ShortOpen Shortstrategy.entryexit:ExitShortexit ExitShortstrategy.exitclose_all:close_all strategy.close_allplot:179Upperplotplot:180Lowerplotplot:185Last Pivot Trendplotplot:186Current Pivot Trendplotplot:187Force Trendplotplot:188Combined Trendplotplot:189Current Directionplotplot:208Allow Entryplot

Order rules

OrderFires whenBy defaultLine
Close Short(combinedTrend > 0)On193
Open Long long((tradeOnBreakout and currentDir > 0) or (tradeOnPullback and currentDir < 0) or tradeOnAny or (currentTrend >0 and trend >0 and currentDir > 0 and tradeOnRetest)) and allowEntryOn196
Exit ExitLong stopuseStopLossOff “Use Stop Loss”198
Close Long(combinedTrend < 0)On200
Open Short short((tradeOnBreakout and currentDir < 0) or (tradeOnPullback and currentDir > 0) or tradeOnAny or (currentTrend < 0 and trend < 0 and currentDir < 0 and tradeOnRetest)) and allowEntryOn203
Exit ExitShort stopuseStopLossOff “Use Stop Loss”205
Close (combinedTrend == 0)On207

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Similar scripts

No other indicator or strategy here shares enough of its calculations.

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L37:C0: no source was supplied for the library 'HeWhoMustNotBeNamed/ta/1'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯//             ▒▒             ▒                        -//@version=5+//@version=6strategy("Band-Zigzag - TrendFollower Strategy [Trendoscope]", "BZSTF[Trendoscope]", overlay=true, initial_capital=1000,⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No It imports the library HeWhoMustNotBeNamed/ta/1 and the library HeWhoMustNotBeNamed/arrays/1 and the library HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6, whose source is not available here, so it does not run hereNot measured
PineTSNot testedNot testedNot measured

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © HeWhoMustNotBeNamed//                                       ░▒             //                                  ▒▒▒   ▒▒      //                              ▒▒▒▒▒     ▒▒      //                      ▒▒▒▒▒▒▒░     ▒     ▒▒          //                  ▒▒▒▒▒▒           ▒     ▒▒          //             ▓▒▒▒       ▒        ▒▒▒▒▒▒▒▒▒▒▒  //   ▒▒▒▒▒▒▒▒▒▒▒ ▒        ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒         //   ▒  ▒       ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░        //   ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒         //   ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒                       //    ▒▒▒▒▒         ▒▒▒▒▒▒▒                            //                 ▒▒▒▒▒▒▒▒▒                           //                ▒▒▒▒▒ ▒▒▒▒▒                          //               ░▒▒▒▒   ▒▒▒▒▓      ████████╗██████╗ ███████╗███╗   ██╗██████╗  ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗//              ▓▒▒▒▒     ▒▒▒▒      ╚══██╔══╝██╔══██╗██╔════╝████╗  ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝//              ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒        ██║   ██████╔╝█████╗  ██╔██╗ ██║██║  ██║██║   ██║███████╗██║     ██║   ██║██████╔╝█████╗ //             ▒▒▒▒▒       ▒▒▒▒▒       ██║   ██╔══██╗██╔══╝  ██║╚██╗██║██║  ██║██║   ██║╚════██║██║     ██║   ██║██╔═══╝ ██╔══╝  //            ▒▒▒▒▒         ▒▒▒▒▒      ██║   ██║  ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║     ███████╗//             ▒▒             ▒                        //@version=5strategy("Band-Zigzag - TrendFollower Strategy [Trendoscope]", "BZSTF[Trendoscope]", overlay=true, initial_capital=1000,         default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent,          pyramiding=1, commission_value=0.05, close_entries_rule="ANY", margin_long=100, margin_short=100,         max_lines_count=500, max_labels_count=500, max_boxes_count=500, use_bar_magnifier=false)tradeDirection = input.string(strategy.direction.all, "Trade Direction", options=[strategy.direction.long, strategy.direction.short, strategy.direction.all],                             group="Trade Settings", tooltip='Use this to filter only long or short trades')tradeSettingsTooltip = 'Pullback - On first pullback after trend confirmation\nBreakout - On first breakout of trend\Pullback-Breakout - On first pullback and breakout of trend\nAny - As soon as trend change'tradeType = input.string('Any', 'Trade Type', options=['Pullback', 'Breakout', 'Pullback-Breakout', 'Any'], group='Trade Settings', tooltip=tradeSettingsTooltip)tradeOnBreakout = tradeType == 'Breakout'tradeOnPullback = tradeType == 'Pullback'tradeOnRetest = tradeType == 'Pullback-Breakout'tradeOnAny = tradeType == 'Any'useStopLoss = input.bool(false, 'Use Stop Loss', group='Trade Settings', tooltip = 'If set, initial stoploss is used for every trade. Otherwise, trade can only be closed by change of trend. Not required if using Recent Pivot Override')strategy.risk.allow_entry_in(tradeDirection)import HeWhoMustNotBeNamed/ta/1 as etaimport HeWhoMustNotBeNamed/arrays/1 as paimport HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6 as hpbandType = input.string('Bollinger Bands', '', ['Bollinger Bands', 'Keltner Channel', 'Donchian Channel'], group='Bands', inline='b1')maType = input.string('sma', '', options=['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'highlow', 'linreg', 'median'], inline = 'b1', group='Bands')maLength = input.int(20, '', minval = 5, step=5, inline = 'b1', group='Bands')multiplier = input.float(2.0, '', step=0.5, minval=0.5, group='Bands', inline='b1', tooltip = 'Band parameters let you select type of band/channel, moving average base, length and multiplier')useTrueRange = input.bool(true, 'Use True Range (For KC only)', group='Bands', tooltip = 'Used only for keltener channel calculation')sticky = input.bool(true, 'Sticky', group='Bands', tooltip = 'Sticky bands avoids changing the band unless there is breach. Meaning, band positions only change when price is outside the band.')useAdaptive = input.bool(true, 'Adaptive', group='Bands', tooltip = 'When selected, lower band will not decrease when pivot high is in motion and upper band will not increase when pivot low in motion')showBands = input.bool(true, 'Display Bands', group='Bands', tooltip = 'If selected, displays bands on chart')useLatestPivot = input.bool(true, 'Use Recent Pivot Override', group='Trend', inline='t')currentTrendInvalidationMultiplier = input.float(1.618, '', 0, 100, 1, group='Trend', inline='t',             tooltip = 'Trend calculation is done on last confirmed pivot. This option provides opportunity to also consider current unconfirmed pivot for defining trend on extreme moves. This will help in avoiding steep drawbacks')float upper = 0.0float lower = 0.0float middle = 0.0type Pivot    float price    int bar    int bartime    int direction    float percentB    float ratio = 0type Drawing    line zigzagLine    label zigzagLabelunshift(array<Pivot> zigzag, Pivot p)=>    if(array.size(zigzag) > 1)        lastPivot = array.get(zigzag, 0)        llastPivot = array.get(zigzag, 1)        p.direction := p.price*p.direction > llastPivot.price*p.direction ? p.direction*2 : p.direction        p.ratio := math.abs(p.price - lastPivot.price)/math.abs(llastPivot.price - lastPivot.price)    array.unshift(zigzag, p)    if(array.size(zigzag)>15)        array.pop(zigzag)shift(array<Drawing> drawings)=>    del = array.shift(drawings)    line.delete(del.zigzagLine)    label.delete(del.zigzagLabel)unshift(array<Drawing> drawings, Drawing drawing, int maxItems)=>    array.unshift(drawings, drawing)    if(array.size(drawings) > maxItems)        del = array.pop(drawings)        line.delete(del.zigzagLine)        label.delete(del.zigzagLabel)if(bandType == 'Bollinger Bands')    [bmiddle, bupper, blower] = eta.bb(close, maType, maLength, multiplier, sticky)    upper := bupper    lower := blower    middle := bmiddleif(bandType == 'Keltner Channel')    [kmiddle, kupper, klower] = eta.kc(close, maType, maLength, multiplier, useTrueRange, sticky)    upper := kupper    lower := klower    middle := kmiddleif(bandType == 'Donchian Channel')    [dmiddle, dupper, dlower] = eta.dc(maLength, false, close, sticky)    upper := dupper    lower := dlower    middle := dmiddlevar zigzag = array.new<Pivot>()var trend = 0var currentTrend = 0var currentDir = 0var currentTrendForce = 0var currentTrendExtreme = 0if(array.size(zigzag) > 1)    recentPivot = array.get(zigzag, 0)    lastPivot = array.get(zigzag, 1)    currentDir := recentPivot.direction    currentTrend := recentPivot.ratio > recentPivot.percentB? int(math.sign(recentPivot.direction)) : -int(math.sign(recentPivot.direction))    trend := lastPivot.ratio > lastPivot.percentB? int(math.sign(lastPivot.direction)) : -int(math.sign(lastPivot.direction))    currentTrendForce := recentPivot.ratio > recentPivot.percentB and recentPivot.ratio> currentTrendInvalidationMultiplier? int(math.sign(recentPivot.direction)) : -int(math.sign(recentPivot.direction))    var uupper = nz(upper)var llower = nz(lower)uupper := currentDir >= 0 or not useAdaptive? upper : math.min(upper, uupper)llower := currentDir <= 0 or not useAdaptive? lower : math.max(lower, llower)percentBHigh = (high - llower)/(uupper - llower)percentBLow = (uupper - low)/(uupper - llower)addPivot(zigzag, direction)=>    lastRemoved = false    price = direction > 0? high : low    percentB = direction > 0? percentBHigh : percentBLow    Pivot p = Pivot.new(price, bar_index, time, int(direction), percentB)    if(array.size(zigzag) == 0)        unshift(zigzag, p)    else        lastPivot = array.get(zigzag, 0)        lastPivotDirection = math.sign(lastPivot.direction)        if (lastPivotDirection != p.direction)            unshift(zigzag, p)        if(lastPivotDirection == p.direction and lastPivot.price*direction < p.price*direction)            array.remove(zigzag, 0)            unshift(zigzag, p)            lastRemoved := true    lastRemoved       add_pivots(zigzag, pHigh, pLow)=>    count = 0    removeLast = false    if(array.size(zigzag) == 0)        if(pHigh)            addPivot(zigzag, 1)            count+=1        if(pLow)            addPivot(zigzag, -1)            count+=1    else        lastPivot = array.get(zigzag, 0)        lastDir = math.sign(lastPivot.direction)        if(pHigh and lastDir == 1)  or (pLow and lastDir == -1)            removeLast := addPivot(zigzag, lastDir)            count := removeLast ? count+1 : count        if(pHigh and (lastDir == -1)) or (pLow and (lastDir == 1))            addPivot(zigzag, -lastDir)            count+=1    [count, removeLast]draw_zigzag(zigzag, count, removeLast)=>    var zigzagDrawings = array.new<Drawing>()    if(removeLast and array.size(zigzagDrawings) > 0)        shift(zigzagDrawings)    if(array.size(zigzag) > count and count >= 1)        for i=count to 1            startPivot = array.get(zigzag, count)            endPivot = array.get(zigzag, count-1)            startDirection = startPivot.direction            endDirection = endPivot.direction            lineColor = endDirection == 2? color.green : endDirection == -2? color.red : color.silver            txt = str.tostring(endPivot.ratio*100, format.percent) + "/" + str.tostring(endPivot.percentB*100, format.percent)                        ln = line.new(startPivot.bartime, startPivot.price, endPivot.bartime, endPivot.price, xloc.bar_time, color=lineColor, width = 2)            lbl = label.new(endPivot.bartime, endPivot.price, txt, xloc.bar_time, yloc.price, lineColor, endPivot.direction > 0? label.style_label_down : label.style_label_up, textcolor = color.black)                        Drawing dr = Drawing.new(ln, lbl)            unshift(zigzagDrawings, dr, 500)    zigzagDrawingspHigh = high >= uupperpLow = low <= llower[count, removeLast] = add_pivots(zigzag, pHigh, pLow)draw_zigzag(zigzag, count, removeLast)plot(showBands? uupper:na, 'Upper', color.green, 0, plot.style_linebr)plot(showBands? llower:na, 'Lower', color.red, 0, plot.style_linebr)var combinedTrend = 0combinedTrend := trend > 0 or (useLatestPivot and (currentTrendForce > 0))? 1 :                 trend < 0 or (useLatestPivot and (currentTrendForce < 0))? -1 : combinedTrendcandleColor = combinedTrend > 0? color.green : combinedTrend < 0 ? color.red : color.silverplot(trend, 'Last Pivot Trend', trend >0? color.green : trend < 0? color.red : color.silver, display=display.data_window)plot(currentTrend, 'Current Pivot Trend', currentTrend > 0? color.green : currentTrend < 0? color.red : color.silver, display=display.data_window)plot(currentTrendForce, 'Force Trend', currentTrendForce >0? color.green : currentTrendForce < 0? color.red : color.silver, display=display.data_window)plot(combinedTrend, "Combined Trend", candleColor, display = display.data_window)plot(currentDir, "Current Direction", color=currentDir>0?color.green:currentDir<0?color.red:color.silver, display = display.data_window)var allowEntry = falseallowEntry := ta.crossover(combinedTrend, 0) or ta.crossunder(combinedTrend, 0)? true : allowEntryif(combinedTrend > 0)    strategy.close("Short")    if((tradeOnBreakout and currentDir > 0) or (tradeOnPullback and currentDir < 0) or tradeOnAny or (currentTrend >0 and trend >0 and currentDir > 0 and tradeOnRetest)) and allowEntry        allowEntry := false        strategy.entry("Long", strategy.long)        if useStopLoss            strategy.exit("ExitLong", "Long", stop=low - (uupper-llower))if(combinedTrend < 0)    strategy.close("Long")    if((tradeOnBreakout and currentDir < 0) or (tradeOnPullback and currentDir > 0) or tradeOnAny or (currentTrend < 0 and trend < 0 and currentDir < 0 and tradeOnRetest)) and allowEntry        allowEntry := false        strategy.entry("Short", strategy.short)        if useStopLoss            strategy.exit("ExitShort", "Short", stop=high + (uupper-llower))if(combinedTrend == 0)    strategy.close_all()plot(allowEntry?1:0, 'Allow Entry', display = display.data_window)