This is an expansion of the Tradingview built in Divergences indicator (bottom) with 2 MAJOR differences.
First, and most importantly, the built in indicator identifies pivots in your chosen oscillator, but then utilizes the corresponding candle's HIGH or LOW to identify potential divergences. I'm not a fan of this method because oscillator values are typically calculated using the candle CLOSE values, so, in my opinion, divergences should be identified using the candle CLOSE value as well, as they are in this script.
Second, the built in divergence indicator only looks back one oscillator pivot for potential divergences. I coded this to look back one additional pivot as well to identify more valid potential divergences. The script will only identify these types of "multiple pivot divergences" if the oscillator pivot in between the two diverging pivots DOES NOT intersect the line being drawn them.
Notes for chart:
#1: This built in Divergence indicator misses this hidden bearish divergence because of the pivot in between (marked with red vertical line). No divergence exists between the most recent pivots, but it does if we compare it to the next one back.
#2: The RSI14 is making a lower high here, the first criteria for a bearish divergence. The built in Divergence indicator then references the candles' HIGHS. Because the most recent HIGH exceeds the previous one, it is considered a higher high and incorrectly identified as a bearish divergence. If we use the candle CLOSE price to identify divergences, this does not qualify.
#3: Here, we see both of the updates in action. Neither of these bearish divergences are identified with the built in Divergence Indicator. The first divergence s missed due to the use of candle HIGHS rather than closes; the original HIGH is greater than the next HIGH, however, comparison of closes shows that it is, in fact, a higher CLOSE. The second divergence is missed because original indicator can only look back one pivot and, consequently, misses the divergence between the next one back.
Please note, you may notice while using this script that some of the older divergences do not show any lines between the oscillator pivots. THIS IS NOT A BUG! In order to draw divergence lines properly for multiple pivots back, I had to use the line.new functions rather than plot functions. These line functions will delete old lines when a certain number have been drawn on the chart so these old ones are automatically erased as time passes.