Algorithm to accurately finding swing & internal points

 

Hi,

I'm new to MQL5 and would like to make an indicator that identify the swing & internal points of the chart. I read that in order for you to find the swing/internal points then you need to identify the HH/HL/LL/LH of the chart. I want to collect some algorithm ideas on how to do this. Thanks!

[Deleted]  

Your topic has been moved to the section: Technical Indicators
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893

  • Usually people who can't code don't receive free help on this forum.
  • If you show your attempts and describe your problem clearly, you will most probably receive an answer from the community. Use the CODE button (Alt-S) when inserting code.
  • To learn MQL programming, you can research the many available Articles on the subject, or examples in the Codebase, as well as reference the online Book and Documentation
  • Remember also, that you can debug your code with MetaEditor's own debugging functionality.
  • If you do not want to learn to code, that is not a problem. You can either look at the Codebase if something free already exists, or in the Market for paid products (also sometimes free). However, recommendations or suggestions for Market products are not allowed on the forum, so you will have to do your own research.
  • Finally, you also have the option to hire a programmer in the Freelance section.
 
If you want purely accurate swing detection then you will achieve that with enormous delay, because true swings have to be confirmed and are after the fact.
If you want to find swings on time without delay it is just fleeting peak search and bottom search without caring about the true market structure, and there's a few trend based pivot indicators for that. Some are still after the fact, but others like psar are non lagging.
I published a psar zigzag, channel zigzag, and price percentage zigzag showing that there are completely different approaches that you can take. Study the code if you want to learn, or study other zigzags on the codebase as well
 
Conor Mcnamara #:
If you want purely accurate swing detection then you will achieve that with enormous delay, because true swings have to be confirmed and are after the fact.
If you want to find swings on time without delay it is just fleeting peak search and bottom search without caring about the true market structure, and there's a few trend based pivot indicators for that. Some are still after the fact, but others like psar are non lagging.
I published a psar zigzag, channel zigzag, and price percentage zigzag showing that there are completely different approaches that you can take. Study the code if you want to learn, or study other zigzags on the codebase as well


Is zigzag method the only accurate way to identify swing highs/lows at the moment?

 
Eka Rudianto #:


Is zigzag method the only accurate way to identify swing highs/lows at the moment?

I would say it is the best way, but I also made something called "magzag" which is a new approach to making the zigzag quantitative instead of being based on arbitrary price action.

There is also something called Fractals which really is nothing but a weaker version of the zigzag as it is based on turning points but has no input parameters. 

I attached a market structure indicator which is also essentially finding the swing highs and lows without using zigzag logic and doesn't repaint

Files:
 
Conor Mcnamara #:

I would say it is the best way, but I also made something called "magzag" which is a new approach to making the zigzag quantitative instead of being based on arbitrary price action.

There is also something called Fractals which really is nothing but a weaker version of the zigzag as it is based on turning points but has no input parameters. 

I attached a market structure indicator which is also essentially finding the swing highs and lows without using zigzag logic and doesn't repaint


Hi, thanks so much for the reply and the input! when you mentioned "doesn't repaint", what does that mean?

[Deleted]  
Eka Rudianto #when you mentioned "doesn't repaint", what does that mean?

"Repainting" means that the current bar calculations re-adjusts previous bars' indicator values. Most ZigZag indicators "repaint", some more than others.

 
Bit old but the technique that I use just 'improves' the fractals logic. Instead of having a rigid min bars rule around a pivot, I use an aggressive break rule to validate some pivots that don't satisfy the right hand but are significant. For example if minBars=3, There is an already confirmed high, a low is yet to form but we already 3 bars in the down bar sequence, we can have a bar breaking that confirmed high. We can mark this low now as confirmed. Also if you have 2 highs and lows confirmed in sequence, you can sneak another pivot in between as the extreme point. You can design a sweeping layer that eliminates the noise and singles out significant swing points only.
 

The attached indicator was written by another coder who reserved its copyright to Metaquotes. For the life of me, I can't remember who coded it.

Anyway, the indicator draws arrows at significant swing highs and lows based on a simple input bars period. As Conor Mcnamara already alluded in this thread, pinpointing significant highs and lows relies on price history and therefore, inherently lags. Even the original ZigZag indicator was intended to be used for identifying waves in price history. Note that unlike the ZigZag indicator, the indicator below does not alternate its drawing of swings. Instead, each arrow is drawn based on its surrounding price bars.

EURUSDH1

Files:
 
I'm going to drop here what I know exists, and the general behaviour of each type of extreme/pivot algorithm.

1. Candidate batch processing

This is the standardised zigzag that people first come to know about. It uses legacy code that was originally designed for early hardware constraints.

Behaviour:
Finds true market structure swings based on the depth (bar lookback). It performs a baseline migration (leg continuity) which some people call repaint, but that is not a bad kind of repaint, it is a normal leg update.

Pros:
Locates the market structure swings with low CPU load. 

Cons:
It can self-correct, and it can be after the fact for swing detection. It will not update fast enough for news impact.


2. Wave based extremes

This zigzag flips the leg when the market moves in the opposite direction by a certain percentage or number of pips.

Behaviour: It is often a static zigzag which flips leg when it is time to. There is no leg continuity as it does not update the extreme.

Pros:
Locates valid pivots, works as a price action filter automatically without added complexity, very little lag. It is not constrained to the timeframe as it's based purely on price movement.

Cons:
It doesn't do the baseline migration (leg continuity), so it is not suitable for some trading systems. It can sometimes swing abruptly with news impact which deviates from the actual market structure.


3. Fractal based extremes

This zigzag is based on fractals confirming an extreme swing with a bar lookback and lookahead.

Behaviour: 
It is often a static zigzag and does not perform leg continuity.

Pros: 

It finds valid swings and often never has to self correct when using a valid lookback/lookahead. 

Cons:

It is constrained to the bars on the timeframe. It is also often after the fact as it can lag significantly to confirm the extreme. 


4. Extremum channel zigzag

This zigzag marks the extremes of an extreme channel (such as the Donchian channel). It flips the leg once the channel starts to shift in the other direction.

Behaviour:
It may be a static zigzag or it can perform a baseline migration as the channel moves.

Pros:
This zigzag never self corrects as the channel is doing a lot of the work to determine the valid directional price shifts so that no candidate erasure or batch processing is needed. When the leg flips, it's not arbitrary but is often significant to the time of a market breakout or pullback.

Cons:
This zigzag can be difficult to program to be stable in order to produce valid legs that aren't victim to noise. 


5. ATR volatility extremes

This zigzag forms a new leg when the price is moving above or below and passes an ATR volatility threshold. 

Behaviour:
It behaves like the standard zigzag with leg continuity.

Pros:
It can find valid market structure swings, and will never self correct as ATR is non repainting. It doesn't need to perform any candidate erasure, it simply believes in the move that triggers the threshold to know when to flip the leg.

Cons:
It can sometimes be unexpected when the swing search changes. It can change abruptly when the volatility changes significantly. This zigzag can also be lagging a lot which makes ATR an undesirsble choice for extreme search algorithms.


I won't go into the rest, but what is also possible is extreme algorithms based on directional momentum, directional volume pressure, and price acceleration. 

It's also possible to build extreme search algorithms that work like a virtual trailing stop loss. If the market passes the boundary of the virtual trailing stop, the extreme price is written, and the search changes. In fact I found a rare zigzag code before which flipped the extreme search when a trailing stop based threshold was breached on a rolling window of fractals. It was very complex.

Every extreme indicator has its use. None of them are bad. It all depends on the trading system.
 

I would separate the problem into two layers:

  1. Confirmed swing points.
  2. Internal structure points.

If you mix both in one rule, the indicator usually becomes noisy or starts repainting. A confirmed swing needs right-side bars, so it will always have some delay. Internal points can be detected earlier, but they should be treated as lower-confidence structure until price confirms them.

A simple confirmed swing high/low function can start like this:

bool IsSwingHigh(const int i,const double &high[],int depth) { for(int k=1;k<=depth;k++) { if(high[i] <= high[i-k]) return false; if(high[i] <= high[i+k]) return false; } return true; } bool IsSwingLow(const int i,const double &low[],int depth) { for(int k=1;k<=depth;k++) { if(low[i] >= low[i-k]) return false; if(low[i] >= low[i+k]) return false; } return true; }

After that, I would not classify HH/HL/LL/LH from every candle. Store only accepted pivots first, then compare the last accepted pivot with the previous pivot of the same type.

For internal structure, use a smaller depth and add validation rules, for example:

  • minimum distance from the previous pivot;
  • minimum candle range or ATR fraction;
  • break of a previous internal high/low;
  • do not accept two consecutive highs or lows unless the new one is more extreme.

You can keep the data in a small structure:

struct PivotPoint
{
   datetime time;
   double   price;
   int      type;   // 1 high, -1 low
   bool     major;
};

The important part is to decide what you want from the indicator. If you want non-repainting structure, accept the delay. If you want earlier internal points, mark them as provisional and update them until confirmation. Trying to make them early and final at the same time is usually where the logic becomes unstable.