Intra Bar Volume ProfileThis indicator provides a high-resolution volume profile analysis for every single bar on the chart. It builds this profile by sampling data from a lower intra-bar timeframe, allowing for a granular view of price distribution and buying/selling pressure within the bar.
Key Features:
Intra-Bar Profile Engine: For each bar on the main chart, the indicator builds a complete volume profile on a lower 'Intra-Bar Timeframe'. It uses:
Statistical Models ('Allot model'): Distributes volume across price levels using 'PDF' (Probability Density Function) or 'Classic' (close) methods.
Buy/Sell Classifiers ('Volume Estimator'): Splits volume using a 'Dynamic' (trend/wick-based) or 'Classic' (candle color) model.
On-Chart Visualization (Overlay): The analysis is rendered directly onto the price bars:
Point of Control (POC): A line showing the price level with the most volume for that bar.
Value Area (VA): A colored box representing the price range where the specified percentage (e..g., 50%) of volume was traded.
VWAP: Displays the volume-weighted average price (VWAP) for the bar as a separate line.
Integrated Alerts: Includes 8 alerts that trigger when the main price crosses over or under the key intra-bar levels: POC, VWAP, and the Value Area High/Low.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMM
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Market Structure Volume ProfileThis indicator visualizes volume profiles that are dynamically anchored to market structure events, rather than fixed time intervals. It builds these profiles using high-resolution intra-bar data to provide a precise view of where value is established during critical market phases.
Key Features:
Event-Based Profile Anchoring: The indicator starts a new profile based on one of three user-selected events ('Profile Anchor'):
Swing: A new profile begins when the 'impulse baseline' (derived from intra-bar delta) changes. This baseline adjusts when a new price pivot is confirmed: When a price high forms, the baseline moves to the lower of its previous level or the peak delta (max of delta O/C) at the pivot. When a price low forms, it moves to the higher of its previous level or the trough delta (min of delta O/C) at the pivot.
Structure: A new profile begins immediately on the bar that confirms a market structure break (e.g., a new HH or LL, based on a sequence of price pivots).
Delta: A new profile begins immediately on the bar that confirms a break in the cumulative delta's market structure (e.g., a new HH or LL in the delta). Both 'Swing' and 'Delta' anchors are derived from the same continuous (non-resetting) Cumulative Volume Profile Delta (CVPD), which is built from the intra-bar statistical analysis.
Statistical Profile Engine: For each bar in the anchored period, the indicator builds a volume profile on a lower 'Intra-Bar Timeframe'. Instead of simple tick counting, it uses advanced statistical models:
Allocation ('Allot model'): 'PDF' (Probability Density Function) distributes volume proportionally across the bar's range based on an assumed statistical model (e.g., T4-Skew). 'Classic' assigns all volume to the close.
Buy/Sell Split ('Volume Estimator'): 'Dynamic' applies a model that analyzes candle wicks and recent trend to estimate buy/sell pressure. 'Classic' classifies all volume based on the candle color.
Visualization & Lag: The indicator plots the final profile (as a polygon) and the developing statistical lines (POC, VA, VWAP, StdDev).
Note on Lag: All anchor events require Pivot Right Bars for confirmation.
In 'Structure' and 'Delta' mode, the developing lines (POC, VA, etc.) are plotted using a non-repainting method (showing the value from pivRi bars ago).
In 'Swing' mode, the profile is plotted retroactively, starting from the bar where the pivot occurred. The developing lines are also plotted with this full pivRi lag to align with the past data.
Flexible Display Modes: The finalized profile can be displayed in three ways: 'Up/Down' (buy vs. sell), 'Total' (combined volume), and 'Delta' (net difference).
Dynamic Row Sizing: Includes an option ('Rows per Percent') to automatically adjust the number of profile rows (buckets) based on the profile's price range.
Integrated Alerts: Includes 13 alerts that trigger for:
A new profile reset ('Profile was resetted').
Price crossing any of the 6 developing levels (POC, VA High/Low, VWAP, StdDev High/Low).
Alert Lag Assumption: In 'Swing' mode, alerts are delayed to match the retroactively plotted lines. In 'Structure' and 'Delta' modes, alerts fire in real-time based on the current price crossing the current (repainting) value of the metric, which may differ from the non-repainting plotted line.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This includes the values used for real-time alerts in 'Structure' and 'Delta' modes.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Periodic Volume ProfileThis indicator visualizes volume profiles that are dynamically anchored to market structure events, rather than fixed time intervals. It builds these profiles using high-resolution intra-bar data to provide a precise view of where value is established during critical market phases.
Key Features:
Event-Based Profile Anchoring: The indicator starts a new profile based on one of three user-selected events ('Profile Anchor'):
Swing: A new profile begins when the 'impulse baseline' (derived from delta) changes. This baseline adjusts when a new price pivot is confirmed: When a price high forms, the baseline moves to the lower of its previous level or the peak delta (max of delta O/C) at the pivot. When a price low forms, it moves to the higher of its previous level or the trough delta (min of delta O/C).
Structure: A new profile begins immediately on the bar that confirms a market structure break (e.g., a new HH or LL, based on a sequence of price pivots).
Delta: A new profile begins immediately on the bar that confirms a break in the cumulative delta's market structure (e.g., a new HH or LL in the delta).
Statistical Profile Engine: For each bar in the anchored period, the indicator builds a volume profile on a lower 'Intra-Bar Timeframe'. It uses:
Statistical Models ('Allot model'): Distributes volume across price levels using 'PDF' (Probability Density Function) or 'Classic' (close) methods.
Buy/Sell Classifiers ('Volume Estimator'): Splits volume using a 'Dynamic' (trend/wick-based) or 'Classic' (candle color) model.
Note on Anchor Lag: The different anchor types have different delays. 'Structure' and 'Delta' profiles begin in real-time on the confirmation bar. The 'Swing' profile calculation is plotted retroactively to the pivot's origin, as the pivot is only confirmed Pivot Right Bars after it occurs.
Flexible Visualization Modes: The finalized profile (plotted at the end of each period) can be displayed in three ways: 'Up/Down' (buy vs. sell), 'Total' (combined volume), and 'Delta' (net difference).
Developing Real-Time Metrics: The indicator plots the developing Point of Control (POC), Value Area (VA), VWAP, and Standard Deviation bands in real-time as the new profile forms.
Dynamic Row Sizing: Includes an option ('Rows per Percent') to automatically adjust the number of profile rows (buckets) based on the profile's price range, maintaining a consistent visual density.
Integrated Alerts: Includes 13 alerts that trigger for:
A new profile reset ('Profile was resetted').
Price crossing any of the 6 developing levels (POC, VA High/Low, VWAP, StdDev High/Low).
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Pivot Orderflow DeltaThis indicator analyzes order flow by calculating a continuous Cumulative Volume Profile Delta (CVPD). It plots this delta as a series of "delta candles" and identifies divergences and structural pivot levels.
Key Features:
Statistical Delta Engine: For each bar, the indicator builds a high-resolution volume profile on a lower 'Intra-Bar Timeframe'. It uses statistical models ('PDF' allocation) and advanced classifiers ('Dynamic' split) to determine the buy/sell pressure, which is then accumulated.
Cumulative Delta Candle Visualization: The indicator plots the continuous, accumulated delta as a series of candles, where for each bar:
Open: Is the cumulative delta value of the previous bar.
Close: Is the new total cumulative delta.
High/Low: Represent the peak/trough cumulative delta reached during that bar's formation.
Dynamic Pivot Baseline: The indicator plots a separate dynamic baseline ('Impulse Start') that adjusts when a new price pivot is confirmed.
When a price high forms, the baseline moves to the lower of its previous level or the peak delta (max of delta candle O/C) at the pivot.
When a price low forms, the baseline moves to the higher of its previous level or the trough delta (min of delta candle O/C) at the pivot.
Full Divergence Suite (Class A, B, C): A built-in divergence engine automatically detects and plots Regular (A), Hidden (B), and Exaggerated (C) divergences between price and the peak/trough of the delta candles (High/Low).
Detailed Pivot Confluence: The indicator plots distinct markers to differentiate between pivots occurring only on the price chart, only on the delta oscillator, or on both simultaneously.
Note on Confirmation (Lag): Divergence and pivot signals rely on a confirmation method. A pivot is only plotted after the Pivot Right Bars input has passed, which introduces an inherent lag.
Integrated Alerts: Includes 23 comprehensive alerts for:
The start and end of all 6 divergence types.
The detection of a new Impulse Start pivot.
Delta/volume agreement/disagreement.
Delta crossing the zero line.
The formation of price-only or delta-only pivots.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Cumulative Volume Profile DeltaThis indicator calculates the Cumulative Volume Profile Delta (CVPD). It constructs a high-resolution volume profile for each bar using intra-bar data, then derives and accumulates the delta from that profile to show net buying/selling pressure.
Key Features:
Statistical Volume Profile Engine: For each bar, the indicator builds a high-resolution volume profile on a lower 'Intra-Bar Timeframe'. Instead of simple tick counting, it uses statistical models ('PDF' allocation) to distribute volume across price levels and advanced classifiers ('Dynamic' split) to determine the buy/sell pressure before accumulation.
Periodic Accumulation: The CVPD accumulation is anchored to a user-defined 'Anchor Timeframe' (e.g., daily, weekly). This cyclical reset allows to analyze the build-up of pressure within specific trading periods.
"Delta Candle" Visualization: The periodic CVPD is shown as a candle, where:
Open: The CVPD value at the start of the period (or zero).
High/Low: Represent the peak buying (CVD High) and selling (CVD Low) pressure within that period's profile.
Close: The final net delta value (CVD) for the period.
Dual CVD & Divergence Engine: The indicator calculates two CVPDs: a Periodic one (for plotting) and a Continuous one (non-resetting). The continuous line is used as a stable source for the built-in divergence engine (detecting Regular, Hidden, and Exaggerated).
Dynamic Divergence Plotting: Divergence markers are plotted relative to the periodic (candle) CVPD. They automatically adjust their vertical position after a reset to remain visually aligned with the plotted candles.
Note on Confirmation (Lag): Divergence signals rely on a pivot confirmation method to ensure they do not repaint.
The Start of a- divergence is only detected after the confirming pivot is fully formed (a delay based on Pivot Right Bars).
The End of a divergence is detected either instantly (if the signal is invalidated by price action) or with a delay (when a new, non-divergent pivot is confirmed).
Multi-Timeframe (MTF) Capability:
MTF Output: The entire analysis (Delta Candles, Divergences) can be calculated on a higher timeframe (using the Timeframe input), with standard options to handle gaps (Fill Gaps) and prevent repainting (Wait for...).
Limitation: The Divergence detection engine (pivDiv) is disabled if a Higher Timeframe (HTF) is selected.
Integrated Alerts: Includes 18 comprehensive alerts for:
The start and end of all 6 divergence types.
The periodic CVPD crossing the zero line.
Conditions of agreement or disagreement between the delta and the main bar's direction.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.Example: crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
Volume Profile DeltaThis indicator calculates the Volume Profile Delta (VPD). It constructs a high-resolution volume profile for each bar using intra-bar data, offering a detailed understanding of buying and selling pressure at discrete price levels.
Key Features:
Statistical Volume Profile Engine: For each bar, the indicator builds a high-resolution volume profile on a lower 'Intra-Bar Timeframe'. Instead of simple tick counting, it uses statistical models ('PDF' allocation) to distribute volume across price levels and advanced classifiers ('Dynamic' split) to determine the buy/sell pressure within that profile, providing a more nuanced delta calculation.
"Delta Candle" Visualization: The per-bar VPD is displayed as a candle, where:
Open: Always anchored at the zero line.
High/Low: Represent the peak buying (CVD High) and selling (CVD Low) pressure accumulated within that bar's profile.
Close: The final net delta value (CVD) for the bar.
Customizable Moving Average: An optional moving average of the net delta (Close) can be added. The MA type, length, and an optional Volume weighted setting are customizable.
Intra-Bar Peak Pivot Detection: Automatically identifies and plots significant turning points (pivots) in the peak buying (High) and selling (Low) pressure.
Note on Confirmation (Lag): Pivot signals are confirmed using a lookback method. A pivot is only plotted after the Pivot Right Bars input has passed, which introduces an inherent lag.
Multi-Timeframe (MTF) Capability:
MTF Output: The entire analysis (Delta Candles, MA, Pivots) can be calculated on a higher timeframe (using the Timeframe input), with standard options to handle gaps (Fill Gaps) and prevent repainting (Wait for...).
Limitation: The Pivot detection (Calculate Pivots) is disabled if a Higher Timeframe (HTF) is selected.
Integrated Alerts: Includes 8 alerts for:
The net delta crossing its moving average.
The detection of new peak buying or selling pivots.
Conditions of agreement or disagreement between the net delta and the main bar's direction.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration.
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Script®. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**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.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
Construct a new `VProf` object with fixed bucket count & range.
Parameters:
buckets (int) : series int number of price buckets ≥ 1
rangeUp (float) : series float upper price bound (absolute)
rangeLo (float) : series float lower price bound (absolute)
dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
trendLen (int) : series int Look‑back bars for trend factor (default 3)
Returns: VProf freshly initialised profile
method clone(self)
Create a deep copy of the volume profile.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object to copy
Returns: VProf A new, independent copy of the profile
method clear(self)
Reset all bucket tallies while keeping configuration intact.
Namespace types: VProf
Parameters:
self (VProf) : VProf profile object
Returns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
Merges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
Namespace types: VProf
Parameters:
self (VProf) : VProf The target profile object to merge into.
srcABuy (array) : array The source profile's buy volume bucket array.
srcASell (array) : array The source profile's sell volume bucket array.
srcRangeUp (float) : series float The upper price bound of the source profile.
srcRangeLo (float) : series float The lower price bound of the source profile.
srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
Returns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
Add current bar’s volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimator’s CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
offset (int) : series int To offset the calculated bar
Returns: VProf `self` (method chaining)
method setBuckets(self, buckets)
Sets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
buckets (int) : series int The new number of buckets
Returns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
Sets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
rangeUp (float) : series float The new upper price bound
rangeLo (float) : series float The new lower price bound
Returns: VProf `self` (chaining)
method setValueArea(self, valueArea)
Set the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
valueArea (int) : series int The new Value Area percentage (0..100)
Returns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
Get Buy volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Buy volume ≥ 0
method getBktSellVol(self, idx)
Get Sell volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Sell volume ≥ 0
method getBktBnds(self, idx)
Get Bounds of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
Get POC information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
Get Value Area (VA) information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
Get the profile's median price and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
Get the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
Get the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
Namespace types: VProf
Parameters:
self (VProf) : VProf The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
Cumulative Volume Delta (CVD) like metric over all buckets.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
VProf Bucketed Buy/Sell volume profile plus meta information.
Fields:
buckets (series int) : int Number of price buckets (granularity ≥1)
rangeUp (series float) : float Upper price range (absolute)
rangeLo (series float) : float Lower price range (absolute)
dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
cdfSteps (series int) : int Simpson integration resolution (even ≥2)
split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
trendLen (series int) : int Look‑back length for trend factor (≥1)
maxBkt (series int) : int User-defined number of buckets (unclamped)
aBuy (array) : array Buy volume per bucket
aSell (array) : array Sell volume per bucket
cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
poc (series int) : int Index of max‑volume bucket (POC). Is `na` until calculated.
vaUp (series int) : int Index of upper Value‑Area bound. Is `na` until calculated.
vaLo (series int) : int Index of lower value‑Area bound. Is `na` until calculated.
median (series float) : float Median price of the volume distribution. Is `na` until calculated.
vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
LibBrStLibrary "LibBrSt"
This is a library for quantitative analysis, designed to estimate
the statistical properties of price movements *within* a single
OHLC bar, without requiring access to tick data. It provides a
suite of estimators based on various statistical and econometric
models, allowing for analysis of intra-bar volatility and
price distribution.
Key Capabilities:
1. **Price Distribution Models (`PriceEst`):** Provides a selection
of estimators that model intra-bar price action as a probability
distribution over the range. This allows for the
calculation of the intra-bar mean (`priceMean`) and standard
deviation (`priceStdDev`) in absolute price units. Models include:
- **Symmetric Models:** `uniform`, `triangular`, `arcsine`,
`betaSym`, and `t4Sym` (Student-t with fat tails).
- **Skewed Models:** `betaSkew` and `t4Skew`, which adjust
their shape based on the Open/Close position.
- **Model Assumptions:** The skewed models rely on specific
internal constants. `betaSkew` uses a fixed concentration
parameter (`BETA_SKEW_CONCENTRATION = 4.0`), and `t4Sym`/`t4Skew`
use a heuristic scaling factor (`T4_SHAPE_FACTOR`)
to map the distribution.
2. **Econometric Log-Return Estimators (`LogEst`):** Includes a set of
econometric estimators for calculating the volatility (`logStdDev`)
and drift (`logMean`) of logarithmic returns within a single bar.
These are unit-less measures. Models include:
- **Parkinson (1980):** A High-Low range estimator.
- **Garman-Klass (1980):** An OHLC-based estimator.
- **Rogers-Satchell (1991):** An OHLC estimator that accounts
for non-zero drift.
3. **Distribution Analysis (PDF/CDF):** Provides functions to work
with the Probability Density Function (`pricePdf`) and
Cumulative Distribution Function (`priceCdf`) of the
chosen price model.
- **Note on `priceCdf`:** This function uses analytical (exact)
calculations for the `uniform`, `triangular`, and `arcsine`
models. For all other models (e.g., `betaSkew`, `t4Skew`),
it uses **numerical integration (Simpson's rule)** as
an approximation of the cumulative probability.
4. **Mathematical Functions:** The library's Beta distribution
models (`betaSym`, `betaSkew`) are supported by an internal
implementation of the natural log-gamma function, which is
based on the Lanczos approximation.
---
**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.
priceStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) *in price units* for the current
bar, according to the chosen `PriceEst` distribution assumption.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ ≥ 0 ; `na` if undefined (e.g. zero range).
priceMean(estimator, offset)
Estimates **μ̂** (mean price) for the chosen `PriceEst` within the
current bar.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ in price units.
pricePdf(estimator, price, offset)
Probability-density under the chosen `PriceEst` model.
**Returns 0** when `p` is outside the current bar’s .
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
price (float) : series float Price level to evaluate.
offset (int) : series int To offset the calculated bar
Returns: series float Density value.
priceCdf(estimator, upper, lower, steps, offset)
Cumulative probability **between** `upper` and `lower` under
the chosen `PriceEst` model. Outside-bar regions contribute zero.
Uses a fast, analytical calculation for Uniform, Triangular, and
Arcsine distributions, and defaults to numerical integration
(Simpson's rule) for more complex models.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
upper (float) : series float Upper Integration Boundary.
lower (float) : series float Lower Integration Boundary.
steps (int) : series int # of sub-intervals for numerical integration (if used).
offset (int) : series int To offset the calculated bar.
Returns: series float Probability mass ∈ .
logStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) of *log-returns* for the current bar.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ (unit-less); `na` if undefined.
logMean(estimator, offset)
Estimates μ̂ (mean log-return / drift) for the chosen `LogEst`.
The returned value is consistent with the assumptions of the
selected volatility estimator.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ (unit-less log-return).
PDF Smoothed Moving Average [BackQuant]PDF Smoothed Moving Average
Introducing BackQuant’s PDF Smoothed Moving Average (PDF-MA) — an innovative trading indicator that applies Probability Density Function (PDF) weighting to moving averages, creating a unique, trend-following tool that offers adaptive smoothing to price movements. This advanced indicator gives traders an edge by blending PDF-weighted values with conventional moving averages, helping to capture trend shifts with enhanced clarity.
Core Concept: Probability Density Function (PDF) Smoothing
The Probability Density Function (PDF) provides a mathematical approach to applying adaptive weighting to data points based on a specified variance and mean. In the PDF-MA indicator, the PDF function is used to weight price data, adding a layer of probabilistic smoothing that enhances the detection of trend strength while reducing noise.
The PDF weights are controlled by two key parameters:
Variance: Determines the spread of the weights, where higher values spread out the weighting effect, providing broader smoothing.
Mean : Centers the weights around a particular price value, influencing the trend’s directionality and sensitivity.
These PDF weights are applied to each price point over the chosen period, creating an adaptive and smooth moving average that more closely reflects the underlying price trend.
Blending PDF with Standard Moving Averages
To further improve the PDF-MA, this indicator combines the PDF-weighted average with a traditional moving average, selected by the user as either an Exponential Moving Average (EMA) or Simple Moving Average (SMA). This blended approach leverages the strengths of each method: the responsiveness of PDF smoothing and the robustness of conventional moving averages.
Smoothing Method: Traders can choose between EMA and SMA for the additional moving average layer. The EMA is more responsive to recent prices, while the SMA provides a consistent average across the selected period.
Smoothing Period: Controls the length of the lookback period, affecting how sensitive the average is to price changes.
The result is a PDF-MA that provides a reliable trend line, reflecting both the PDF weighting and traditional moving average values, ideal for use in trend-following and momentum-based strategies.
Trend Detection and Candle Coloring
The PDF-MA includes a built-in trend detection feature that dynamically colors candles based on the direction of the smoothed moving average:
Uptrend: When the PDF-MA value is increasing, the trend is considered bullish, and candles are colored green, indicating potential buying conditions.
Downtrend: When the PDF-MA value is decreasing, the trend is considered bearish, and candles are colored red, signaling potential selling or shorting conditions.
These color-coded candles provide a quick visual reference for the trend direction, helping traders make real-time decisions based on the current market trend.
Customization and Visualization Options
This indicator offers a range of customization options, allowing traders to tailor it to their specific preferences and trading environment:
Price Source : Choose the price data for calculation, with options like close, open, high, low, or HLC3.
Variance and Mean : Fine-tune the PDF weighting parameters to control the indicator’s sensitivity and responsiveness to price data.
Smoothing Method : Select either EMA or SMA to customize the conventional moving average layer used in conjunction with the PDF.
Smoothing Period : Set the lookback period for the moving average, with a longer period providing more stability and a shorter period offering greater sensitivity.
Candle Coloring : Enable or disable candle coloring based on trend direction, providing additional clarity in identifying bullish and bearish phases.
Trading Applications
The PDF Smoothed Moving Average can be applied across various trading strategies and timeframes:
Trend Following : By smoothing price data with PDF weighting, this indicator helps traders identify long-term trends while filtering out short-term noise.
Reversal Trading : The PDF-MA’s trend coloring feature can help pinpoint potential reversal points by showing shifts in the trend direction, allowing traders to enter or exit positions at optimal moments.
Swing Trading : The PDF-MA provides a clear trend line that swing traders can use to capture intermediate price moves, following the trend direction until it shifts.
Final Thoughts
The PDF Smoothed Moving Average is a highly adaptable indicator that combines probabilistic smoothing with traditional moving averages, providing a nuanced view of market trends. By integrating PDF-based weighting with the flexibility of EMA or SMA smoothing, this indicator offers traders an advanced tool for trend analysis that adapts to changing market conditions with reduced lag and increased accuracy.
Whether you’re trading trends, reversals, or swings, the PDF-MA offers valuable insights into the direction and strength of price movements, making it a versatile addition to any trading strategy.
Likelihood of Winning - Probability Density FunctionIn developing the "Likelihood of Winning - Probability Density Function (PDF)" indicator, my aim was to offer traders a statistical tool to quantify the probability of reaching target prices. This indicator, grounded in risk assessment principles, enables users to analyze potential outcomes based on the normal distribution, providing insights into market dynamics.
The tool's flexibility allows for customization of the data series, lookback periods, and target settings for both long and short scenarios. It features a color-coded visualization to easily distinguish between probabilities of hitting specified targets, enhancing decision-making in trading strategies.
I'm excited to share this indicator with the trading community, hoping it will enhance data-driven decision-making and offer a deeper understanding of market risks and opportunities. My goal is to continuously improve this tool based on user feedback and market evolution, contributing to more informed trading practices.
This indicator leverages the "NormalDistributionFunctions" library, enabling easy integration into other indicators or strategies. Users can readily embed advanced statistical analysis into their trading tools, fostering innovation within the Pine Script community.
PDFMA Awesome Oscillator [Loxx]Theory:
Bill Williams's Awesome Oscillator Technical Indicator (AO) is a 34-period simple moving average, plotted through the bars midpoints (H+L)/2, which is subtracted from the 5-period simple moving average, built across the bars midpoints (H+L)/2. It shows us quite clearly what’s happening to the market driving force at the present moment.
This version uses PdfMA (Probability Density Function weighted Moving Average) instead of SMA (Simple Moving Average). This is a deviation from the original AO since in the AO since there is no parameter that you can change, but with this version, you can change the variance part of the PdfMA calculation. That way you can get different values for the AO even without changing periods of calculation (the general rule of thumb is: the greater the variance, the smoother the result)
Usage:
You can use color changes (mainly on zero cross) for trend change signals
ATR-Stepped PDF MA [Loxx]ATR-Stepped PDF MA is and ATR-stepped moving average that uses a probability density function moving average.
What is Probability Density Function?
Probability density function based MA is a sort of weighted moving average that uses probability density function to calculate the weights.
Included:
-Toggle on/off bar coloring
-Toggle on/off signals
-Alerts long/short
Probability Density Function based MA MACD [Loxx]Probability Density Function based MA MACD is a MACD indicator using a type of weighted moving average.
What is Probability Density Function based MA MACD?
Probability density function based MA is a sort of weighted moving average that uses probability density function to calculate the weights.
Included:
-Toggle on/off bar coloring
MathProbabilityDistributionLibrary "MathProbabilityDistribution"
Probability Distribution Functions.
name(idx) Indexed names helper function.
Parameters:
idx : int, position in the range (0, 6).
Returns: string, distribution name.
usage:
.name(1)
Notes:
(0) => 'StdNormal'
(1) => 'Normal'
(2) => 'Skew Normal'
(3) => 'Student T'
(4) => 'Skew Student T'
(5) => 'GED'
(6) => 'Skew GED'
zscore(position, mean, deviation) Z-score helper function for x calculation.
Parameters:
position : float, position.
mean : float, mean.
deviation : float, standard deviation.
Returns: float, z-score.
usage:
.zscore(1.5, 2.0, 1.0)
std_normal(position) Standard Normal Distribution.
Parameters:
position : float, position.
Returns: float, probability density.
usage:
.std_normal(0.6)
normal(position, mean, scale) Normal Distribution.
Parameters:
position : float, position in the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.normal(0.6)
skew_normal(position, skew, mean, scale) Skew Normal Distribution.
Parameters:
position : float, position in the distribution.
skew : float, skewness of the distribution.
mean : float, mean of the distribution, default=0.0 for standard distribution.
scale : float, scale of the distribution, default=1.0 for standard distribution.
Returns: float, probability density.
usage:
.skew_normal(0.8, -2.0)
ged(position, shape, mean, scale) Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.ged(0.8, -2.0)
skew_ged(position, shape, skew, mean, scale) Skew Generalized Error Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_ged(0.8, 2.0, 1.0)
student_t(position, shape, mean, scale) Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.student_t(0.8, 2.0, 1.0)
skew_student_t(position, shape, skew, mean, scale) Skew Student-T Distribution.
Parameters:
position : float, position.
shape : float, shape.
skew : float, skew.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
Returns: float, probability.
usage:
.skew_student_t(0.8, 2.0, 1.0)
select(distribution, position, mean, scale, shape, skew, log) Conditional Distribution.
Parameters:
distribution : string, distribution name.
position : float, position.
mean : float, mean, default=0.0 for standard distribution.
scale : float, scale, default=1.0 for standard distribution.
shape : float, shape.
skew : float, skew.
log : bool, if true apply log() to the result.
Returns: float, probability.
usage:
.select('StdNormal', __CYCLE4F__, log=true)
Mobility Oscillator [CC]The Mobility Oscillator was created by Mel Widner (Stocks and Commodities Feb 1996) and this is another of my ongoing series of undiscovered gems. I would say this is probably the most complicated script I have written for an indicator. It is extremely complicated to calculate comparing to other indicators but this is essentially an overbought and oversold indicator that uses a very unique technique to calculate overbought and oversold levels and overall upward or downward momentum there is in the underlying stock. It uses a price distribution function to determine how often the current prices fall within the current trend which tells us how strong the momentum for the current trend actually is. I had to customize this indicator a bit to give clear buy and sell readings so I had to introduce a lag in exchange for clearer signals. This indicator ranges between +100 and -100 and when it stays at the +100 level for example then this means a sustained uptrend and vice versa. I have included strong buy and sell signals in addition to normal ones so strong signals are darker in color and normal signals are lighter in color. Buy when the line turns green and sell when it turns red.
Let me know if there are any other scripts or indicators you would like to see me publish!
Probability Distribution HistogramProbability Distribution Histogram
During data exploration it is often useful to plot the distribution of the data one is exploring. This indicator plots the distribution of data between different bins.
Essentially, what we do is we look at the min and max of the entire data set to determine its range. When we have the range of the data, we decide how many bins we want to divide this range into, so that the more bins we get, the smaller the range (a.k.a. width) for each bin becomes. We then place each data point in its corresponding bin, to see how many of the data points end up in each bin. For instance, if we have a data set where the smallest number is 5 and the biggest number is 105, we get a range of 100. If we then decide on 20 bins, each bin will have a width of 5. So the left-most bin would therefore correspond to values between 5 and 10, and the bin to the right would correspond to values between 10 and 15, and so on.
Once we have distributed all the data points into their corresponding bins, we compare the count in each bin to the total number of data points, to get a percentage of the total for each bin. So if we have 100 data points, and the left-most bin has 2 data points in it, that would equal 2%. This is also known as probability mass (or well, an approximation of it at least, since we're dealing with a bin, and not an exact number).
Usage
This is not an indicator that will give you any trading signals. This indicator is made to help you examine data. It can take any input you give it and plot how that data is distributed.
The indicator can transform the data in a few ways to help you get the most out of your data exploration. For instance, it is usually more accurate to use logarithmic data than raw data, so there is an option to transform the data using the natural logarithmic function. There is also an option to transform the data into %-Change form or by using data differencing.
Another option that the indicator has is the ability to trim data from the data set before plotting the distribution. This can help if you know there are outliers that are made up of corrupted data or data that is not relevant to your research.
I also included the option to plot the normal distribution as well, for comparison. This can be useful when the data is made up of residuals from a prediction model, to see if the residuals seem to be normally distributed or not.















