Pivots in Pine Script are great points to use for many scripts and strategies. They’re not without their faults and problems (one of the main issues being the delay required to truly recognize a pivot), but otherwise they’re very useful.
One not-so-obvious issue that you’re likely to run into can happen if you need a zig-zag like pattern, a pivot high, followed by a pivot low, followed by a high, then a low, etc etc etc…
What can happen is you can have a pivot high after a pivot high, without a pivot low in between.
How to Solve Same Direction Pivots
What’d I would suggest here is creating a variable that tracks all pivot points.
isPivot == isPivotHigh or isPivotLow
Then whenever you find a new pivot, compare it against the previous one to see if its in the same direction.
For this example, let’s say we’re plotting our pivots and want to retain the zig-zag like pattern. We’ll want a variable for
- Holding pivot highs
isPivotHigh
- Holding pivot lows
isPivotLow
- Holding all pivots
isPivot
- Holding the pivots we want to plot
plotThisHigh
It might look something like this:
isPivotHigh = pivothigh(high, 5, 5)
isPivotLow = pivotlow(low, 5, 5)
isPivot = isPivotHigh or isPivotLow
plotThisHigh = isPivotHigh // assume we do want to plot this high
if isPivotHigh
sameDirection = valuewhen(isPivot, isPivotHigh, 0) // check if the previous pivot was also a high
plotThisHigh := !sameDirection // reassign our plotting var if its not the same direction
The code above shows how you might handle this for pivot highs. You can duplicate the last four lines to do the same logic for pivot lows.
Why Use This Strategy
The reason why I recommend using a separate variable for plotting (plotThisHigh
as opposed to resassigning or redefining isPivotHigh
) is because the following. Imagine there are three pivotHighs in a row (with no pivotLows in between). If you reassign pivotHigh
the logic will no longer work since calculating sameDirection
correctly depends on isPivotHigh
.
Again, do the same for isPivotLow
using a var likeplotThisLow
.
We’re Done!
This was a basic Pine Script tutorial on how to use pivots. The pivothigh function and pivotlow function are great and very convenient, but beware of the pitfalls mentioned in this article.
Need help with Pine Script? Did this article not mention something you’re looking for? Just reach out in our Discord server ????