0

I try to implement ZigZag Indicator in TypeScript. My ZigZagCalculation function accepts as a parameters: Bar[] bar, deviation: number And returns array with all the zig-zag points.

My bar array has a capacity of x, so every new bar that is added placed on the first index of the array, and the value in the last index of the array is removed.

My question is: can I avoid re-calculation of the ZigZag when new Bar is added,by calculate only the two new ends of the array, instead of iterate the array all over again (in O(n))?

Thank you

My implementation so far includes regular implementation of the ZigZag, and my function returns an object of:

{ highPoints: { index: number; price: Bar }[]; lowPoints: { index: number; price: Bar }[]; } 
5
  • 2
    Do you mind providing more context? I'm guessing that you are trying to detect ZigZag pattern in some financial data. Also your current implementation and Bar object signature would be helpful too Commented Oct 14, 2024 at 12:10
  • When adding a new element in front it is easy to know if it provides a new ZigZag by examining the two next values: add your new value in v[0], then a new zigzag appears if sign(v[1]-v[2]) different than sign(v[0]-v[1]). When removing an element you can examine the three last elements and observe the same: remove a ZigZag if sign(v[last-1]-v[last]) different then sign(v[last-2]-v[last-1]) and remove v[last]. Isn't it what you are looking for? Commented Oct 14, 2024 at 14:38
  • Please provide a detailed example. Commented Oct 17, 2024 at 8:29
  • @VladyslavShlianin I am trying to use ZigZag in a financial manner. In my ZigZag indicator implementation, I calculate turning points (highs and lows) based on a percentage deviation. The algorithm works as follows: 1.Initial Trend Detection: The trend starts as unknown (0), and once the price change exceeds the specified deviation, the trend is set to up (1) or down (-1). 2.Price Change Calculation: I calculate the percentage change from the last pivot point to the current price. If the price change exceeds the deviation, a new pivot point is set (either high or low). (Continue below) Commented Oct 18, 2024 at 19:06
  • @VladyslavShlianin 3. Trend Switching: The algorithm checks if the current price is creating new highs (in an uptrend) or new lows (in a downtrend). If a significant reversal is detected (i.e., price change against the trend exceeds the deviation), the trend switches, and a new zigzag point is added. 4. Tracking Pivot Points: I store high and low points separately, along with the overall ZigZag points. This allows the algorithm to adapt to price volatility dynamically. Commented Oct 18, 2024 at 19:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.