LibPvot

This is a library for advanced technical analysis, specializing
in two core areas: the detection of price-oscillator
divergences and the analysis of market structure. It provides
a back-end engine for signal detection and a toolkit for
indicator plotting.
Key Features:
1. **Complete Divergence Suite (Class A, B, C):** The engine detects
all three major types of divergences, providing a full spectrum of
analytical signals:
- **Regular (A):** For potential trend reversals.
- **Hidden (B):** For potential trend continuations.
- **Exaggerated (C):** For identifying weakness at double tops/bottoms.
2. **Advanced Signal Filtering:** The detection logic uses a
percentage-based price tolerance (`prcTol`). This feature
enables the practical detection of Exaggerated divergences
(which rarely occur at the exact same price) and creates a
"dead zone" to filter insignificant noise from triggering
Regular divergences.
3. **Pivot Synchronization:** A bar tolerance (`barTol`) is used
to reliably match price and oscillator pivots that do not
align perfectly on the same bar, preventing missed signals.
4. **Signal Invalidation Logic:** Features two built-in invalidation
rules:
- An optional `invalidate` parameter automatically terminates
active divergences if the price or the oscillator breaks
the level of the confirming pivot.
- The engine also discards 'half-pivots' (e.g., a price pivot)
if a corresponding oscillator pivot does not appear within
the `barTol` window.
5. **Stateful Plotting Helpers:** Provides helper functions
(`bullDivPos` and `bearDivPos`) that abstract away the
state management issues of visualizing persistent signals.
They generate gap-free, accurately anchored data series
ready to be used in `plotshape` functions, simplifying
indicator-side code.
6. **Rich Data Output:** The core detection functions (`bullDiv`, `bearDiv`)
return a comprehensive 9-field data tuple. This includes the
boolean flags for each divergence type and the precise
coordinates (price, oscillator value, bar index) of both the
starting and the confirming pivots.
7. **Market Structure & Trend Analysis:** Includes a
`marketStructure` function to automatically identify pivot
highs/lows, classify their relationship (HH, LH, LL, HL),
detect structure breaks, and determine the current trend
state (Up, Down, Neutral) based on pivot sequences.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
bullDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
Detects bullish divergences (Regular, Hidden, Exaggerated) based on pivot lows.
Parameters:
priceSrc (float): series float Price series to check for pivots (e.g., `low`).
oscSrc (float): series float Oscillator series to check for pivots.
leftLen (int): series int Number of bars to the left of a pivot (default 5).
rightLen (int): series int Number of bars to the right of a pivot (default 5).
depth (int): series int Maximum number of stored pivot pairs to check against (default 2).
barTol (int): series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
prcTol (float): series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
persist (bool): series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
invalidate (bool): series bool If `true` (default), terminates an active divergence if price or oscillator break
below the confirming pivot low.
Returns: [regBull, hidBull, exgBull, initPivotPrc, initPivotOsz, initPivotBar, lastPivotPrc, lastPivotOsz, lastPivotBar] A tuple containing comprehensive data for a detected bullish divergence.
regBull series bool `true` if a Regular bullish divergence (Class A) is active.
hidBull series bool `true` if a Hidden bullish divergence (Class B) is active.
exgBull series bool `true` if an Exaggerated bullish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot low.
initPivotOsz series float Oscillator value of the initial pivot low.
initPivotBar series int Bar index of the initial pivot low.
lastPivotPrc series float Price value of the last (confirming) pivot low.
lastPivotOsz series float Oscillator value of the last pivot low.
lastPivotBar series int Bar index of the last pivot low.
bearDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
Detects bearish divergences (Regular, Hidden, Exaggerated) based on pivot highs.
Parameters:
priceSrc (float): series float Price series to check for pivots (e.g., `high`).
oscSrc (float): series float Oscillator series to check for pivots.
leftLen (int): series int Number of bars to the left of a pivot (default 5).
rightLen (int): series int Number of bars to the right of a pivot (default 5).
depth (int): series int Maximum number of stored pivot pairs to check against (default 2).
barTol (int): series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
prcTol (float): series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
persist (bool): series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
invalidate (bool): series bool If `true` (default), terminates an active divergence if price or oscillator break
above the confirming pivot high.
Returns: [regBear, hidBear, exgBear, initPivotPrc, initPivotOsz, initPivotBar, lastPivotPrc, lastPivotOsz, lastPivotBar] A tuple containing comprehensive data for a detected bearish divergence.
regBear series bool `true` if a Regular bearish divergence (Class A) is active.
hidBear series bool `true` if a Hidden bearish divergence (Class B) is active.
exgBear series bool `true` if an Exaggerated bearish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot high.
initPivotOsz series float Oscillator value of the initial pivot high.
initPivotBar series int Bar index of the initial pivot high.
lastPivotPrc series float Price value of the last (confirming) pivot high.
lastPivotOsz series float Oscillator value of the last pivot high.
lastPivotBar series int Bar index of the last pivot high.
bullDivPos(regBull, hidBull, exgBull, rightLen, yPos)
Calculates the plottable data series for bullish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
Parameters:
regBull (bool): series bool The regular bullish divergence flag from `bullDiv`.
hidBull (bool): series bool The hidden bullish divergence flag from `bullDiv`.
exgBull (bool): series bool The exaggerated bullish divergence flag from `bullDiv`.
rightLen (int): series int The same `rightLen` value used in `bullDiv` for correct timing.
yPos (float): series float The series providing the base Y-coordinate for the shapes (e.g., `low`).
Returns: [regBullPosY, hidBullPosY, exgBullPosY] A tuple of three `series float` for plotting bullish divergences.
regBullPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBullPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBullPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
bearDivPos(regBear, hidBear, exgBear, rightLen, yPos)
Calculates the plottable data series for bearish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
Parameters:
regBear (bool): series bool The regular bearish divergence flag from `bearDiv`.
hidBear (bool): series bool The hidden bearish divergence flag from `bearDiv`.
exgBear (bool): series bool The exaggerated bearish divergence flag from `bearDiv`.
rightLen (int): series int The same `rightLen` value used in `bearDiv` for correct timing.
yPos (float): series float The series providing the base Y-coordinate for the shapes (e.g., `high`).
Returns: [regBearPosY, hidBearPosY, exgBearPosY] A tuple of three `series float` for plotting bearish divergences.
regBearPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBearPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBearPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
marketStructure(highSrc, lowSrc, leftLen, rightLen, srcTol)
Analyzes the market structure by identifying pivot points, classifying
their sequence (e.g., Higher Highs, Lower Lows), and determining the
prevailing trend state.
Parameters:
highSrc (float): series float Price series for pivot high detection (e.g., `high`).
lowSrc (float): series float Price series for pivot low detection (e.g., `low`).
leftLen (int): series int Number of bars to the left of a pivot (default 5).
rightLen (int): series int Number of bars to the right of a pivot (default 5).
srcTol (float): series float Percentage tolerance to consider two pivots as 'equal' (default 0.05%).
Returns: [pivType, lastPivHi, lastPivLo, lastPiv, pivHiBroken, pivLoBroken, trendState] A tuple containing detailed market structure information.
pivType series PivType The type of the most recently formed pivot (e.g., `hh`, `ll`).
lastPivHi series float The price level of the last confirmed pivot high.
lastPivLo series float The price level of the last confirmed pivot low.
lastPiv series float The price level of the last confirmed pivot (either high or low).
pivHiBroken series bool `true` if the price has broken above the last pivot high.
pivLoBroken series bool `true` if the price has broken below the last pivot low.
trendState series TrendState The current trend state (`up`, `down`, or `neutral`).
Perpustakaan Pine
Dalam semangat sebenar TradingView, penulis telah menerbitkan kod Pine ini sebagai perpustakaan sumber terbuka supaya pengaturcara Pine lain dari komuniti kami boleh menggunakannya semula. Sorakan kepada penulis! Anda juga boleh menggunakan perpustakaan ini secara peribadi atau dalam penerbitan sumber terbuka lain, tetapi penggunaan semula kod ini dalam penerbitan adalah tertakluk kepada Peraturan Dalaman.
Penafian
Perpustakaan Pine
Dalam semangat sebenar TradingView, penulis telah menerbitkan kod Pine ini sebagai perpustakaan sumber terbuka supaya pengaturcara Pine lain dari komuniti kami boleh menggunakannya semula. Sorakan kepada penulis! Anda juga boleh menggunakan perpustakaan ini secara peribadi atau dalam penerbitan sumber terbuka lain, tetapi penggunaan semula kod ini dalam penerbitan adalah tertakluk kepada Peraturan Dalaman.