ZigZag and SR: Dynamic Swing Analysis with Support and Resistance

ZigZag and SR: Dynamic Swing Analysis with Support and Resistance

1) Introduction

The ZigZag indicator is a classic tool to filter out minor price fluctuations and highlight major swing points. The version presented here, ZigZag and SR, goes one step further by combining the swing structure with automatic support and resistance levels, as well as labels for trend classification.

This makes it particularly useful for traders who want a clean, structural view of price action without being distracted by noise.

2) What does “ZigZag and SR” add?

While a standard ZigZag only connects pivot highs and lows, this enhanced version introduces:

  • Dynamic support and resistance levels (green/red dotted lines).
  • Automatic trend labeling: Higher High (HH), Higher Low (HL), Lower High (LH), Lower Low (LL).
  • Customizable visualization: the user can enable or disable the ZigZag lines, support/resistance, and labels.
  • ATR-based positioning of labels to avoid overlap with price bars.

These features provide an intuitive chart overlay that helps traders quickly assess trend direction and key zones of interest.

3) How it works (step by step)

a) Pivot detection

The algorithm scans for pivot highs (highest[prd](high)) and pivot lows (lowest[prd](low)) over a user-defined lookback period (prd).

b) Direction of movement

Once a pivot is identified, the indicator determines the direction of the swing:

  • Uptrend segment (dir = 1) when a pivot high is confirmed.
  • Downtrend segment (dir = -1) when a pivot low is confirmed.

A variable tracks changes of direction (dirchanged) to ensure the ZigZag only updates when a genuine swing reversal occurs.

c) ZigZag construction with arrays

Arrays ($zigzag$zigzagidx$dir) are used to store pivot levels, their bar indices, and direction.
When a new pivot is confirmed:

  • If the trend has changed, a new segment is added.
  • If the trend continues, the last segment is updated to extend to the new extreme.

This ensures the indicator always reflects the most relevant market swings.

d) Dynamic support and resistance

For every confirmed pivot, the indicator projects horizontal dotted lines forward in time:

  • Green for support (pivot low).
  • Red for resistance (pivot high).

These lines dynamically extend until a new structure point invalidates them.

e) HH, HL, LH, LL classification

Based on the relative position of new pivots compared to previous ones, the code labels swings as:

  • HH (Higher High) or HL (Higher Low) in uptrends.
  • LH (Lower High) or LL (Lower Low) in downtrends.

To avoid clutter, labels are shifted up or down using ATR(14) as a margin.

f) Efficient rendering with islastbarupdate

To optimize performance, the drawing routines are executed only when the last bar updates, preventing unnecessary redrawing across all candles.

4) Parameters and recommended settings

  • prd (default = 15): Defines the sensitivity of pivot detection.
    • Higher values → fewer swings, only major moves.
    • Lower values → more swings, captures smaller fluctuations.
  • showSR (default = 1): Enables or disables the support/resistance dotted lines.
  • showLabels (default = 1): Toggles the HH/HL/LH/LL labels.
  • showZZ (default = 1): Toggles the ZigZag connecting lines.

These options give full flexibility: the user can display only the ZigZag, only support/resistance, or the complete setup.

5) Reading the chart: practical cases

  • Trending markets: The sequence of HH-HL or LL-LH clearly shows the dominant direction. Support and resistance levels confirm continuation or possible breakout points.
  • Range-bound markets: The ZigZag alternates between highs and lows of similar magnitude, highlighting horizontal zones of equilibrium.
  • Breakouts: When a support or resistance dotted line is breached, traders can quickly spot the transition to a new structural phase.

This makes the tool adaptable for both trend-following strategies and mean-reversion setups.

6) Limitations and best practices

  • Repainting nature: As with all ZigZag indicators, the latest swing may repaint until a pivot is fully confirmed. This is not a bug but a characteristic of ZigZag logic.
  • Choosing prd wisely:
    • Use larger values on higher timeframes to capture meaningful structure.
    • Use smaller values on intraday charts for short-term swing recognition.
  • Timeframe sensitivity: The indicator adapts to any timeframe but behaves best when aligned with your trading horizon.

By understanding these nuances, traders can avoid common pitfalls and integrate the tool effectively into their workflow.

7) Code

Share this

Risk disclosure:

No information on this site is investment advice or a solicitation to buy or sell any financial instrument. Past performance is not indicative of future results. Trading may expose you to risk of loss greater than your deposits and is only suitable for experienced investors who have sufficient financial means to bear such risk.

ProRealTime ITF files and other attachments : How to import ITF files into ProRealTime platform?

PRC is also on YouTube, subscribe to our channel for exclusive content and tutorials

  1. NicoGB67 • 44 days ago #

    Excelente Iván!

  2. NicoGB67 • 44 days ago #

    En mi modesta opinión de como entiendo este complicado mundo del trading, este indicador que has publicado es muy bueno para poder entrar en impulsos o correcciones y si se pudiera mejorar puliendo o reforzando sería casi perfecto, dejando claro que no existe el indicador perfecto, gracias por tus trabajos.

    • Iván • 43 days ago #

      Me alegro que sea útil el indicador. Pulir/reforzar, eso ya lo dejo para vosotros 🙂

  3. xpe74 • 42 days ago #

    Hello, really nice and working (nearly) perfectly well. Quick questions about the code . What means “zigzagidx”. I understand zigzag but not with IDX. Same question for T . what is the value behind T. I also have 1 question about your code line 90 for i=t-1 downto 3 do, you are introducing a looping function but why value 3?

    • Iván • 42 days ago #

      Hi, thanks!
      1) zigzagidx is the array that stores the bar index (barindex) of each detected pivot. It allows us to know exactly where (in time) the pivot occurred, so we can draw the segments correctly on the chart.
      2) t is simply a counter. Every time a new ZigZag point (HH, HL, LH or LL) is detected, t is incremented by 1 and used as the index to store the ZigZag values and their positions in the arrays:
      3) As for the for i = t-1 downto 3 do, we use 3 as the minimum value because the code compares current values to i-2 (for example: $zigzag[i] > $zigzag[i-2]). To avoid accessing a negative or undefined index, we stop the loop at 3.

  4. xpe74 • 42 days ago #

    Thanks a lot ..

  5. xpe74 • 42 days ago #

    was it converted as a trading strategy?

  6. xpe74 • 42 days ago #

    could be interesting to do so as visually it works well ….

  7. xpe74 • 41 days ago #

    Hi ivan, still working on your indicator. Is there a way (as i’m not a coder) to integrate in your code , a formula allowing to show on graph ( as a kind of timestamp on 1st bar) , when the pivot started (LL/LH/HH/HL) ……… thanks for your help

avatar
Register or

Likes

avatar avatar avatar avatar avatar avatar avatar avatar
Related users ' posts
mistersylv What parameter should we change to make another channel appear in the higher or lower time u...
carpentier Joffrey Bonjour à tous, Avant tout merci pour ce travail, cependant je suis bloqué quand je l'insta...
carpentier Joffrey Re, C'est ok, j'ai trouvé mon erreur... Cependant sur quel base peut on calculer son CALC...
Aragorna Hi Nicolas, How is it possible to use it in a higher timeframe plotted on a lower timeframe?...
Meta Signals Pro Pleasure ! Please let us know if you make good trades with it and if you see improvements we...
francis59 Bonjour, Bonjour, comment puis-je créer un screener basé sur cet indicateur, qui affiche le...
Trader Sab I am curious to try it how, however I get an error message for line 47 and 48 - drawsegment,...
thierrybl Thanks a lot
B-ling1 Hi Vonasi, I love this indicator - good job! Just one question: If I want the monthly OHLC L...
ezman Copy and paste this code, don't work. error!
datageek How do I change the thickness of the line or change it too dashed lines? Kind regards
lkiklkik NE fonctionne pas ( ou plus ... )
Nicolas il faut modifier toutes les références à top par itop et bottom par ibottom. Ces mots étant ...
Vonasi There is another version of this indicator that can plot the same lines but onto an indicato...
Martin35 Hello Vonasi, do you think it is possible with PRT to code with the same principle as on thi...
mathiasKN Steffen Schmauch • 12/11/2018 # hello Nicolas, can I change the indicator that I only get t...
Nicolas Please open a new topic in the indicator forum and explain there your query, thank you.
upupandaway This seems like a very useful indicator. However, it does not seem to open properly in the c...
mscharstrom Hi @robertogozzi, I really love this indicator. However, I'd like to tinker with it to fit ...
Ahimsa Hi Roberto I cannot thank you enough for writing this code. It could help me more than you ...
Nicolas With PRT v11, you have to click on "price" at the upper left side of the price chart.
teddy58 Ich habe es mit N= 1,5 und N=2,5 getestet mit 200000 Einheiten. Es funktioniert leider erst ...
Matriciel I use this indicator to help me make a decision when there is a divergence. The divergences ...
Jan Wind Hi, I personnaly am not a big fan of ZIGZAG indicator, as it repaints itself during time. ...
Nicolas Sure, I suggest you open a new topic in the forum to discuss about your ideas.
hdgm Bonjour Nicolas, est ce que l'on peut en faire une stratégie de trading automatisée ?
Nicolas Non, pas en utilisant l'indicateur zigzag traditionnel de la plateforme.
Marcel The line is just a moving average line. The indicator reacts on the Parabolic SAR dots.
Mattzi I dont get the dots! What am i doing wrong? :)
Mattzi Ignore this comment ;)
TACBOLSA
7 years ago
Tradingrob Hi Tac Bolsa, thanks for the information. But after carefully ready all the material i still...
TAC Bolsa Hello, the indicator creates the support depending on the volume and is dynamic.
carlvan Not working on PRT 11.1. And the site https://www.tiburonesdealetacorta.com does not exist....
Gianluca ok i fixed it i hope is ok like this: //TAC trader zone 10.2 | indicator //01.01.2018 //R...
TAC Bolsa Hello try this new version or view the blog with the new indicators .. https://www.t...
TAC Bolsa Sorry, TAC Trader Zone V2 https://www.tiburonesdealetacorta.com/2018/11/indicador-tac-tr...
rama I want to use this indicator in trading system, it says zig zag is obsolete and not supported
Nicolas Right, due to its repainting behavior, the zigzag is not allowed in automated trading with r...
rama I noticed it changes as time progress, I am 7 as the average, how many period it wont chang...
FULVIO09 Attualmente non c'è sufficiente volatilità : la condizione "C0 = AverageTrueRange[1500](Clos...
vlongobardo67 Ma io intendevo in backtest ! Scusa non l’ho menzionato.
ciniselloftse salve fulvio .il trading sistem e sempre profittevole?
Actabi Thank you ! Have you realised your "next step" ?
Jessar guten Tag, gibt es bereits die Aktualisierte Datei?
Per Inge Gents - An update - I have been studying various trading approaches, as this one that is bas...
cervantes2 Buenas tardes y gracias por este magnifico indicador. Queria saber si tienes un proscreener ...
cervantes2 Que busque los valores que la linea verde acaba de cruzar al alza o a la baja
AngelPujalt Tenéis algún screener de este indicador?
Yannick Hello There is a mistake in trailing stop code, I think that this should fix the problem s...
Paul About the trailing-stop the way it's coded. That works for backtesting only, just look at th...
Jonny sorry paul, but system says that is not possible to put many stop order combined...what have...
Violet Abz, the arrows and circles are only the *first part* of a trade setup. If certain conditio...
gabri Violet, you did an excellent job. I attached here https://www.prorealcode.com/prorealtim...
fab.ub HI GABRI, if the cirled arrow is the intermediate point in which You can define your entry a...
Matt B RolanBay, L'ellipse apparaît-elle à la bougie notifiée et reste ?
gianlucapegaso scusa Gagry ma il programm da copiare è quello con tutte le modifiche di cui ho letto nei va...
Valentinocorse bonjour a tous , superbe travail j'aimerai si possible une indication pour modifier l'indic...

Top