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

avatar
Register or

Likes

avatar avatar avatar avatar
Related users ' posts
geroniman merci Ivan, super indicatuer. Les cours vont souvent toucher 50% des zones vertes ou rouges....
Iván Pour ajouter une ligne supplémentaire, il suffit de créer une nouvelle variable, par exemple...
Maurizio A. excellent indicateur ! comment puis-je modifier le code pour afficher uniquement les dernier...
sanchota Mira que has hecho unos cuantos indicadores,pues este los supera a todos.Brillante.
roccafragius Hello Ivan, another great Indicator, very useful to trace the trend ( blue line) and the pos...
teshmi9z Hola, ¿es posible detectar cuándo el precio regresa a la zona del 61 al 88 % de Fibonacci y,...
NicoGB67 Hola Iván, estoy usando desde hace poco este indicador y a veces cuando estoy esperando un n...
Iván Hola. El comportamiento es normal porque el último fibo es provisional por lo tanto se puede...
Regisnew Bonjour Ivan serait il possible de proposer un screener pour détecter les zones de support v...
bembel242 Hello Ivan ! A belated HNY ! I know late ! Quick question on theis great indicator plse. I u...
gp38super Wow! This is GOLD! Great job!
Iván Hi You should delete from the indicator code all drawing functions and all variables not us...
Iván I've created a screener to show [longcondition or shortcondition]
Chrisinobi Hallo Ivan, Danke das ist Perfekt !! Kannst du bitte in der Screener-Bibliothek die itf. hoc...
philippe59139 Bravo super travail
xpe74 top job ......
xpe74 Hello, cet indicateur a il fait l'objet d'une conversion en stratégie de trading ?? does thi...
gidien Thanks for the hint. I think i know now, why this happen. The "settings" block was added by ...
LucasBest Thank you for sharing your work, both original and very disconcerting. When I went through t...
gidien Hello LucasBest, thanks for your comment. Point 1: Yes your are right. The Zigzag ve...
steffen_burat Hello Nicolas, I have a cumulative histogram update problem, the indicator often updates ...
taklause Hello Nicolas, if I try to use your indicator in a trading system, the error on prc pops up ...
Gio56 Bonjour Nicolas J'ai le meme souci que steffen , l'indicateur ne cumule qu'après avoir redé...
jonpt88 hI . THIS LOOKS GOOD. Thanks. Just one doubt: is this kind of impulse indicator - does it sh...
effegi
3 years ago
effegi A good alternative solution, even I had thought of the variant that uses high and low (proba...
Seb did you automate that 1-2-3 strategy? how is that working for you?
effegi Not yet, I'm busy developing other strategies/indicators at the moment, but it's on my to-do...
StephFor //ind1 = ZigZagPoint[2*averagetruerange[200]](close) avr = 3 //3% ind1 = ZigZag[avr](close...
Manu L. @Steph un grand merci pour ton aide mais :-( J'ai copier le code tel quel mais cependant j...
AlphaMauss Je n'ai pas réussi à faire fonctionner l'indicateur avec le code fourni en commentaire sur P...
fazel53 How do i attach this indicator to my mt5 platform?
Nicolas You can't! All indicators here are for ProRealTime trading platform: https://www.prorealtime...
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 ...

Top