Indicator should not reposition itself (ZigZag extention)

 

Best community,

After lots of research, education on the go and trial and error I have nearly managed to produce my first indicator. I have one issue left which I cannot seem to wrap my head arround yet and hope this community can provide me with some guidance.

The issue at hand: based on the original ZigZag I have a trend signal which in turn produces buy/sell-signals. The point is that the signal repositions itself to the previous low/high when a new high/low is generated by the ZigZag. If the signal is generated before the new High/low the signal excecutes and repositions when the new high/low is established, so no big worries here. But in quick reversals the new high/low is generated before the signal is generated. This means the signal is not excecuted (in an EA)and immediately placed on the previous high/low.


Illustration of first and correctly generated signal which is later repositioned (white arrow = Signal, blue dot = up-trend):

Example = 1H EURUSD @ 2020, july 22th 11:00 (repositions back to high of 06:00)


Correct

Seconds later it repositions to the previous high as a new high is established:

Repositioned


I wanted to add the code but it makes the message to long. Please find it in the attatchment. Apart from esthetics/performance my gut feel tells me it has something to do with the (several) extra loops. Unfortunately, after many hours of research and trial and error I have not managed to figure this one out. Extra info: signal is and shouldbe generated 2 bars after high's/lows to prevent false signals.

Files:
 

Update:

In the script I was referring to the SR-lines for determination of last high/low; SR0[2] <> SR0[3]. When referring to the ZigZag (SR-points) instead of the lines the indicator does not reposition. This does indicate that I should take a closer look at the loops that are defining the SR-lines from the SR-points (which are determined in the only original ZigZag-loop).