shivmangal
shivmangal

Reputation: 1

Efficient Algorithm to Compute "Highest Connected Wick Candle’s Bar Index" in <=O(log n) Time

I'm developing an indicator (e.g., in ProRealTime or a similar charting platform) where I need to compute, for each candle, the “highest connected wick candle’s bar index.” Two examples help clarify what I mean:

enter image description here

Example 1:
For candle at bar index 0, its upper wick overlaps the body of candle 1, so its answer is 0 (it isn’t connected to any earlier candle).

Example 2:
For candle at bar index 1, its upper wick overlaps with the upper wick of candle 2, and candle 2’s upper wick overlaps with candle 3, and so on. I continue looking “up” (to the left in the chart) until I hit a candle where the body overlaps with the current highest connected wick (this happens at candle 10). In this case, all candles from index 1 to 9 have the same answer: 9.

The idea is:

For a given candle i, traverse backwards (to lower indices) while each candle’s upper wick overlaps with the current chain of connected wicks. Stop the chain when you find a candle where the body (open/close range) overlaps the connected wick.

My current solution uses a for/while loop that checks every previous candle for each new candle, which results in an O(n²) worst-case time complexity. This approach becomes very slow when processing many bars in real time. Here is my code:-

IF (($morningCandle[i] =1 OR $bullishCandle[i]=1 )) then // i'm finding highestConnectedWick candle's  barindex on every bullish candle
 firstHigh = High[barindex-i] // initial candle high
bIndex= i+1
while(bIndex+n >= i ) Do // n= 1000 max allowed to go back
if(high[BarIndex-bIndex] > firstHigh AND open[BarIndex-bIndex] < firstHigh AND close[BarIndex-bIndex] < firstHigh ) then
firstHigh = high[BarIndex-bIndex]
endif
IF( (open[BarIndex-bIndex] < firstHigh AND close[BarIndex-bIndex] > firstHigh) OR (open[BarIndex-bIndex] > firstHigh AND close[BarIndex-bIndex] < firstHigh ) OR (bIndex+n-2 < i) ) then
break
endif
bIndex = bIndex-1
wend
endif
endif

Rules for Highest Connected Wick Calculation:

  1. Start with a given candle (current bar index).

  2. Look left (backward in time) to find the highest connected wick by checking previous candles.

  3. A candle is connected if its upper wick overlaps with the upper wick of any previous candle.

  4. Continue checking backward until:

    • A previous candle’s body (open-close range) overlaps with the highest connected wick found so far → STOP and return the last valid bar index before the overlap.

    • No overlap is found → The candle itself is the highest connected wick (return its own index).

My goal:
Find an algorithm with an overall time complexity of O(n) (or at most O(n log n)) that avoids scanning backwards linearly for every candle.

Upvotes: 0

Views: 26

Answers (0)

Related Questions