Indicator · Pine Script v5 · On the chart

Harmonic Patterns Based Trend Follower

by regalouisei· code credited to HeWhoMustNotBeNamed

This indicator detects harmonic patterns using a Zigzag pivot engine and derives trend-following entry and stop levels relative to key pattern legs.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code89
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago25 Feb 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

89 lines of Pine Script v5 from pinescript/editors_picks/harmonic-patterns-based-trend-follower.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

harmonic-patterns-based-trend-follower.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
import HeWhoMustNotBeNamed/rzigzag/10 as zg
import HeWhoMustNotBeNamed/eHarmonicpatternsLogScale/1 as hp

indicator('Harmonic Patterns Based Trend Follower', 'HP-TF [Trendoscope]', overlay=true, max_lines_count = 500)
base = input.string('CD', 'Base', ['minmax', 'correction', 'CD'], group="Supertrend", tooltip='Base for which entry/stop and thus range can be calculated')
entryPercent = input.int(30, 'Entry %', minval=30, maxval = 200, step=5, group='Supertrend', tooltip = 'Percent of Base from D for entry in pattern direction')
stopPercent = input.int(5, 'Stop %', minval=0, maxval = 30, step=5, group='Supertrend', tooltip = 'Percent of Base from D for exit in opposite direction')
useClosePrices = input.bool(true, 'Use Close Prices', group='Supertrend', tooltip = 'Use close prices for finding breakouts and calculate trend direction')

errorPercent = input.int(3, title='Error %', minval=3, step=5, maxval=21, group='Harmonic Patterns',
                             tooltip='Error threshold for calculation on patterns. Increased error threshold will reduce the accuracy of patterns. Lower error threshold will reduce number of patterns detected.')
zigzagLength = input.int(8, step=5, minval=3, title='Zigzag', group='Harmonic Patterns', tooltip='Zigzag Length on which pattern detection is built')
logScale = input.bool(false, 'Log Scale', group='Harmonic Patterns', tooltip='If selected, patterns are scanned on log scale instead of regular price scale')
showHarmonicPatterns = input.bool(true, 'Display Harmonic Patterns', group='Harmonic Patterns', tooltip='If selected, harmonic patterns scanned will be drawn on chart')
depth = 10

startIndex = 1
var float bullishRange = na
var float bearishRange = na
var int trend = na

[zigzagmatrix, zgFlags] = zg.zigzag(zigzagLength, array.from(high, low), depth, 0)
if(matrix.rows(zigzagmatrix) >= startIndex+5)
    existingPattern = false
    isHarmonicPattern = false
    x = matrix.get(zigzagmatrix, startIndex+4, 0)
    a = matrix.get(zigzagmatrix, startIndex+3, 0)
    b = matrix.get(zigzagmatrix, startIndex+2, 0)
    c = matrix.get(zigzagmatrix, startIndex+1, 0)
    d = matrix.get(zigzagmatrix, startIndex, 0)
    patterns = hp.isHarmonicPattern(x, a, b, c, d, array.new<bool>(), true, errorPercent, logScale=logScale)

    if(array.includes(patterns, true) and array.get(zgFlags, 1))
        xBar = matrix.get(zigzagmatrix, startIndex+4, 1)
        aBar = matrix.get(zigzagmatrix, startIndex+3, 1)
        bBar = matrix.get(zigzagmatrix, startIndex+2, 1)
        cBar = matrix.get(zigzagmatrix, startIndex+1, 1)
        dBar = matrix.get(zigzagmatrix, startIndex, 1)
        if showHarmonicPatterns
            line.new(int(xBar), x, int(aBar), a, color=color.blue, style = line.style_dotted, width = 0)
            line.new(int(aBar), a, int(bBar), b, color=color.blue, style = line.style_dotted, width = 0)
            line.new(int(bBar), b, int(cBar), c, color=color.blue, style = line.style_dotted, width = 0)
            line.new(int(cBar), c, int(dBar), d, color=color.blue, style = line.style_dotted, width = 0)
            line.new(int(bBar), b, int(dBar), d, color=color.blue, style = line.style_dotted, width = 0)
            line.new(int(xBar), x, int(bBar), b, color=color.blue, style = line.style_dotted, width = 0)
    
        dir = matrix.get(zigzagmatrix, startIndex, 3)
        baseValue = base == 'minmax' ? math.max(x,a,b,c,d) - math.min(x,a,b,c,d) : base == 'correction'? math.abs((dir > 0? math.max(a, c) : math.min(a, c)) - d) : math.abs(c-d)
        entryRange = d - math.sign(dir)*baseValue*(entryPercent/100)
        stopRange = d + math.sign(dir)*baseValue*(stopPercent/100)

        newBullishRange = math.max(entryRange, stopRange)
        newBearishRange = math.min(entryRange, stopRange)

        bullishRange := trend < 0? math.min(bullishRange, newBullishRange) : newBullishRange
        bearishRange := trend > 0? math.max(bearishRange, newBearishRange) : newBearishRange

highPrice = useClosePrices? close : high
lowPrice = useClosePrices ? close : low
trend := highPrice >= bullishRange? 1 : lowPrice <=bearishRange? -1 : trend
trendColor = trend>0? color.lime : trend < 0? color.red: color.silver

plot(bullishRange, "BullishRange", color=color.green)
plot(bearishRange, "BearishRange", color=color.red)

barcolor(trendColor)
plot(trend, "Trend", trendColor, display = display.data_window)

Overview

Harmonic Patterns Based Trend Follower overlays dynamic trailing levels on the price chart to assist in tracking market direction following pattern completion. Users can adjust pattern detection tolerance, Zigzag parameters, and entry or stop percentages. Note that Zigzag pivots and resulting pattern labels adjust retroactively on unconfirmed price bars.

Details

Published by

regalouisei on GitHub

Code credit

HeWhoMustNotBeNamed, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
BasestringCDbase
Entry %int30entryPercent
Stop %int5stopPercent
Use Close PricesbooltrueuseClosePrices
Error %int3errorPercent
Zigzagint8zigzagLength
Log ScaleboolfalselogScale
Display Harmonic PatternsbooltrueshowHarmonicPatterns
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

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

Function - Linear Regression

by ricardosantos79
261 stars

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart. A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots up

Indicator v5 TrendSupport & resistance
Updated 4 years ago · None stated GitHub repository of Function - Linear Regression

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers