Strategy · Pine Script v5 · On the chart

Band-Zigzag - TrendFollower Strategy [Trendoscope]

by hasnocool· code credited to HeWhoMustNotBeNamed

Band-Zigzag TrendFollower Strategy is a trend-following trading system that combines volatility bands, such as Bollinger Bands or Keltner Channels, with pivot-based trend structure.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code209
Settings13inputs
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

209 lines of Pine Script v5 from Band-Zigzag - TrendFollower Strategy [Trendoscope].pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Band-Zigzag - TrendFollower Strategy [Trendoscope].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=5
strategy("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 eta
import HeWhoMustNotBeNamed/arrays/1 as pa
import HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6 as hp
bandType = 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.0
float lower = 0.0
float middle = 0.0
type Pivot
    float price
    int bar
    int bartime
    int direction
    float percentB
    float ratio = 0
type Drawing
    line zigzagLine
    label zigzagLabel
unshift(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 := bmiddle
if(bandType == 'Keltner Channel')
    [kmiddle, kupper, klower] = eta.kc(close, maType, maLength, multiplier, useTrueRange, sticky)
    upper := kupper
    lower := klower
    middle := kmiddle
if(bandType == 'Donchian Channel')
    [dmiddle, dupper, dlower] = eta.dc(maLength, false, close, sticky)
    upper := dupper
    lower := dlower
    middle := dmiddle
var zigzag = array.new<Pivot>()
var trend = 0
var currentTrend = 0
var currentDir = 0
var currentTrendForce = 0
var currentTrendExtreme = 0
if(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)
    zigzagDrawings
pHigh = high >= uupper
pLow = 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 = 0
combinedTrend := trend > 0 or (useLatestPivot and (currentTrendForce > 0))? 1 :
                 trend < 0 or (useLatestPivot and (currentTrendForce < 0))? -1 : combinedTrend
candleColor = combinedTrend > 0? color.green : combinedTrend < 0 ? color.red : color.silver
plot(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 = false
allowEntry := ta.crossover(combinedTrend, 0) or ta.crossunder(combinedTrend, 0)? true : allowEntry
if(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)
Expand (248 lines)

Overview

Band-Zigzag - TrendFollower Strategy [Trendoscope] evaluates trend switches and invalidation levels using adaptive or sticky bands to trigger long or short positions. Users can select the moving average type, band multiplier, direction filters, and pivot settings. The strategy plots trend lines and band levels directly on the main chart, though stop-loss protection is turned off by default.

Details

Published by

hasnocool on GitHub

Code credit

HeWhoMustNotBeNamed, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands, Breakout

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Trade Directionstringstrategy.direction.alltradeDirection
Trade TypestringAnytradeType
Use Stop LossboolfalseuseStopLoss
bandTypestringBollinger BandsbandType
maTypestringsmamaType
maLengthint20maLength
multiplierfloat2.0multiplier
Use True Range (For KC only)booltrueuseTrueRange
Stickybooltruesticky
AdaptivebooltrueuseAdaptive
Display BandsbooltrueshowBands
Use Recent Pivot OverridebooltrueuseLatestPivot
Show all 13 settings
SettingTypeDefaultVariable
currentTrendInvalidationMultiplierfloat1.618currentTrendInvalidationMultiplier
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

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint

均线突破交易系统

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 trend-following strategy adapts classic Donchian breakout channels according to market volatility regimes. It calculates an ATR percentile rank across a rolling lookback period, shifting dynamically between tighter breakout channels with smaller stops dur

Strategy v6 TrendBreakout
Updated 11 months ago · None stated GitHub repository of Seykota Alt 1: Adaptive Volatility

This strategy executes breakout trades using two Donchian Channels alongside an optional 200-period EMA trend filter. Entries trigger when the price sets a new highest high or lowest low over the primary Donchian Channel period. Exits are managed via a shorter

Strategy v5 BreakoutTrend
Updated 1 year ago · None stated GitHub repository of Ruckard Walcrypto DoubleDonchian B002

Breakout Strategy

by JoelPasapera
11 stars

This strategy implements a channel breakout system directly on the main price chart. It calculates highest highs and lowest lows over configurable entry and exit periods using historical candles. A long entry triggers when the close breaks above the entry chan

Strategy v6 BreakoutTrend
Updated 5 months ago · Apache-2.0 GitHub repository of Breakout 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