VolatilityIndicatorsLibrary   "VolatilityIndicators" 
This is a library of  Volatility Indicators .
It aims to facilitate the grouping of this category of indicators, and also offer the customized supply of
the parameters and sources, not being restricted to just the closing price.
@Thanks and credits:
1. Dynamic Zones: Leo Zamansky, Ph.D., and David Stendahl
2. Deviation: Karl Pearson (code by TradingView)
3. Variance: Ronald Fisher (code by TradingView)
4. Z-score: Veronique Valcu (code by HPotter)
5. Standard deviation: Ronald Fisher (code by TradingView)
6. ATR (Average True Range): J. Welles Wilder (code by TradingView)
7. ATRP (Average True Range Percent): millerrh
8. Historical Volatility: HPotter
9. Min-Max Scale Normalization: gorx1
10. Mean Normalization: gorx1
11. Standardization: gorx1
12. Scaling to unit length: gorx1
13. LS Volatility Index: Alexandre Wolwacz (Stormer), Fabrício Lorenz, Fábio Figueiredo (Vlad) (code by me)
14. Bollinger Bands: John Bollinger (code by TradingView)
15. Bollinger Bands %: John Bollinger (code by TradingView)
16. Bollinger Bands Width: John Bollinger (code by TradingView)
 dev(source, length, anotherSource) 
  Deviation. Measure the difference between a source in relation to another source
  Parameters:
     source (float) 
     length (simple int) : (int) Sequential period to calculate the deviation
     anotherSource (float) : (float) Source to compare
  Returns: (float) Bollinger Bands Width
 variance(src, mean, length, biased, degreesOfFreedom) 
  Variance. A statistical measurement of the spread between numbers in a data set. More specifically,
variance measures how far each number in the set is from the mean (average), and thus from every other number in the set.
Variance is often depicted by this symbol: σ2. It is used by both analysts and traders to determine volatility and market security.
  Parameters:
     src (float) : (float) Source to calculate variance
     mean (float) : (float) Mean (Moving average)
     length (simple int) : (int) The sequential period to calcule the variance (number of values in data set)
     biased (simple bool) : (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
     degreesOfFreedom (simple int) : (int)  Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
Default value is n-1, where n here is length. Only applies when biased parameter is defined as true.
  Returns: (float) Standard deviation
 stDev(src, length, mean, biased, degreesOfFreedom) 
  Measure the Standard deviation from a source in relation to it's moving average.
In this implementation, you pass the average as a parameter, allowing a more personalized calculation.
  Parameters:
     src (float) : (float) Source to calculate standard deviation
     length (simple int) : (int) The sequential period to calcule the standard deviation
     mean (float) : (float) Moving average.
     biased (simple bool) : (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
else uses unbiased sample variance (n-1 or another value, as long as it is in the range between 1 and n-1), where n=length.
     degreesOfFreedom (simple int) : (int)  Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
Default value is n-1, where n here is length.
  Returns: (float) Standard deviation
 zscore(src, mean, length, biased, degreesOfFreedom) 
  Z-Score. A z-score is a statistical measurement that indicates how many standard deviations a data point is from
the mean of a data set. It is also known as a standard score. The formula for calculating a z-score is (x - μ) / σ,
where x is the individual data point, μ is the mean of the data set, and σ is the standard deviation of the data set.
Z-scores are useful in identifying outliers or extreme values in a data set. A positive z-score indicates that the
data point is above the mean, while a negative z-score indicates that the data point is below the mean. A z-score of
0 indicates that the data point is equal to the mean.
Z-scores are often used in hypothesis testing and determining confidence intervals. They can also be used to compare
data sets with different units or scales, as the z-score standardizes the data. Overall, z-scores provide a way to
measure the relative position of a data point in a data
  Parameters:
     src (float) : (float) Source to calculate z-score
     mean (float) : (float) Moving average.
     length (simple int) : (int) The sequential period to calcule the standard deviation
     biased (simple bool) : (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
else uses unbiased sample variance (n-1 or another value, as long as it is in the range between 1 and n-1), where n=length.
     degreesOfFreedom (simple int) : (int)  Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
Default value is n-1, where n here is length.
  Returns: (float) Z-score
 atr(source, length) 
  ATR: Average True Range. Customized version with source parameter.
  Parameters:
     source (float) : (float) Source
     length (simple int) : (int) Length (number of bars back)
  Returns: (float) ATR
 atrp(length, sourceP) 
  ATRP (Average True Range Percent)
  Parameters:
     length (simple int) : (int) Length (number of bars back) for ATR
     sourceP (float) : (float) Source for calculating percentage relativity
  Returns: (float) ATRP
 atrp(source, length, sourceP) 
  ATRP (Average True Range Percent). Customized version with source parameter.
  Parameters:
     source (float) : (float) Source for ATR
     length (simple int) : (int) Length (number of bars back) for ATR
     sourceP (float) : (float) Source for calculating percentage relativity
  Returns: (float) ATRP
 historicalVolatility(lengthATR, lengthHist) 
  Historical Volatility
  Parameters:
     lengthATR (simple int) : (int) Length (number of bars back) for ATR
     lengthHist (simple int) : (int) Length (number of bars back) for Historical Volatility
  Returns: (float) Historical Volatility
 historicalVolatility(source, lengthATR, lengthHist) 
  Historical Volatility
  Parameters:
     source (float) : (float) Source for ATR
     lengthATR (simple int) : (int) Length (number of bars back) for ATR
     lengthHist (simple int) : (int) Length (number of bars back) for Historical Volatility
  Returns: (float) Historical Volatility
 minMaxNormalization(src, numbars) 
  Min-Max Scale Normalization. Maximum and minimum values are taken from the sequential range of
numbars bars back, where numbars is a number defined by the user.
  Parameters:
     src (float) : (float) Source to normalize
     numbars (simple int) : (int) Numbers of sequential bars back to seek for lowest and hightest values.
  Returns: (float) Normalized value
 minMaxNormalization(src, numbars, minimumLimit, maximumLimit) 
  Min-Max Scale Normalization. Maximum and minimum values are taken from the sequential range of
numbars bars back, where numbars is a number defined by the user.
In this implementation, the user explicitly provides the desired minimum (min) and maximum (max) values for the scale,
rather than using the minimum and maximum values from the data.
  Parameters:
     src (float) : (float) Source to normalize
     numbars (simple int) : (int) Numbers of sequential bars back to seek for lowest and hightest values.
     minimumLimit (simple float) : (float) Minimum value to scale
     maximumLimit (simple float) : (float) Maximum value to scale
  Returns: (float) Normalized value
 meanNormalization(src, numbars, mean) 
  Mean Normalization
  Parameters:
     src (float) : (float) Source to normalize
     numbars (simple int) : (int) Numbers of sequential bars back to seek for lowest and hightest values.
     mean (float) : (float) Mean of source
  Returns: (float) Normalized value
 standardization(src, mean, stDev) 
  Standardization (Z-score Normalization). How "outside the mean" values relate to the standard deviation (ratio between first and second)
  Parameters:
     src (float) : (float) Source to normalize
     mean (float) : (float) Mean of source
     stDev (float) : (float) Standard Deviation
  Returns: (float) Normalized value
 scalingToUnitLength(src, numbars) 
  Scaling to unit length
  Parameters:
     src (float) : (float) Source to normalize
     numbars (simple int) : (int) Numbers of sequential bars back to seek for lowest and hightest values.
  Returns: (float) Normalized value
 lsVolatilityIndex(movingAverage, sourceHvol, lengthATR, lengthHist, lenNormal, lowerLimit, upperLimit) 
  LS Volatility Index. Measures the volatility of price in relation to an average.
  Parameters:
     movingAverage (float) : (float) A moving average
     sourceHvol (float) : (float) Source for calculating the historical volatility
     lengthATR (simple int) : (float) Length for calculating the ATR (Average True Range)
     lengthHist (simple int) : (float) Length for calculating the historical volatility
     lenNormal (simple int) : (float) Length for normalization
     lowerLimit (simple int) 
     upperLimit (simple int) 
  Returns: (float) LS Volatility Index
 lsVolatilityIndex(sourcePrice, movingAverage, sourceHvol, lengthATR, lengthHist, lenNormal, lowerLimit, upperLimit) 
  LS Volatility Index. Measures the volatility of price in relation to an average.
  Parameters:
     sourcePrice (float) : (float) Source for measure the distance
     movingAverage (float) : (float) A moving average
     sourceHvol (float) : (float) Source for calculating the historical volatility
     lengthATR (simple int) : (float) Length for calculating the ATR (Average True Range)
     lengthHist (simple int) : (float) Length for calculating the historical volatility
     lenNormal (simple int) 
     lowerLimit (simple int) 
     upperLimit (simple int) 
  Returns: (float) LS Volatility Index
 bollingerBands(src, length, mult, basis) 
  Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted
two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price,
but can be adjusted to user preferences. In this version you can pass a customized basis (moving average), not only SMA.
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) The time period to be used in calculating the standard deviation
     mult (simple float) : (float) Multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float) A tuple of Bollinger Bands, where index 1=basis; 2=basis+dev; 3=basis-dev; and dev=multiplier*stdev
 bollingerBands(src, length, aMult, basis) 
  Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted
two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price,
but can be adjusted to user preferences. In this version you can pass a customized basis (moving average), not only SMA.
Also, various multipliers can be passed, thus getting more bands (instead of just 2).
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) The time period to be used in calculating the standard deviation
     aMult (float ) : (float ) An array of multiplies used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
This array of multipliers permit the use of various bands, not only 2.
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float ) An array of Bollinger Bands, where:
index 1=basis; 2=basis+dev1; 3=basis-dev1; 4=basis+dev2, 5=basis-dev2, 6=basis+dev2, 7=basis-dev2, Nup=basis+devN, Nlow=basis-devN
and dev1, dev2, devN are ```multiplier N * stdev```
 bollingerBandsB(src, length, mult, basis) 
  Bollinger Bands %B - or Percent Bandwidth (%B).
Quantify or display where price (or another source) is in relation to the bands.
%B can be useful in identifying trends and trading signals.
Calculation:
%B = (Current Price - Lower Band) / (Upper Band - Lower Band)
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) The time period to be used in calculating the standard deviation
     mult (simple float) : (float) Multiplier used in standard deviation
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float) Bollinger Bands %B
 bollingerBandsB(src, length, aMult, basis) 
  Bollinger Bands %B - or Percent Bandwidth (%B).
Quantify or display where price (or another source) is in relation to the bands.
%B can be useful in identifying trends and trading signals.
Calculation
%B = (Current Price - Lower Band) / (Upper Band - Lower Band)
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) The time period to be used in calculating the standard deviation
     aMult (float ) : (float ) Array of multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
This array of multipliers permit the use of various bands, not only 2.
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float ) An array of Bollinger Bands %B. The number of results in this array is equal the numbers of multipliers passed via parameter.
 bollingerBandsW(src, length, mult, basis) 
  Bollinger Bands Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands
Calculation:
Bollinger Bands Width = (Upper Band - Lower Band) / Middle Band
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) Sequential period to calculate the standard deviation
     mult (simple float) : (float) Multiplier used in standard deviation
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float) Bollinger Bands Width
 bollingerBandsW(src, length, aMult, basis) 
  Bollinger Bands Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands
Calculation
Bollinger Bands Width = (Upper Band - Lower Band) / Middle Band
  Parameters:
     src (float) : (float) Source to calculate standard deviation used in Bollinger Bands
     length (simple int) : (int) Sequential period to calculate the standard deviation
     aMult (float ) : (float ) Array of multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
This array of multipliers permit the use of various bands, not only 2.
     basis (float) : (float) Basis of Bollinger Bands (a moving average)
  Returns: (float ) An array of Bollinger Bands Width. The number of results in this array is equal the numbers of multipliers passed via parameter.
 dinamicZone(source, sampleLength, pcntAbove, pcntBelow) 
  Get Dynamic Zones
  Parameters:
     source (float) : (float) Source
     sampleLength (simple int) : (int) Sample Length
     pcntAbove (simple float) : (float) Calculates the top of the dynamic zone, considering that the maximum values are above x% of the sample
     pcntBelow (simple float) : (float) Calculates the bottom of the dynamic zone, considering that the minimum values are below x% of the sample
  Returns:   A tuple with 3 series of values: (1) Upper Line of Dynamic Zone;
(2) Lower Line of Dynamic Zone; (3) Center of Dynamic Zone (x = 50%)
 Examples: 
Cari dalam skrip untuk "bar"
Stochastic of Two-Pole SuperSmoother [Loxx]Stochastic of Two-Pole SuperSmoother   is a Stochastic Indicator that takes as input Two-Pole SuperSmoother of price. Includes gradient coloring and Discontinued Signal Lines signals with alerts. 
 What is Ehlers ; Two-Pole Super Smoother? 
From "Cycle Analytics for Traders Advanced Technical Trading Concepts" by John F. Ehlers
A SuperSmoother filter is used anytime a moving average of any type would otherwise be used, with the result that the SuperSmoother filter output would have substantially less lag for an equivalent amount of smoothing produced by the moving average. For example, a five-bar SMA has a cutoff period of approximately 10 bars and has two bars of lag. A SuperSmoother filter with a cutoff period of 10 bars has a lag a half bar larger than the two-pole modified Butterworth filter.Therefore, such a SuperSmoother filter has a maximum lag of approximately 1.5 bars and even less lag into the attenuation band of the filter. The differential in lag between moving average and SuperSmoother filter outputs becomes even larger when the cutoff periods are larger.
Market data contain noise, and removal of noise is the reason for using smoothing filters. In fact, market data contain several kinds of noise. I’ll group one kind of noise as systemic, caused by the random events of trades being exercised. A second kind of noise is aliasing noise, caused by the use of sampled data. Aliasing noise is the dominant term in the data for shorter cycle periods.
It is easy to think of market data as being a continuous waveform, but it is not. Using the closing price as representative for that bar constitutes one sample point. It doesn’t matter if you are using an average of the high and low instead of the close, you are still getting one sample per bar. Since sampled data is being used, there are some dSP aspects that must be considered. For example, the shortest analysis period that is possible (without aliasing)2 is a two-bar cycle.This is called the Nyquist frequency, 0.5 cycles per sample.A perfect two-bar sine wave cycle sampled at the peaks becomes a square wave due to sampling. However, sampling at the cycle peaks can- not be guaranteed, and the interference between the sampling frequency and the data frequency creates the aliasing noise.The noise is reduced as the data period is longer. For example, a four-bar cycle means there are four samples per cycle. Because there are more samples, the sampled data are a better replica of the sine wave component. The replica is better yet for an eight-bar data component.The improved fidelity of the sampled data means the aliasing noise is reduced at longer and longer cycle periods.The rate of reduction is 6 dB per octave. My experience is that the systemic noise rarely is more than 10 dB below the level of cyclic information, so that we create two conditions for effective smoothing of aliasing noise:
1. It is difficult to use cycle periods shorter that two octaves below the Nyquist frequency.That is, an eight-bar cycle component has a quantization noise level 12 dB below the noise level at the Nyquist frequency. longer cycle components therefore have a systemic noise level that exceeds the aliasing noise level.
2. A smoothing filter should have sufficient selectivity to reduce aliasing noise below the systemic noise level. Since aliasing noise increases at the rate of 6 dB per octave above a selected filter cutoff frequency and since the SuperSmoother attenuation rate is 12 dB per octave, the Super- Smoother filter is an effective tool to virtually eliminate aliasing noise in the output signal.
 What are DSL Discontinued Signal Line? 
A lot of indicators are using signal lines in order to determine the trend (or some desired state of the indicator) easier. The idea of the signal line is easy : comparing the value to it's smoothed (slightly lagging) state, the idea of current momentum/state is made.
Discontinued signal line is inheriting that simple signal line idea and it is extending it : instead of having one signal line, more lines depending on the current value of the indicator.
"Signal" line is calculated the following way :
When a certain level is crossed into the desired direction, the EMA of that value is calculated for the desired signal line
When that level is crossed into the opposite direction, the previous "signal" line value is simply "inherited" and it becomes a kind of a level
This way it becomes a combination of signal lines and levels that are trying to combine both the good from both methods.
In simple terms, DSL uses the concept of a signal line and betters it by inheriting the previous signal line's value & makes it a level.
 Included: 
 
 Bar coloring
 Alerts
 Signals
 Loxx's Expanded Source Types
 
Adaptive Two-Pole Super Smoother Entropy MACD [Loxx]Adaptive Two-Pole Super Smoother Entropy (Math) MACD is an Ehlers Two-Pole Super Smoother that is transformed into an  MACD oscillator using entropy mathematics. Signals are generated using Discontinued Signal Lines. 
 What is Ehlers; Two-Pole Super Smoother?  
From "Cycle Analytics for Traders Advanced Technical Trading Concepts" by John F. Ehlers
A SuperSmoother filter is used anytime a moving average of any type would otherwise be used, with the result that the SuperSmoother filter output would have substantially less lag for an equivalent amount of smoothing produced by the moving average. For example, a five-bar SMA has a cutoff period of approximately 10 bars and has two bars of lag. A SuperSmoother filter with a cutoff period of 10 bars has a lag a half bar larger than the two-pole modified Butterworth filter.Therefore, such a SuperSmoother filter has a maximum lag of approximately 1.5 bars and even less lag into the attenuation band of the filter. The differential in lag between moving average and SuperSmoother filter outputs becomes even larger when the cutoff periods are larger.
Market data contain noise, and removal of noise is the reason for using smoothing filters. In fact, market data contain several kinds of noise. I’ll group one kind of noise as systemic, caused by the random events of trades being exercised. A second kind of noise is aliasing noise, caused by the use of sampled data. Aliasing noise is the dominant term in the data for shorter cycle periods.
It is easy to think of market data as being a continuous waveform, but it is not. Using the closing price as representative for that bar constitutes one sample point. It doesn’t matter if you are using an average of the high and low instead of the close, you are still getting one sample per bar. Since sampled data is being used, there are some dSP aspects that must be considered. For example, the shortest analysis period that is possible (without aliasing)2 is a two-bar cycle.This is called the Nyquist frequency, 0.5 cycles per sample.A perfect two-bar sine wave cycle sampled at the peaks becomes a square wave due to sampling. However, sampling at the cycle peaks can- not be guaranteed, and the interference between the sampling frequency and the data frequency creates the aliasing noise.The noise is reduced as the data period is longer. For example, a four-bar cycle means there are four samples per cycle. Because there are more samples, the sampled data are a better replica of the sine wave component. The replica is better yet for an eight-bar data component.The improved fidelity of the sampled data means the aliasing noise is reduced at longer and longer cycle periods.The rate of reduction is 6 dB per octave. My experience is that the systemic noise rarely is more than 10 dB below the level of cyclic information, so that we create two conditions for effective smoothing of aliasing noise:
1. It is difficult to use cycle periods shorter that two octaves below the Nyquist frequency.That is, an eight-bar cycle component has a quantization noise level 12 dB below the noise level at the Nyquist frequency. longer cycle components therefore have a systemic noise level that exceeds the aliasing noise level.
2. A smoothing filter should have sufficient selectivity to reduce aliasing noise below the systemic noise level. Since aliasing noise increases at the rate of 6 dB per octave above a selected filter cutoff frequency and since the SuperSmoother attenuation rate is 12 dB per octave, the Super- Smoother filter is an effective tool to virtually eliminate aliasing noise in the output signal.
 What are DSL Discontinued Signal Line? 
A lot of indicators are using signal lines in order to determine the trend (or some desired state of the indicator) easier. The idea of the signal line is easy : comparing the value to it's smoothed (slightly lagging) state, the idea of current momentum/state is made.
Discontinued signal line is inheriting that simple signal line idea and it is extending it : instead of having one signal line, more lines depending on the current value of the indicator.
"Signal" line is calculated the following way :
When a certain level is crossed into the desired direction, the EMA of that value is calculated for the desired signal line
When that level is crossed into the opposite direction, the previous "signal" line value is simply "inherited" and it becomes a kind of a level
This way it becomes a combination of signal lines and levels that are trying to combine both the good from both methods.
In simple terms, DSL uses the concept of a signal line and betters it by inheriting the previous signal line's value & makes it a level.
 Included: 
 
 Bar coloring
 Alerts
 Signals
 Loxx's Expanded Source Types
SUPERTREND MIXED ICHI-DMI-DONCHIAN-VOL-GAP-HLBox@RLSUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL 
by RegisL76
This script is based on several trend indicators. 
* ICHIMOKU (KINKO HYO) 
* DMI (Directional Movement Index) 
* SUPERTREND ICHIMOKU + SUPERTREND DMI 
* DONCHIAN CANAL Optimized with Colored Bars 
* HMA Hull 
* Fair Value GAP 
* VOLUME/ MA Volume 
* PRICE / MA Price 
* HHLL BOXES 
All these indications are visible simultaneously on a single graph. A data table summarizes all the important information to make a good trade decision.
ICHIMOKU Indicator: 
The ICHIMOKU indicator is visualized in the traditional way.
 ICHIMOKU standard setting values are respected but modifiable. (Traditional defaults =  . 
An oriented visual symbol, near the last value, indicates the progression (Ascending, Descending or neutral) of the TENKAN-SEN and the KIJUN-SEN as well as the period used. 
The CLOUD (KUMO) and the CHIKOU-SPAN are present and are essential for the complete analysis of the ICHIMOKU. 
At the top of the graph are visually represented the crossings of the TENKAN and the KIJUN. 
Vertical lines, accompanied by labels, make it possible to quickly visualize the particularities of the ICHIMOKU. 
A line displays the current bar. 
A line visualizes the end of the CLOUD (KUMO) which is shifted 25 bars into the future. 
A line visualizes the end of the chikou-span, which is shifted 25 bars in the past. 
DIRECTIONAL MOVEMENT INDEX (DMI) :  Treated conventionally : DI+, DI-, ADX and associated with a SUPERTREND DMI. 
A visual symbol at the bottom of the graph indicates DI+ and DI- crossings 
A line of oriented and colored symbols (DMI Line) at the top of the chart indicates the direction and strength of the trend.
SUPERTREND ICHIMOKU + SUPERTREND DMI : 
Trend following by SUPERTREND calculation. 
DONCHIAN CHANNEL: Treated conventionally. (And optimized by colored bars when overshooting either up or down.
The lines, high and low of the last values of the channel are represented to quickly visualize the level of the RANGE. 
SUPERTREND HMA (HULL) Treated conventionally. 
The HMA line visually indicates, according to color and direction, the market trend. 
A visual symbol at the bottom of the chart indicates opportunities to sell and buy. 
VOLUME: 
Calculation of the MOBILE AVERAGE of the volume with comparison of the volume compared to the moving average of the volume. 
The indications are colored and commented according to the comparison. 
PRICE: Calculation of the MOBILE AVERAGE of the price with comparison of the price compared to the moving average of the price. 
The indications are colored and commented according to the comparison. 
HHLL BOXES: 
Visualizes in the form of a box, for a given period, the max high and min low values of the price. 
The configuration allows taking into account the high and low wicks of the price or the opening and closing values. 
FAIR VALUE GAP : 
This indicator displays 'GAP' levels over the current time period and an optional higher time period. 
The script takes into account the high/low values of the current bar and compares with the 2 previous bars. 
The "gap" is generated from the lack of overlap between these bars. Bearish or bullish gaps are determined by whether the gap is above or below HmaPrice, as they tend to fill, and can be used as targets. 
NOTE: FAIR VALUE GAP has no values displayed in the table and/or label. 
Important information (DATA) relating to each indicator is displayed in real time in a table and/or a label.
 Each information is commented and colored according to direction, value, comparison etc. 
Each piece of information indicates the values of the current bar and the previous value (in "FULL" mode). 
The other possible modes for viewing the table and/or the label allow a more synthetic view of the information ("CONDENSED" and "MINIMAL" modes). 
In order not to overload the vision of the chart too much, the visualization box of the RANGE DONCHIAN, the vertical lines of the shifted marks of the ICHIMOKU, as well as the boxes of the HHLL Boxes indicator are only visualized intermittently (managed by an adjustable time delay  ). 
The "HISTORICAL INFO READING" configuration parameter set to zero (by default) makes it possible to read all the information of the current bar in progress (Bar #0). All other values allow to read the information of a historical bar. The value 1 reads the information of the bar preceding the current bar (-1). The value 10 makes it possible to read the information of the tenth bar behind (-10) compared to the current bar, etc. 
At the bottom of the DATAS table and label, lights, red, green or white indicate quickly summarize the trend from the various indicators. 
Each light represents the number of indicators with the same trend at a given time. 
Green for a bullish trend, red for a bearish trend and white for a neutral trend. 
The conditions for determining a trend are for each indicator: 
SUPERTREND  ICHIMOHU + DMI: the 2 Super trends together are either bullish or bearish. 
Otherwise the signal is neutral. 
DMI: 2 main conditions: 
BULLISH if DI+ >= DI- and ADX >25. 
BEARISH if DI+ < DI- and ADX >25. 
NEUTRAL if the 2 conditions are not met.
ICHIMOKU: 3 main conditions: 
BULLISH if PRICE above the cloud and TENKAN > KIJUN and GREEN CLOUD AHEAD. 
BEARISH if PRICE below the cloud and TENKAN < KIJUN and RED CLOUD AHEAD. 
The other additional conditions (Data) complete the analysis and are present for informational purposes of the trend and depend on the context. 
DONCHIAN CHANNEL: 1 main condition: 
BULLISH: the price has crossed above the HIGH DC line. 
BEARISH: the price has gone below the LOW DC line. 
NEUTRAL if the price is between the HIGH DC and LOW DC lines 
The 2 other complementary conditions (Datas) complete the analysis: 
HIGH DC and LOW DC are increasing, falling or stable. 
SUPERTREND HMA HULL: The script determines several trend levels: 
STRONG BUY, BUY, STRONG SELL, SELL AND NEUTRAL. 
VOLUME: 3 trend levels: 
VOLUME > MOVING AVERAGE, 
VOLUME < MOVING AVERAGE, 
VOLUME = MOVING AVERAGE. 
PRICE: 3 trend levels: 
PRICE > MOVING AVERAGE, 
PRICE < MOVING AVERAGE, 
PRICE = MOVING AVERAGE. 
If you are using this indicator/strategy and you are satisfied with the results, you can possibly make a donation (a coffee, a pizza or more...) via paypal to: lebourg.regis@free.fr. 
Thanks in advance !!! 
Have good winning Trades.
**************************************************************************************************************************
SUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL
by RegisL76
Ce script est basé sur plusieurs indicateurs de tendance.
* ICHIMOKU (KINKO HYO)
* DMI (Directional Movement Index)
* SUPERTREND ICHIMOKU +  SUPERTREND DMI
* DONCHIAN CANAL Optimized with Colored Bars
* HMA Hull
* Fair Value GAP
* VOLUME/ MA Volume
* PRIX / MA Prix
* HHLL BOXES
Toutes ces indications sont visibles simultanément sur un seul et même graphique.
Un tableau de données récapitule toutes les informations importantes pour prendre une bonne décision de Trade.
I- Indicateur ICHIMOKU : 
L’indicateur ICHIMOKU est visualisé de manière traditionnelle
Les valeurs de réglage standard ICHIMOKU sont respectées mais modifiables. (Valeurs traditionnelles par défaut =  
Un symbole visuel orienté, à proximité de la dernière valeur, indique la progression (Montant, Descendant ou neutre) de la TENKAN-SEN et de la KIJUN-SEN ainsi que la période utilisée. 
Le NUAGE (KUMO) et la CHIKOU-SPAN sont bien présents et sont primordiaux pour l'analyse complète de l'ICHIMOKU.
En haut du graphique sont représentés visuellement les croisements de la TENKAN et de la KIJUN.
Des lignes verticales, accompagnées d'étiquettes, permettent de visualiser rapidement les particularités de l'ICHIMOKU.
Une ligne visualise la barre en cours.
Une ligne visualise l'extrémité du NUAGE (KUMO) qui est décalé de 25 barres dans le futur.
Une ligne visualise l'extrémité de la chikou-span, qui est décalée de 25 barres dans le passé.
II-DIRECTIONAL MOVEMENT INDEX (DMI)
Traité de manière conventionnelle : DI+, DI-, ADX et associé à un SUPERTREND DMI
Un symbole visuel en bas du graphique indique les croisements DI+ et DI-
Une ligne de symboles orientés et colorés (DMI Line) en haut du graphique, indique la direction et la puissance de la tendance.
III SUPERTREND ICHIMOKU + SUPERTREND DMI
Suivi de tendance par calcul SUPERTREND
IV- DONCHIAN CANAL : 
Traité de manière conventionnelle.
(Et optimisé par des barres colorées en cas de dépassement soit vers le haut, soit vers le bas.
Les lignes, haute et basse des dernières valeurs du canal sont représentées pour visualiser rapidement la fourchette du RANGE. 
V- SUPERTREND HMA (HULL)
Traité de manière conventionnelle.
La ligne HMA indique visuellement, selon la couleur et l'orientation, la tendance du marché.
Un symbole visuel en bas du graphique indique les opportunités de vente et d'achat.
*VI VOLUME : 
Calcul de la MOYENNE MOBILE du volume avec comparaison du volume par rapport à la moyenne mobile du volume.
Les indications sont colorées et commentées en fonction de la comparaison.
*VII PRIX : 
Calcul de la MOYENNE MOBILE du prix avec comparaison du prix par rapport à la moyenne mobile du prix.
Les indications sont colorées et commentées en fonction de la comparaison.
*VIII HHLL BOXES : 
Visualise sous forme de boite, pour une période donnée, les valeurs max hautes et min basses du prix.
La configuration permet de prendre en compte les mèches hautes et basses du prix ou bien les valeurs d'ouverture et de fermeture.
IX - FAIR VALUE GAP
Cet indicateur affiche les niveaux de 'GAP' sur la période temporelle actuelle ET une période temporelle facultative supérieure.
Le script prend en compte les valeurs haut/bas de la barre actuelle  et compare avec les 2 barres précédentes.
Le "gap" est généré à partir du manque de recouvrement entre ces barres.
Les écarts baissiers ou haussiers sont déterminés selon que l'écart est supérieurs ou inférieur à HmaPrice, car ils ont tendance à être comblés, et peuvent être utilisés comme cibles.
NOTA : FAIR VALUE GAP n'a pas de valeurs affichées dans la table et/ou l'étiquette.
Les informations importantes (DATAS) relatives à chaque indicateur sont visualisées en temps réel dans une table et/ou une étiquette.
Chaque information est commentée et colorée en fonction de la direction, de la valeur, de la comparaison etc.
Chaque information indique la valeurs de la barre en cours et la valeur précédente ( en mode "COMPLET").
Les autres modes possibles pour visualiser la table et/ou l'étiquette, permettent une vue plus synthétique des informations (modes "CONDENSÉ" et "MINIMAL").
Afin de ne pas trop surcharger la vision du graphique, la boite de visualisation du RANGE DONCHIAN, les lignes verticales des marques décalées de l'ICHIMOKU, ainsi que les boites de l'indicateur HHLL Boxes ne sont visualisées que de manière intermittente (géré par une temporisation réglable  ).
Le paramètre de configuration "HISTORICAL INFO READING" réglé sur zéro (par défaut) permet de lire toutes les informations de la barre actuelle en cours (Barre #0).
Toutes autres valeurs permet de lire les informations d'une barre historique. La valeur 1 permet de lire les informations de la barre précédant la barre en cours (-1).
La valeur 10 permet de lire les information de la dixième barre en arrière (-10) par rapport à la barre en cours, etc.
Dans le bas de la table et de l'étiquette de DATAS, des voyants, rouge, vert ou blanc indique de manière rapide la synthèse de la tendance issue des différents indicateurs.
Chaque voyant représente le nombre d'indicateur ayant la même tendance à un instant donné. Vert pour une tendance Bullish, rouge pour une tendance Bearish et blanc pour une tendance neutre.
Les conditions pour déterminer une tendance sont pour chaque indicateur :
SUPERTREND ICHIMOHU + DMI : les 2 Super trends sont ensemble soit bullish soit Bearish. Sinon le signal est neutre.
DMI : 2 conditions principales : 
BULLISH si DI+ >= DI- et ADX >25.
BEARISH si DI+ <  DI- et ADX >25.
NEUTRE si les 2 conditions ne sont pas remplies.
ICHIMOKU : 3 conditions principales :
BULLISH si PRIX au dessus du nuage  et TENKAN > KIJUN et NUAGE VERT DEVANT.
BEARISH si PRIX en dessous du nuage et TENKAN < KIJUN et NUAGE ROUGE DEVANT.
Les autres conditions complémentaires (Datas) complètent l'analyse et sont présents à titre informatif de la tendance et dépendent du contexte.
CANAL DONCHIAN : 1 condition principale : 
BULLISH : le prix est passé au dessus de la ligne HIGH DC.
BEARISH : le prix est passé au dessous de la ligne LOW DC.
NEUTRE si le prix se situe entre les lignes  HIGH DC et LOW DC
Les 2 autres conditions complémentaires (Datas) complètent l'analyse : HIGH DC  et LOW DC sont croissants, descendants ou stables.
SUPERTREND HMA HULL : 
Le script détermine plusieurs niveaux de tendance :
STRONG BUY, BUY, STRONG SELL, SELL ET NEUTRE.
VOLUME : 3 niveaux de tendance : 
VOLUME > MOYENNE MOBILE, VOLUME < MOYENNE MOBILE, VOLUME = MOYENNE MOBILE.
PRIX : 3 niveaux de tendance : 
PRIX > MOYENNE MOBILE, PRIX < MOYENNE MOBILE, PRIX = MOYENNE MOBILE.
Si vous utilisez cet indicateur/ stratégie et que vous êtes satisfait des résultats, 
 vous pouvez éventuellement me faire un don (un café, une pizza ou plus ...) via paypal à : lebourg.regis@free.fr.
 Merci d'avance !!!
Ayez de bons Trades gagnants.
Price Displacement - Candlestick (OHLC) CalculationsA Magical little helper friend for Candle Math. 
When composing scripts, it is often necessary to manipulate the math around the OHLC. At times, you want a scalar (absolute) value others you want a vector (+/-). Sometimes you want the open - close and sometimes you want just the positive number of the body size. You might want it in ticks or you might want it in points or you might want in percentages. And every time you try to put it together you waste precious time and brain power trying to think about how to properly structure what you're looking for. Not to mention it's normally not that aesthetically pleasing to look at in the code.
So, this fixes all of that. 
Using this library. A function like 'pd.pt(_exp)' can call any kind of candlestick math you need. The function returns the candlestick math you define using particular expressions. 
Candle Math Functions Include:
 Points: 
 pt(_exp)  Absolute Point Displacement. Point quantity of given size parameters according to _exp.
 vpt(_exp)  Vector Point Displacement. Point quantity of given size parameters according to _exp.
 Ticks: 
 tick(_exp)  Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
 vtick(_exp)  Vector Tick Displacement. Tick quantity of given size parameters according to _exp. 
 Percentages: 
 pct(_exp, _prec)  Absolute Percent Displacement. (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
 vpct(_exp, _prec)  Vector Percent Displacement (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
 Expressions You Can Use with Formulas: 
The expressions are simple (simple strings that is) and I did my best to make them sensible, generally using just the ohlc abreviations. I also included uw, lw, bd, and rg for when you're just trying to pull a candle component out. That way you don't have to think about which of the ohlc you're trying to get just use pd.tick("uw") and now the variable is assigned the length of the upper wick, absolute value, in ticks. If you wanted the vector in pts its pd.vpt("uw"). It also makes changing things easy too as I write it out. 
Expression List: 
Combinations
"oh" = open - high  
"ol" = open - low   
"oc" = open - close 
"ho" = high - open  
"hl" = high - low   
"hc" = high - close 
"lo" = low - open   
"lh" = low - high   
"lc" = low - close 
"co" = close - open 
"ch" = close - high 
"cl" = close - low  
Candle Components
"uw" = Upper Wick 
"bd" = Body  
"lw" = Lower Wick 
"rg" = Range  
Pct() Only                                                               
"scp" = Scalar Close Position
"sop" = Scalar Open Position 
"vcp" = Vector Close Position
"vop" = Vector Open Position 
The attributes are going to be available in the pop up dialogue when you mouse over the function, so you don't really have to remember them. I tried to make that look as efficient as possible. You'll notice it follows the OHLC pattern. Thus, "oh" precedes "ho" (heyo) because "O" would be first in the OHLC. Its a way to help find the expression you're looking for quickly. Like looking through an alphabetized list for traders. 
There is a copy/paste console friendly helper list in the script itself.
 Additional Notes on the Pct() Only functions: 
This is the original reason I started writing this. These concepts place a rating/value on the bar based on candle attributes in one number. These formulas put a open or close value in a percentile of the bar relative to another aspect of the bar.
 Scalar - Non-directional. Absolute Value. 
Scalar Position: The position of the price attribute relative to the scale of the bar range (high - low)
 
 Example: high = 100. low = 0. close = 25.
 (A) Measure price distance C-L. How high above the low did the candle close (e.g. close - low  = 25)
 (B)  Divide by bar range (high - low).  25 / (100 - 0) = .25
 Explaination: The candle closed at the 25th percentile of the bar range given the bar range low = 0 and bar range high = 100.  
 Formula: scp = (close - low) / (high - low)  
 
 Vector = Directional.  
Vector Position: The position of the price attribute relative to the scale of the bar midpoint (Vector Position at hl2 = 0)
 
 Example: high = 100. low = 0. close = 25.
 (A) Measure Price distance C-L: How high above the low did the candle close (e.g. close - low  = 25)
 (B) Measure Price distance H-C: How far below the high did the candle close (e.g. high - close = 75)
 (C) Take Difference: A - B = C = -50
 (D) Divide by bar range (high - low).  -50 / (100 - 0) = -0.50
 Explaination: Candle close at the midpoint between hl2 and the low.  
 Formula: vcp = {   / (high - low) }  
 
Thank you for checking this out. I hope no one else has already done this (because it took half the day) and I hope you find value in it. Be well. Trade well. 
Library   "PD" 
Price Displacement
 pt(_exp)  Absolute Point Displacement. Point quantity of given size parameters according to _exp.
  Parameters:
     _exp : (string) Price Parameter
  Returns: Point size of given expression as an absolute value.
 vpt(_exp)  Vector Point Displacement. Point quantity of given size parameters according to _exp.
  Parameters:
     _exp : (string) Price Parameter
  Returns: Point size of given expression as a vector. 
 tick(_exp)  Absolute Tick Displacement. Tick quantity of given size parameters according to _exp.
  Parameters:
     _exp : (string) Price Parameter
  Returns: Tick size of given expression as an absolute value. 
 vtick(_exp)  Vector Tick Displacement. Tick quantity of given size parameters according to _exp. 
  Parameters:
     _exp : (string) Price Parameter
  Returns: Tick size of given expression as a vector.
 pct(_exp, _prec)  Absolute Percent Displacement  (w/rounding overload).  Percent quantity of bar range of given size parameters according to _exp.
  Parameters:
     _exp : (string) Expression
     _prec : (int) Overload - Place value precision definition
  Returns: Percent size of given expression as decimal. 
 vpct(_exp, _prec)  Vector Percent Displacement  (w/rounding overload). Percent quantity of bar range of given size parameters according to _exp.
  Parameters:
     _exp : (string) Expression
     _prec : (int) Overload - Place value precision definition
  Returns: Percent size of given expression as decimal. 
ConditionalAverages█   OVERVIEW 
This library is a Pine Script™ programmer’s tool containing functions that average values selectively.
█   CONCEPTS 
Averaging can be useful to smooth out unstable readings in the data set, provide a benchmark to see the underlying trend of the data, or to provide a general expectancy of values in establishing a central tendency. Conventional averaging techniques tend to apply indiscriminately to all values in a fixed window, but it can sometimes be useful to average values only when a specific condition is met. As conditional averaging works on specific elements of a dataset, it can help us derive more context-specific conclusions. This library offers a collection of averaging methods that not only accomplish these tasks, but also exploit the efficiencies of the Pine Script™ runtime by foregoing unnecessary and resource-intensive  for  loops.
█   NOTES 
 To Loop or Not to Loop 
Though  for  and  while  loops are essential programming tools, they are often unnecessary in Pine Script™. This is because the Pine Script™ runtime already runs your scripts in a loop where it executes your code on each bar of the dataset. Pine Script™ programmers who understand how their code executes on charts can use this to their advantage by designing loop-less code that will run orders of magnitude faster than functionally identical code using loops. Most of this library's function illustrate how you can achieve loop-less code to process past values. See the  User Manual page on loops  for more information. If you are looking for ways to measure execution time for you scripts, have a look at our  LibraryStopwatch library .
Our `avgForTimeWhen()` and `totalForTimeWhen()` are exceptions in the library, as they use a  while  structure. Only a few iterations of the loop are executed on each bar, however, as its only job is to remove the few elements in the array that are outside the moving window defined by a time boundary.
 Cumulating and Summing Conditionally 
The  ta.cum()  or  math.sum()  built-in functions can be used with ternaries that select only certain values. In our `avgWhen(src, cond)` function, for example, we use this technique to cumulate only the occurrences of `src` when `cond` is true:
 float cumTotal = ta.cum(cond ? src : 0) We then use:
 float cumCount = ta.cum(cond ? 1 : 0) to calculate the number of occurrences where `cond` is true, which corresponds to the quantity of values cumulated in `cumTotal`.
 Building Custom Series With Arrays 
The advent of arrays in Pine has enabled us to build our custom data series. Many of this library's functions use arrays for this purpose, saving newer values that come in when a condition is met, and discarding the older ones, implementing a  queue .
 `avgForTimeWhen()` and `totalForTimeWhen()` 
These two functions warrant a few explanations. They operate on a number of values included in a moving window defined by a timeframe expressed in milliseconds. We use a 1D timeframe in our example code. The number of bars included in the moving window is unknown to the programmer, who only specifies the period of time defining the moving window. You can thus use `avgForTimeWhen()` to calculate a rolling moving average for the last 24 hours, for example, that will work whether the chart is using a 1min or 1H timeframe. A 24-hour moving window will typically contain many more values on a 1min chart that on a 1H chart, but their calculated average will be very close.
Problems will arise on non-24x7 markets when large time gaps occur between chart bars, as will be the case across holidays or trading sessions. For example, if you were using a 24H timeframe and there is a two-day gap between two bars, then no chart bars would fit in the moving window after the gap. The `minBars` parameter mitigates this by guaranteeing that a minimum number of bars are always included in the calculation, even if including those bars requires reaching outside the prescribed timeframe. We use a minimum value of 10 bars in the example code.
 Using  var  in Constant Declarations 
In the past, we have been using  var  when initializing so-called constants in our scripts, which as per the  Style Guide 's recommendations, we identify using UPPER_SNAKE_CASE. It turns out that  var  variables incur slightly superior maintenance overhead in the Pine Script™ runtime, when compared to variables initialized on each bar. We thus no longer use  var  to declare our "int/float/bool" constants, but still use it when an initialization on each bar would require too much time, such as when initializing a string or with a heavy function call.
 Look first. Then leap.  
█   FUNCTIONS 
 avgWhen(src, cond)  
  Gathers values of the source when a condition is true and averages them over the total number of occurrences of the condition.
  Parameters:
     src : (series int/float) The source of the values to be averaged. 
     cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
  Returns: (float) A cumulative average of values when a condition is met.
 avgWhenLast(src, cond, cnt)  
  Gathers values of the source when a condition is true and averages them over a defined number of occurrences of the condition.
  Parameters:
     src : (series int/float) The source of the values to be averaged. 
     cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
     cnt : (simple int) The quantity of last occurrences of the condition for which to average values.
  Returns: (float) The average of `src` for the last `x` occurrences where `cond` is true.
 avgWhenInLast(src, cond, cnt)  
  Gathers values of the source when a condition is true and averages them over the total number of occurrences during a defined number of bars back.
  Parameters:
     src : (series int/float) The source of the values to be averaged. 
     cond : (series bool) The condition determining when a value will be included in the set of values to be averaged.
     cnt : (simple int) The quantity of bars back to evaluate.
  Returns: (float) The average of `src` in last `cnt` bars, but only when `cond` is true.
 avgSince(src, cond)  
  Averages values of the source since a condition was true.
  Parameters:
     src : (series int/float) The source of the values to be averaged. 
     cond : (series bool) The condition determining when the average is reset.
  Returns: (float) The average of `src` since `cond` was true.
 avgForTimeWhen(src, ms, cond, minBars)  
  Averages values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
  Parameters:
     src : (series int/float) The source of the values to be averaged. 
     ms : (simple int) The time duration in milliseconds defining the size of the moving window.
     cond : (series bool) The condition determining which values are included. Optional.
     minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
  Returns: (float) The average of `src` when `cond` is true in the moving window.
 totalForTimeWhen(src, ms, cond, minBars)  
  Sums values of `src` when `cond` is true, over a moving window of length `ms` milliseconds.
  Parameters:
     src : (series int/float) The source of the values to be summed. 
     ms : (simple int) The time duration in milliseconds defining the size of the moving window.
     cond : (series bool) The condition determining which values are included. Optional.
     minBars : (simple int) The minimum number of values to keep in the moving window. Optional.
  Returns: (float) The sum of `src` when `cond` is true in the moving window.
Overnight Gap AnalysisThere is a wide range of opinion on holding positions overnight due to gap risk. So, out of curiosity, I coded this analysis as a strategy to see what the result of only holding a position overnight on an asset would be. The results really surprised me. The script backtests 10+ years, and here are the findings:
 
 Holding a position for 1 hour bar overnight on QQQ since January 2010 results in a 545% return. QQQ's entire return holding through the same period is 643%
 The max equity drawdown on holding that position overnight is lower then the buy/hold drawdown on the underlying asset.
 It doesn't matter if the last bar of the day is green or red, the results are similar.
 It doesn't matter if it is a bull or bear market. Filtering the script to only trade when the price is above the 200-day moving average actually reduces its return from 545% to 301%, though it does also reduce drawdown.
 I see similar patterns when applying the script to other index ETFs. Applying it to leveraged index ETFs can end up beating buy/hold of the underlying index.
 Since this script holds through the 1st bar of the day, this could also speak to a day-opening price pattern
 
The default inputs are for the script to be applied to  1 hour charts only  that have 7 bars on the chart per day. You can apply it to other chart types, but must follow the instructions below for it to work properly. 
 What the script is doing : 
This script is buying the close of the last bar of the day and closing the trade at the close of the next bar. So, all trades are being held for 1 bar. By default, the script is setup for use on a 1hr chart that has 7 bars per day. If you try to apply it to a different timeframe, you will need to adjust the count of the last bar of the day with the script input. I.e. There are 7 bars per day on an hour chart on US Stocks/ETFs, so the input is set to 7 by default. 
 Other ways this script can be used : 
This script can also test the result of holding a position over any 1 bar in the day using that same input. For instance, on an hour chart you can input 6 on the script input, and it will model buying the close of the 6th bar of the day while selling on the close of the next bar. I used this out of curiosity to model what only holding the last bar of the day would result in. On average, you lose money on the last bar every day.  
 The irony here is that the root cause of this last bar of the day losing may be people selling their positions at the end of day so that they aren't exposed to overnight gap risk. 
Disclaimer: This is not financial advice. Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help! 
Bjorgum SuperScript
 Bjorgum Reversal 
 
 Bj Reversal uses Tilson moving averages to identify trend changes 
Bars change to yellow as bar close crosses the Tilson moving averages. Blue or red is confirmed as the two Tilson averages themselves cross. 
Reversal is great for pinpointing trend change often giving the absolute best entry or exit
Its sensitive nature can mean more false signals on some assets 
Be sure to use other indicators from the Bjorgum Collection to confirm signals, or use another strategy that fits the asset or time frame being viewed 
 
 Bjorgum HEMA Strategy 
 
 Hema uses HA smoothed EMAs to identify trend direction
Default EMA lengths are 5,9, and 21 period 
Bar Color will change Malibu or Ruby on a cross of BOTH 5 and 9 EMA
The lengths are customizable to whatever lengths the user desires   
 
 Rolando Santos True Relative Movement (TRM) 
 This underrated momentum strategy conceptualized by Rolando Santos uses 2 indicators to give a 3 color scheme
A leading indicator (RSI) is combined with a lagging indicator (TSI) to produce bar colors based on the condition of each indicator
Both indicators in positive territory produce blue bars
Both indicators in negative bias produce yellow bars
If signals are mixed (one up one down) bars become grey
 Speed Selection  
 The Bjorgum speed selector optimizes the strategy based on the users desires or trading style at the touch of a button
Fast setting is better for swing trades - more timely signals, more whipsaw
Slow setting is better for longer holds or more volatile assets - slower signals, smooths out whipsaw  
 RSI Bar Color 
 
 RSI color changes bar color based on user defined RSI values 
Buy/ sell signals are typically given on a cross of the 50 level 
Speed selector (fast/Slow) automatically changes lengths between Bj RSI (5 period) and a standard RSI (14 period)
 
 Additional capabilities can be mixed and matched from strategies in the "Strategy Override" section  
Add-ons include:
 Tilson - The moving average system from Bjorgum Reversal can be toggled to couple with another bar color strategy by clicking this button
PSAR - Parabolic Stop and Reverse indicator can help with trend direction, volatility, and stop losses 
HEMA - The 3 moving average system from the HEMA strategy can be coupled with any of the other strategies by clicking "Show HEMA"
Bj Arrows - These arrows plot at the bar level to draw attention to when the BJ TSI is "curling" (See profile for Bjorgum TSI and download today)
 -Optional "Plotbar Overlay" plots bars with Heikin-Ashi Inputs when toggled  
-This allows for the benefits of price smoothing without sacrificing moving average and indicator performance as real close value is still used 
-This can also help on short time frames and improve results with crypto! The user must "mute" the main series candles when in use to avoid candle overlap.
-Optional price line as muting main bars will disable the TradingView default price line. The horizontal plot will track the real closing price while in HA mode!
Historic VPoCs and pseudo VPVRThis study tries to recreate session based historic VPoCs
and VPVR Volume Profile
as they are used by
TradingLatino TradingView user.
It's aimed at BTCUSDT pair and 4h timeframe.
 HOW IT WORKS 
 HOW IT WORKS - VPVR Profile Block 
It gathers volume from the last chosen Bars
in order to draw the vpvr profile block
Volume that intersects with current level range
being studied is added to its value.
Additionally the current level price is modified
so that it matches the level price where most
of the volume has concentrated
So you get a pretty accurate price for drawn volume
while at the same time the levels are not stuck
to arbitrary level prices.
 HOW IT WORKS - VPoC 
It calculates a Volume Profile for the
given historic session but then
it only outputs that Volume Profile VPoC.
 SETTINGS 
 
  Show VPVR Volume Profile {True}.
  Show Historic VPoC lines {True}.
  Show Historic VPoC labels {True}.
  Extend Historic VPoC lines {True}: If this option is turned off the VPoC lines are only shown during the session duration.
  Show tick difference from current price {False}: BETA. Feedback is needed because I'm not sure how it should work this setting.
  VPVR Number of bars {100}: Define the Visible Range in number of bars so that its Volume Profile can be shown.
  VPVR Profile width (in bars) {15}: VPVR Profile can be make larger or smaller in width thanks to this option.
  VPVR Profile offset (in bars) {15}: VPVR Profile can be shown more to the left or to the right if the defaults do not suit you.
  Historic Session Volume Profile timeframe {1D}: Historic VPoC use 1 day as their timeframe reference by default.
  Number of decimal digits {2}: How many decimal digits are shown in label prices.
  Number of previous sessions to print VPoC {5}: How many previous sessions VPoCs are to be printed. The maximum for this setting is 20.
  Historic VPoC lines width (in pixels) {2}.
  Historic VPoC labels size {small}.
  History VPoC line offset (in bars) {5}: How far to the right VPoCs lines are to be extended. Note: This setting does not apply when 'Extend Historic VPoC lines' is set to 'False'.
 
 WARNING 
Please be aware that VPoC from the first previous session might not be accurate due to Pine Script limitations.
 VPVR USAGE 
This is not a VPVR like the official TradingView indicator.
This is a pseudo VPVR and that means it needs some manual input from you.
But, don't worry it's quite easy to do and if you always use the same number
of bars to calculate your VPVR then you might even just set it up once.
In order to show the VPVR (or Volume Profile on the Visible Range):
 
  Rescale your chart so that you see all the bars for your Visible Range.
  Click on the ruler tool.
  Click on the last bar (far to the right) shown on the screen
  Drag the ruler to first bar (far to the left) shown on the screen
  Check what the ruler says
  E.g. it says: 101 bars
  Open this study settings
  Modify: 'VPVR Number of bars  ' setting
  So that its value matches your measured number of bars (101)
  Press OK to confirm and wait for the indicator to refresh.
 
 STRATEGY USAGE 
If your strategy uses VPoC
to define your resistances
or supports
you can check the VPoCs shown here.
 FEEDBACK 
I have only used this identifier in BTCUSDT 4h timeframe.
I'm interested to know what needs to be tweaked
in other securities and timeframes.
 PINE STUDY TRICK 
This study let's you choose the number of decimals the label will use.
 CREDITS 
I have reused and adapted some code from
'Poor man's volume profile' study
which it's from TradingView IldarAkhmetgaleev user.
I also wanted to thank him for helping me understanding his study.
I have reused some code from
'MTF Selection Framework - PineCoders FAQ' study
which it's from TradingView PineCoders user.
Ultimate VolumeThis script can display a lot of different volume statistics. It also colours bars depending on a chosen, customisable criterion. Most options are disabled by default and can be reenabled in the settings menu.
FAQ
 Why are the bars slightly higher than the default volume bars? 
Due to the limitations of Pinescript.
 What are the two last values (including the one in white?) 
They're there due to the limitations of Pinescript. It used to be possible to prevent certain values from being plotted, but still display them as indicator values, but the functionality of that option was changed and is now WIP so until it's restored, these values are necessary to scale the bars properly.
 Why are the percentages formatted as volume? 
Due to the limitations of Pinescript.
 Why are there so many options? 
I don't know. They sort of happened. But you don't have to switch them on.
 What is money volume? 
It's an average of the bar price multiplied by the bar volume .
 Why does the daily average volume display different values than the standard sma volume? 
Because mine doesn't take into account the current day. So it doesn't fluctuate intraday. Which, I think, makes more sense.
 What is total volume? 
It's a sum of the total volume for that day and is reset on the next. This option only works with intraday timeframes.
 What is average 1 bar intraday volume? 
It's the average volume for 1 intraday bar, based on the current day's values only. Obviously, it only works intraday and changes dynamically. It's not an SMA , it's a simple average of all bars for a given day.
 What is all-time 1 bar intraday volume? 
It's the average volume for 1 intraday bar, but based on the whole chart's history. It's impossible to select a length for this, again, because of certain limitations.
 What is short volume? 
It is approximately 1/3rd of the actual short volume , due to the limitations of FINRA. It's multiplied by 3 in the script and it may be not entirely accurate. The short volume % is calculated differently, using the 1/3rd of short and total volume from FINRA.
 What are the default threshold values? 
They are 150%, 200%, 1000% of the average for the average bar volume and all-time average bar volume options, 10%, 50%, 100% for the average daily volume option and 100K, 500K and 1M for the volume option. 
RedK_Supply/Demand Volume Viewer v1Background
============
VolumeViewer is a volume indicator, that offers a simple way to estimate the movement and balance (or lack of) of supply & demand volume based on the shape of the price bar. i put this together few years ago and i have a version of this published for another platform under different names (Directional Volume, BetterVolume) in case you come across them
what is V.Viewer
=====================
The idea here is to find a "simple proxy" for estimating the demand or supply portions of a volume bar - these 2 forces have the potential to affect the current price trend so we want an easy way to track them - or to understand if a stock is in accumulation or distribution - we want to do this without having access to Level II or bid/ask data, and without having to get into the complexity of exploring the lower timeframe price & volume data 
- to achieve that, we depend on a simple assumption, that the volume associated with an up move is "demand" and the volume associated with a down move is "Supply".  so we basically extrapolate these supply and demand values based on how the bar looks like - a full "green" price bar / candle will be considered 100% demand, and a full "red" price bar will be considered 100% supply - a bar that opens and closes at the same level will be 50/50 split between supply & demand. 
- you may say this is a "too simple" of an assumption to make, but believe me, it works :) at least at the basic scenario we need here: i'm just exploring the volume movement and finding key levels - and it provides a good improvement compared to the classic way we see volume on a chart - which is still available here in VolumeViewer.
in all cases, i consider this to be work in progress, so i'd welcome any ideas to improve (without getting too complicated) - there's already a host of great volume-based indicators that will do the multi timeframe drill down, but that's not my scope here.
Technical Jargon & calculation
===========================
1. first we calculate a score % for the volume portion that is considered demand based on the bar shape 
skip this part if it sounds too technical =>   if you're into coding indicators, you would probably know there are couple of different concepts for that algorithm - for example, the one used in Balance Of Power formula - which i'm a big fan of - but the one i use here is different. (how?) this is my own, ant it simply applies double weight for the "wick" parts of a price bar compared to the "body of the bar" -- i did some side-by-side comparison in past and decided this one works better. you can change it in the code if you like
 
2. after calculating the Bull vs Bears portion of volume, we take a moving average of both for the length you set, to come up with what we consider to be the Demand vs Supply - as usual, i use a weighted moving average (WMA) here.
3. the balance or net volume between these 2 lines is calculated, then we apply a final smoothing and that's the main plot we will get
4. being a very visual person, i did my best to build up the visuals in the correct order - then also to ensure the "study title" bar is properly organized and is simple and useful (Full Volume, Supply, Demand, Net Volume). 
- i wish there was a way in Pine to hide a value that i still need to visually plot but don't want it showing its value on the study title bar, but couldn't find it. so the last plot value is repeated twice.
How to use
===========
- V.Viewer is set up to show the simplified view by default for simplicity. so when you first add it to a chart, you will get only the supply vs demand view you can see in the middle pane in the above chart
- Optional / detailed mode: go into the settings, and expose all other plots, you will be able to add the classic volume histogram, and the Supply / Demand lines - note these 2 lines will be overlay-ed on top of each other - this provides an easy way to see who is in control - especially if you change the display of these 2 lines into "area" style. This is what is showing in the lower pane in the above chart.
** Exploring Key Price Levels
- the premise is, at spots where there's big lack of balance, that's where to expect to find key price levels (support / resistance) and these price levels will come into play in future so can be used to set entry / exit targets for our trades - see the example in the AAPL chart where you can easily locate these "balance or reversal levels" using the tops/bottoms/zero-crossings from the Net Volume line
** Use for longer-term Price Analysis 
- we can also use this simple indicator to gain more insights (at a high level) of the price in terms of accumulation vs distribution and if the sellers or buyers are in control - for example, in the above AAPL chart, V.Viewer tells us that buyers have been in control since October 19 - even during the recent drop, demand continued to be in play - compare that to DIS chart below for the same period, where it shows that the market was dumping DIS thru the weakness. DIS was bleeding red most of the time
Final thoughts
=============
- V.Viewer is an attempt to enhance the way we see and use Volume by leveraging the shape of the price bar to estimate volume supply & demand - and the Net between the 2
- it will work for stocks and other instruments as long as there's volume data
- note that V.Viewer does not track trend. each bar is taken in isolation of prior bars - the price may be going down and V.Viewer is showing supply going up (absorption scenario?) - so i suggest you do not use it to make decisions without consulting other trend / momentum indicators - of course this is a possible improvement idea, or can be implemented in another indicator, add in trend somehow, or maybe think of making this a +100 / -100 Oscillator .. feel free to play with these thoughts 
- all thoughts welcome - if this is useful to you in your trading, please share with other trades here to learn from each other
- the code is commented - please feel free to use it as you like, or build things on top of it - but please continue to credit the author of this code :)
good luck!
- 
Pivots MTF [LucF]Pivots detected at higher timeframes are more significant because more market activity—or work—is required to produce them. This indicator displays pivots calculated on the higher timeframe of your choice.
 Features 
► Timeframe selection
— The higher timeframe (HTF) can be selected in 3 different ways:
 • By steps (15 min., 60 min., 4H, 1D, 3D, 1W, 1M, 1Y). This setting is the default.
 • As a multiple of the current chart's resolution, which can be fractional, so 3.5 will work.
 • Fixed.
— The HTF used can be displayed near the last bar (default).
— Note that using the HTF is not mandatory. If it is disabled, the indicator will calculate on the chart's resolution.
— Non-repainting or repainting mode can be selected. This has no impact on the display of historical bars, but when no repainting is selected, pivot detection in the realtime bar will be delayed by one chart bar (not one bar at the HTF).
► Pivots
— Three color schemes are provided: green/red, aqua/pink and coral/violet (the default).
— Both the thickness and brightness of lines can be controlled separately for the hi and lo pivots.
— The visibility of the last hi/lo pivots can be enhanced.
— Prices can be displayed on pivot lines and the text's size and color can be adjusted.
— The number of bars required for the left/right pivot legs can be controlled (the default is 4).
— The source can be selected individually for hi and lo pivots (the default is  hlc3  and  low .
— The mean of the hi/lo pivot values of the last few thousand chart bars can be displayed. Pivots having lasted longer during the mean's period will weigh more in the calculation. The mean can be displayed in running mode and/or only showing its last level as a long horizontal line. I don't find it very useful; maybe others will.
► Markers and Alerts
— Markers can be configured on breaches of either the last hi/lo pivot levels, or the hi/lo mean. Crossovers and crossunders are controlled separately.
— Alerts can be configured using any of the marker combinations. As is usual for my indicators, only one alert is used. It will trigger on the markers that are active when you create your alert. Once your markers are set up the way you want, create your alert from the chart/timeframe you want the alert to run on, and be sure to use the “Once Per Bar Close” triggering condition. Use an alert message that will remind you of the combination of markers used when creating the alert. If you use multiple markers to trigger one alert, then having the indicator show those markers will be important to help you figure out which marker triggered the alert when it fired.
A quick look at the pattern of these markers will hopefully convince you that using them as entry/exit signals would be perilous, as they are prone to whipsaw. I have included them because some traders may use the markers as reminders.
 Using Pivots 
These pivots can be used in a few different ways:
— When using the  high / low  sources they will show extreme levels, breaches of which should be more significant.
— Another way to use them is with  hlc3  (the average of the  high ,  low  and  close ) for hi pivots and  low  for the lo pivots. This accounts for my personal mythology to the effect that drops typically reach previous lows more easily than rallies make newer highs.
— Using  low  for hi pivots and  high  for lo pivots (so backward) can be a useful way to set stops or to detect weakness in movements.
You will usually be better served by pivots if you consider them as denoting regions rather than precise levels. The flexibility in the display options of this indicator will help you adapt it to the way you use your pivots. To indicate areas rather than levels, for example, try using a brightness of 1 with a line thickness of 30. The cloud effect generated this way will show areas better than fine lines.
Realize that these pivot lines are positioned in the past, and so they are drawn after the fact because a given number of bars need to elapse before calculations determine a pivot has occurred. You will thus never see a pivot top, for example, identified on the realtime bar. To detect a pivot, it takes a number of bars corresponding to the dilation of the higher timeframe in the current one, multiplied by the number of bars you use for your pivots' right leg. Also note that the Pine native function used to detect pivots in this indicator considers a summit to be a top when the number of bars in each leg are lower or equal to that top. Bars in legs do not need to be progressively lower on each side of the pivot for a pivot to be detected. 
 If you program in Pine 
— See the  Pinecoders MTF Selection Framework  for an explanation of the functions used in this script to provide the selection mechanism for the higher timeframe.
— This code uses the  Pine Script Coding Conventions .
 Thanks 
— To the Pine coders asking questions in the  Pine Script chat on TV ; your questions got me to write this indicator.
Leledc Exhaustion V4This is one of my fav script (Leledec Exhaustion). The original script was written in V2 by Glaz here 
 All I did is to convert this to Version 4 of Pine Scripting language.
An Exhaustion Bar is a bar which signals the exhaustion of the trend in the current direction. In other words, an exhaustion bar is “A bar of the last seller” in case of a downtrend and  “A bar of
last buyer” in case of an uptrend.
Having said that when a party cannot take the price further in their direction, naturally the other party comes in, takes charge and reverses the direction of the trend.
 The Psychology 
Let's assume that we have a group of people, say 100 people who decide to go for a casual running. After running for a few KM's few of them will say “I am exhausted. I cannot run further”. They will quit running. After running further, another bunch of runners will say “I am exhausted. I can’t run further” and they also will quit running. This goes on and on and then there will be a stage where only a few will be left in the running. Now a stage will come where the last person left in the running will say “ am exhausted” and he stops running. That means no one is left now in the
running. This means all are exhausted in the running.
The same way an exhaustion bar works. The reason is an exhaustion bar sometimes formed at almost tops and bottoms.
 Timeframe 
The exhaustion bars are found on all Time frames as a trend also exists on all Timeframes. However, as a thumb rule “Higher the Time frame, higher will be the accuracy as well as the profitability”. 
 Trading the Leledec Exhaustion Bars 
 
  I may trade as soon as it is shown on the chart. 
  I may trade when price breaks the high/low of the bar depending on whether I am getting bullish or bearish signal
  I may trade when price breaks the high/low of the bar depending on whether I am getting bullish or bearish signal. I may also be looking to ensure the current volume is higher than the previous few 
(? how many?) bar volumes.
 
Backtesting & Trading Engine [PineCoders]The PineCoders Backtesting and Trading Engine is a sophisticated framework with hybrid code that can run as a study to generate alerts for automated or discretionary trading while simultaneously providing backtest results. It can also easily be converted to a TradingView strategy in order to run TV backtesting. The Engine comes with many built-in strats for entries, filters, stops and exits, but you can also add you own. 
If, like any self-respecting strategy modeler should, you spend a reasonable amount of time constantly researching new strategies and tinkering, our hope is that the Engine will become your inseparable go-to tool to test the validity of your creations, as once your tests are conclusive, you will be able to run this code as a study to generate the alerts required to put it in real-world use, whether for discretionary trading or to interface with an execution bot/app. You may also find the backtesting results the Engine produces in study mode enough for your needs and spend most of your time there, only occasionally converting to strategy mode in order to backtest using TV backtesting. 
As you will quickly grasp when you bring up this script’s Settings, this is a complex tool. While you will be able to see results very quickly by just putting it on a chart and using its built-in strategies, in order to reap the full benefits of the PineCoders Engine, you will need to invest the time required to understand the subtleties involved in putting all its potential into play. 
Disclaimer: use the Engine at your own risk. 
Before we delve in more detail, here’s a bird’s eye view of the Engine’s features: 
 
 More than 40 built-in strategies, 
 Customizable components, 
 Coupling with your own external indicator, 
 Simple conversion from Study to Strategy modes, 
 Post-Exit analysis to search for alternate trade outcomes, 
 Use of the Data Window to show detailed bar by bar trade information and global statistics, including some not provided by TV backtesting, 
 Plotting of reminders and generation of alerts on in-trade events.
 
By combining your own strats to the built-in strats supplied with the Engine, and then tuning the numerous options and parameters in the Inputs dialog box, you will be able to play what-if scenarios from an infinite number of permutations. 
 USE CASES  
You have written an indicator that provides an entry strat but it’s missing other components like a filter and a stop strategy. You add a plot in your indicator that respects the Engine’s External Signal Protocol, connect it to the Engine by simply selecting your indicator’s plot name in the Engine’s Settings/Inputs and then run tests on different combinations of entry stops, in-trade stops and profit taking strats to find out which one produces the best results with your entry strat. 
You are building a complex strategy that you will want to run as an indicator generating alerts to be sent to a third-party execution bot. You insert your code in the Engine’s modules and leverage its trade management code to quickly move your strategy into production. 
You have many different filters and want to explore results using them separately or in combination. Integrate the filter code in the Engine and run through different permutations or hook up your filtering through the external input and control your filter combos from your indicator. 
You are tweaking the parameters of your entry, filter or stop strat. You integrate it in the Engine and evaluate its performance using the Engine’s statistics. 
You always wondered what results a random entry strat would yield on your markets. You use the Engine’s built-in random entry strat and test it using different combinations of filters, stop and exit strats. 
You want to evaluate the impact of fees and slippage on your strategy. You use the Engine’s inputs to play with different values and get immediate feedback in the detailed numbers provided in the Data Window. 
You just want to inspect the individual trades your strategy generates. You include it in the Engine and then inspect trades visually on your charts, looking at the numbers in the Data Window as you move your cursor around. 
You have never written a production-grade strategy and you want to learn how. Inspect the code in the Engine; you will find essential components typical of what is being used in actual trading systems. 
You have run your system for a while and have compiled actual slippage information and your broker/exchange has updated his fees schedule. You enter the information in the Engine and run it on your markets to see the impact this has on your results. 
 FEATURES  
Before going into the detail of the Inputs and the Data Window numbers, here’s a more detailed overview of the Engine’s features. 
 Built-in strats  
The engine comes with more than 40 pre-coded strategies for the following standard system components: 
 
 Entries, 
 Filters, 
 Entry stops, 
 2 stage in-trade stops with kick-in rules, 
 Pyramiding rules, 
 Hard exits.
 
While some of the filter and stop strats provided may be useful in production-quality systems, you will not devise crazy profit-generating systems using only the entry strats supplied; that part is still up to you, as will be finding the elusive combination of components that makes winning systems. The Engine will, however, provide you with a solid foundation where all the trade management nitty-gritty is handled for you. By binding your custom strats to the Engine, you will be able to build reliable systems of the best quality currently allowed on the TV platform. 
 On-chart trade information  
As you move over the bars in a trade, you will see trade numbers in the Data Window change at each bar. The engine calculates the P&L at every bar, including slippage and fees that would be incurred were the trade exited at that bar’s close. If the trade includes pyramided entries, those will be taken into account as well, although for those, final fees and slippage are only calculated at the trade’s exit. 
You can also see on-chart markers for the entry level, stop positions, in-trade special events and entries/exits (you will want to disable these when using the Engine in strategy mode to see TV backtesting results). 
 Customization  
You can couple your own strats to the Engine in two ways: 
1. By inserting your own code in the Engine’s different modules. The modular design should enable you to do so with minimal effort by following the instructions in the code. 
2. By linking an external indicator to the engine. After making the proper selections in the engine’s Settings and providing values respecting the engine’s protocol, your external indicator can, when the Engine is used in Indicator mode only: 
 
 Tell the engine when to enter long or short trades, but let the engine’s in-trade stop and exit strats manage the exits, 
 Signal both entries and exits, 
 Provide an entry stop along with your entry signal, 
 Filter other entry signals generated by any of the engine’s entry strats.
 
 Conversion from strategy to study  
TradingView strategies are required to backtest using the TradingView backtesting feature, but if you want to generate alerts with your script, whether for automated trading or just to trigger alerts that you will use in discretionary trading, your code has to run as a study since, for the time being, strategies can’t generate alerts. From hereon we will use indicator as a synonym for study. 
Unless you want to maintain two code bases, you will need hybrid code that easily flips between strategy and indicator modes, and your code will need to restrict its use of strategy() calls and their arguments if it’s going to be able to run both as an indicator and a strategy using the same trade logic. That’s one of the benefits of using this Engine. Once you will have entered your own strats in the Engine, it will be a matter of commenting/uncommenting only four lines of code to flip between indicator and strategy modes in a matter of seconds. 
Additionally, even when running in Indicator mode, the Engine will still provide you with precious numbers on your individual trades and global results, some of which are not available with normal TradingView backtesting. 
 Post-Exit Analysis for alternate outcomes (PEA)  
While typical backtesting shows results of trade outcomes, PEA focuses on what could have happened after the exit. The intention is to help traders get an idea of the opportunity/risk in the bars following the trade in order to evaluate if their exit strategies are too aggressive or conservative. 
After a trade is exited, the Engine’s PEA module continues analyzing outcomes for a user-defined quantity of bars. It identifies the maximum opportunity and risk available in that space, and calculates the drawdown required to reach the highest opportunity level post-exit, while recording the number of bars to that point. 
Typically, if you can’t find opportunity greater than 1X past your trade using a few different reasonable lengths of PEA, your strategy is doing pretty good at capturing opportunity. Remember that 100% of opportunity is never capturable. If, however, PEA was finding post-trade maximum opportunity of 3 or 4X with average drawdowns of 0.3 to those areas, this could be a clue revealing your system is exiting trades prematurely. To analyze PEA numbers, you can uncomment complete sets of plots in the Plot module to reveal detailed global and individual PEA numbers. 
 Statistics  
The Engine provides stats on your trades that TV backtesting does not provide, such as: 
 
 Average Profitability Per Trade (APPT), aka statistical expectancy, a crucial value. 
 APPT per bar, 
 Average stop size, 
 Traded volume .
 
It also shows you on a trade-by-trade basis, on-going individual trade results and data. 
 In-trade events  
In-trade events can plot reminders and trigger alerts when they occur. The built-in events are: 
 
 Price approaching stop, 
 Possible tops/bottoms, 
 Large stop movement (for discretionary trading where stop is moved manually), 
 Large price movements.
 
 Slippage and Fees  
Even when running in indicator mode, the Engine allows for slippage and fees to be included in the logic and test results. 
 Alerts  
The alert creation mechanism allows you to configure alerts on any combination of the normal or pyramided entries, exits and in-trade events. 
 Backtesting results  
A few words on the numbers calculated in the Engine. Priority is given to numbers not shown in TV backtesting, as you can readily convert the script to a strategy if you need them. 
We have chosen to focus on numbers expressing results relative to X (the trade’s risk) rather than in absolute currency numbers or in other more conventional but less useful ways. For example, most of the individual trade results are not shown in percentages, as this unit of measure is often less meaningful than those expressed in units of risk (X). A trade that closes with a +25% result, for example, is a poor outcome if it was entered with a -50% stop. Expressed in X, this trade’s P&L becomes 0.5, which provides much better insight into the trade’s outcome. A trade that closes with a P&L of +2X has earned twice the risk incurred upon entry, which would represent a pre-trade risk:reward ratio of 2. 
The way to go about it when you think in X’s and that you adopt the sound risk management policy to risk a fixed percentage of your account on each trade is to equate a currency value to a unit of X. E.g. your account is 10K USD and you decide you will risk a maximum of 1% of it on each trade. That means your unit of X for each trade is worth 100 USD. If your APPT is 2X, this means every time you risk 100 USD in a trade, you can expect to make, on average, 200 USD. 
By presenting results this way, we hope that the Engine’s statistics will appeal to those cognisant of sound risk management strategies, while gently leading traders who aren’t, towards them. 
We trade to turn in tangible profits of course, so at some point currency must come into play. Accordingly, some values such as equity, P&L, slippage and fees are expressed in currency. 
Many of the usual numbers shown in TV backtests are nonetheless available, but they have been commented out in the Engine’s Plot module. 
 Position sizing and risk management  
All good system designers understand that optimal risk management is at the very heart of all winning strategies. The risk in a trade is defined by the fraction of current equity represented by the amplitude of the stop, so in order to manage risk optimally on each trade, position size should adjust to the stop’s amplitude. Systems that enter trades with a fixed stop amplitude can get away with calculating position size as a fixed percentage of current equity. In the context of a test run where equity varies, what represents a fixed amount of risk translates into different currency values. 
Dynamically adjusting position size throughout a system’s life is optimal in many ways. First, as position sizing will vary with current equity, it reproduces a behavioral pattern common to experienced traders, who will dial down risk when confronted to poor performance and increase it when performance improves. Second, limiting risk confers more predictability to statistical test results. Third, position sizing isn’t just about managing risk, it’s also about maximizing opportunity. By using the maximum leverage (no reference to trading on margin here) into the trade that your risk management strategy allows, a dynamic position size allows you to capture maximal opportunity. 
To calculate position sizes using the fixed risk method, we use the following formula: Position = Account * MaxRisk% / Stop% [, which calculates a position size taking into account the trade’s entry stop so that if the trade is stopped out, 100 USD will be lost. For someone who manages risk this way, common instructions to invest a certain percentage of your account in a position are simply worthless, as they do not take into account the risk incurred in the trade. 
The Engine lets you select either the fixed risk or fixed percentage of equity position sizing methods. The closest thing to dynamic position sizing that can currently be done with alerts is to use a bot that allows syntax to specify position size as a percentage of equity which, while being dynamic in the sense that it will adapt to current equity when the trade is entered, does not allow us to modulate position size using the stop’s amplitude. Changes to alerts are on the way which should solve this problem. 
In order for you to simulate performance with the constraint of fixed position sizing, the Engine also offers a third, less preferable option, where position size is defined as a fixed percentage of initial capital so that it is constant throughout the test and will thus represent a varying proportion of current equity. 
Let’s recap. The three position sizing methods the Engine offers are: 
1. By specifying the maximum percentage of risk to incur on your remaining equity, so the Engine will dynamically adjust position size for each trade so that, combining the stop’s amplitude with position size will yield a fixed percentage of risk incurred on current equity, 
2. By specifying a fixed percentage of remaining equity. Note that unless your system has a fixed stop at entry, this method will not provide maximal risk control, as risk will vary with the amplitude of the stop for every trade. This method, as the first, does however have the advantage of automatically adjusting position size to equity. It is the Engine’s default method because it has an equivalent in TV backtesting, so when flipping between indicator and strategy mode, test results will more or less correspond. 
3. By specifying a fixed percentage of the Initial Capital. While this is the least preferable method, it nonetheless reflects the reality confronted by most system designers on TradingView today. In this case, risk varies both because the fixed position size in initial capital currency represents a varying percentage of remaining equity, and because the trade’s stop amplitude may vary, adding another variability vector to risk. 
 Note that the Engine cannot display equity results for strategies entering trades for a fixed amount of shares/contracts at a variable price. 
 
 SETTINGS/INPUTS  
Because the initial text first published with a script cannot be edited later and because there are just too many options, the Engine’s Inputs will not be covered in minute detail, as they will most certainly evolve. We will go over them with broad strokes; you should be able to figure the rest out. If you have questions, just ask them here or in the PineCoders Telegram group. 
 Display  
The display header’s checkbox does nothing. 
For the moment, only one exit strategy uses a take profit level, so only that one will show information when checking “Show Take Profit Level”. 
 Entries  
You can activate two simultaneous entry strats, each selected from the same set of strats contained in the Engine. If you select two and they fire simultaneously, the main strat’s signal will be used. 
The random strat in each list uses a different seed, so you will get different results from each. 
The “Filter transitions” and “Filter states” strats delegate signal generation to the selected filter(s). “Filter transitions” signals will only fire when the filter transitions into bull/bear state, so after a trade is stopped out, the next entry may take some time to trigger if the filter’s state does not change quickly. When you choose “Filter states”, then a new trade will be entered immediately after an exit in the direction the filter allows. 
If you select “External Indicator”, your indicator will need to generate a +2/-2 (or a positive/negative stop value) to enter a long/short position, providing the selected filters allow for it. If you wish to use the Engine’s capacity to also derive the entry stop level from your indicator’s signal, then you must explicitly choose this option in the Entry Stops section. 
 Filters  
You can activate as many filters as you wish; they are additive. The “Maximum stop allowed on entry” is an important component of proper risk management. If your system has an average 3% stop size and you need to trade using fixed position sizes because of alert/execution bot limitations, you must use this filter because if your system was to enter a trade with a 15% stop, that trade would incur 5 times the normal risk, and its result would account for an abnormally high proportion in your system’s performance. 
Remember that any filter can also be used as an entry signal, either when it changes states, or whenever no trade is active and the filter is in a bull or bear mode. 
 Entry Stops  
An entry stop must be selected in the Engine, as it requires a stop level before the in-trade stop is calculated. Until the selected in-trade stop strat generates a stop that comes closer to price than the entry stop (or respects another one of the in-trade stops kick in strats), the entry stop level is used. 
It is here that you must select “External Indicator” if your indicator supplies a +price/-price value to be used as the entry stop. A +price is expected for a long entry and a -price value will enter a short with a stop at price. Note that the price is the absolute price, not an offset to the current price level. 
 In-Trade Stops  
The Engine comes with many built-in in-trade stop strats. Note that some of them share the “Length” and “Multiple” field, so when you swap between them, be sure that the length and multiple in use correspond to what you want for that stop strat. Suggested defaults appear with the name of each strat in the dropdown. 
In addition to the strat you wish to use, you must also determine when it kicks in to replace the initial entry’s stop, which is determined using different strats. For strats where you can define a positive or negative multiple of X, percentage or fixed value for a kick-in strat, a positive value is above the trade’s entry fill and a negative one below. A value of zero represents breakeven. 
 Pyramiding  
What you specify in this section are the rules that allow pyramiding to happen. By themselves, these rules will not generate pyramiding entries. For those to happen, entry signals must be issued by one of the active entry strats, and conform to the pyramiding rules which act as a filter for them. The “Filter must allow entry” selection must be chosen if you want the usual system’s filters to act as additional filtering criteria for your pyramided entries. 
 Hard Exits  
You can choose from a variety of hard exit strats. Hard exits are exit strategies which signal trade exits on specific events, as opposed to price breaching a stop level in In-Trade Stops strategies. They are self-explanatory. The last one labelled When Take Profit Level (multiple of X) is reached is the only one that uses a level, but contrary to stops, it is above price and while it is relative because it is expressed as a multiple of X, it does not move during the trade. This is the level called Take Profit that is show when the “Show Take Profit Level” checkbox is checked in the Display section. 
While stops focus on managing risk, hard exit strategies try to put the emphasis on capturing opportunity. 
 Slippage  
You can define it as a percentage or a fixed value, with different settings for entries and exits. The entry and exit markers on the chart show the impact of slippage on the entry price (the fill). 
 Fees  
Fees, whether expressed as a percentage of position size in and out of the trade or as a fixed value per in and out, are in the same units of currency as the capital defined in the Position Sizing section. Fees being deducted from your Capital, they do not have an impact on the chart marker positions. 
 In-Trade Events  
These events will only trigger during trades. They can be helpful to act as reminders for traders using the Engine as assistance to discretionary trading. 
 Post-Exit Analysis  
It is normally on. Some of its results will show in the Global Numbers section of the Data Window. Only a few of the statistics generated are shown; many more are available, but commented out in the Plot module. 
 Date Range Filtering  
Note that you don’t have to change the dates to enable/diable filtering. When you are done with a specific date range, just uncheck “Date Range Filtering” to disable date filtering. 
 Alert Triggers  
Each selection corresponds to one condition. Conditions can be combined into a single alert as you please. Just be sure you have selected the ones you want to trigger the alert before you create the alert. For example, if you trade in both directions and you want a single alert to trigger on both types of exits, you must select both “Long Exit” and “Short Exit” before creating your alert. 
Once the alert is triggered, these settings no longer have relevance as they have been saved with the alert. 
When viewing charts where an alert has just triggered, if your alert triggers on more than one condition, you will need the appropriate markers active on your chart to figure out which condition triggered the alert, since plotting of markers is independent of alert management. 
 Position sizing  
You have 3 options to determine position size: 
1. Proportional to Stop -> Variable, with a cap on size. 
2. Percentage of equity -> Variable. 
3. Percentage of Initial Capital -> Fixed. 
 External Indicator  
This is where you connect your indicator’s plot that will generate the signals the Engine will act upon. Remember this only works in Indicator mode. 
 DATA WINDOW INFORMATION  
The top part of the window contains global numbers while the individual trade information appears in the bottom part. The different types of units used to express values are: 
 
 curr: denotes the currency used in the Position Sizing section of Inputs for the Initial Capital value. 
 quote: denotes quote currency, i.e. the value the instrument is expressed in, or the right side of the market pair (USD in EURUSD ). 
 X: the stop’s amplitude, itself expressed in quote currency, which we use to express a trade’s P&L, so that a trade with P&L=2X has made twice the stop’s amplitude in profit. This is sometimes referred to as R, since it represents one unit of risk. It is also the unit of measure used in the APPT, which denotes expected reward per unit of risk. 
 X%: is also the stop’s amplitude, but expressed as a percentage of the Entry Fill.
 
The numbers appearing in the Data Window are all prefixed: 
 
 “ALL:” the number is the average for all first entries and pyramided entries. 
 ”1ST:” the number is for first entries only. 
 ”PYR:” the number is for pyramided entries only. 
 ”PEA:” the number is for Post-Exit Analyses
 
 Global Numbers  
Numbers in this section represent the results of all trades up to the cursor on the chart. 
 Average Profitability Per Trade (X):  This value is the most important gauge of your strat’s worthiness. It represents the returns that can be expected from your strat for each unit of risk incurred. E.g.: your APPT is 2.0, thus for every unit of currency you invest in a trade, you can on average expect to obtain 2 after the trade. APPT is also referred to as “statistical expectancy”. If it is negative, your strategy is losing, even if your win rate is very good (it means your winning trades aren’t winning enough, or your losing trades lose too much, or both). Its counterpart in currency is also shown, as is the APPT/bar, which can be a useful gauge in deciding between rivalling systems. 
 Profit Factor:  Gross of winning trades/Gross of losing trades. Strategy is profitable when >1. Not as useful as the APPT because it doesn’t take into account the win rate and the average win/loss per trade. It is calculated from the total winning/losing results of this particular backtest and has less predictive value than the APPT. A good profit factor together with a poor APPT means you just found a chart where your system outperformed. Relying too much on the profit factor is a bit like a poker player who would think going all in with two’s against aces is optimal because he just won a hand that way. 
 Win Rate:  Percentage of winning trades out of all trades. Taken alone, it doesn’t have much to do with strategy profitability. You can have a win rate of 99% but if that one trade in 100 ruins you because of poor risk management, 99% doesn’t look so good anymore. This number speaks more of the system’s profile than its worthiness. Still, it can be useful to gauge if the system fits your personality. It can also be useful to traders intending to sell their systems, as low win rate systems are more difficult to sell and require more handholding of worried customers. 
 Equity (curr):  This the sum of initial capital and the P&L of your system’s trades, including fees and slippage. 
 Return on Capital  is the equivalent of TV’s Net Profit figure, i.e. the variation on your initial capital. 
 Maximum drawdown  is the maximal drawdown from the highest equity point until the drop . There is also a close to close (meaning it doesn’t take into account in-trade variations) maximum drawdown value commented out in the code. 
The next values are self-explanatory, until: 
 PYR: Avg Profitability Per Entry (X):  this is the APPT for all pyramided entries. 
 PEA: Avg Max Opp . Available (X):  the average maximal opportunity found in the Post-Exit Analyses. 
 PEA: Avg Drawdown to Max Opp . (X):  this represents the maximum drawdown (incurred from the close at the beginning of the PEA analysis) required to reach the maximal opportunity point. 
 Trade Information  
Numbers in this section concern only the current trade under the cursor. Most of them are self-explanatory. Use the description’s prefix to determine what the values applies to. 
 PYR: Avg Profitability Per Entry (X):  While this value includes the impact of all current pyramided entries (and only those) and updates when you move your cursor around, P&L only reflects fees at the trade’s last bar. 
 PEA: Max Opp . Available (X):  It’s the most profitable close reached post-trade, measured from the trade’s Exit Fill, expressed in the X value of the trade the PEA follows. 
 PEA: Drawdown to Max Opp . (X):  This is the maximum drawdown from the trade’s Exit Fill that needs to be sustained in order to reach the maximum opportunity point, also expressed in X. Note that PEA numbers do not include slippage and fees. 
 EXTERNAL SIGNAL PROTOCOL  
Only one external indicator can be connected to a script; in order to leverage its use to the fullest, the engine provides options to use it as either an entry signal, an entry/exit signal or a filter. When used as an entry signal, you can also use the signal to provide the entry’s stop. Here’s how this works: 
 For filter state:  supply +1 for bull (long entries allowed), -1 for bear (short entries allowed). 
 For entry signals:  supply +2 for long, -2 for short. 
 For exit signals:  supply +3 for exit from long, -3 for exit from short. 
 To send an entry stop level with an entry signal:  Send positive stop level for long entry (e.g. 103.33 to enter a long with a stop at 103.33), negative stop level for short entry (e.g. -103.33 to enter a short with a stop at 103.33). If you use this feature, your indicator will have to check for exact stop levels of 1.0, 2.0 or 3.0 and their negative counterparts, and fudge them with a tick in order to avoid confusion with other signals in the protocol. 
Remember that mere generation of the values by your indicator will have no effect until you explicitly allow their use in the appropriate sections of the Engine’s Settings/Inputs. 
An example of a script issuing a signal for the Engine is published by PineCoders. 
 RECOMMENDATIONS TO ASPIRING SYSTEM DESIGNERS  
 Stick to higher timeframes.  On progressively lower timeframes, margins decrease and fees and slippage take a proportionally larger portion of profits, to the point where they can very easily turn a profitable strategy into a losing one. Additionally, your margin for error shrinks as the equilibrium of your system’s profitability becomes more fragile with the tight numbers involved in the shorter time frames. Avoid <1H time frames. 
 Know and calculate fees and slippage.  To avoid market shock, backtest using conservative fees and slippage parameters. Systems rarely show unexpectedly good returns when they are confronted to the markets, so put all chances on your side by being outrageously conservative—or a the very least, realistic. Test results that do not include fees and slippage are worthless. Slippage is there for a reason, and that’s because our interventions in the market change the market. It is easier to find alpha in illiquid markets such as cryptos because not many large players participate in them. If your backtesting results are based on moving large positions and you don’t also add the inevitable slippage that will occur when you enter/exit thin markets, your backtesting will produce unrealistic results. Even if you do include large slippage in your settings, the Engine can only do so much as it will not let slippage push fills past the high or low of the entry bar, but the gap may be much larger in illiquid markets. 
 Never test and optimize your system on the same dataset , as that is the perfect recipe for overfitting or data dredging, which is trying to find one precise set of rules/parameters that works only on one dataset. These setups are the most fragile and often get destroyed when they meet the real world. 
 Try to find datasets yielding more than 100 trades.  Less than that and results are not as reliable. 
 Consider all backtesting results with suspicion.  If you never entertained sceptic tendencies, now is the time to begin. If your backtest results look really good, assume they are flawed, either because of your methodology, the data you’re using or the software doing the testing. Always assume the worse and learn proper backtesting techniques such as monte carlo simulations and walk forward analysis to avoid the traps and biases that unchecked greed will set for you. If you are not familiar with concepts such as survivor bias, lookahead bias and confirmation bias, learn about them. 
 Stick to simple bars or candles when designing systems.  Other types of bars often do not yield reliable results, whether by design (Heikin Ashi) or because of the way they are implemented on TV (Renko bars). 
 Know that you don’t know  and use that knowledge to learn more about systems and how to properly test them, about your biases, and about yourself. 
 Manage risk first , then capture opportunity. 
 Respect the inherent uncertainty of the future.  Cleanse yourself of the sad arrogance and unchecked greed common to newcomers to trading. Strive for rationality. Respect the fact that while backtest results may look promising, there is no guarantee they will repeat in the future (there is actually a high probability they won’t!), because the future is fundamentally unknowable. If you develop a system that looks promising, don’t oversell it to others whose greed may lead them to entertain unreasonable expectations. 
 Have a plan.  Understand what king of trading system you are trying to build. Have a clear picture or where entries, exits and other important levels will be in the sort of trade you are trying to create with your system. This stated direction will help you discard more efficiently many of the inevitably useless ideas that will pop up during system design. 
 Be wary of complexity.  Experienced systems engineers understand how rapidly complexity builds when you assemble components together—however simple each one may be. The more complex your system, the more difficult it will be to manage. 
 Play! . Allow yourself time to play around when you design your systems. While much comes about from working with a purpose, great ideas sometimes come out of just trying things with no set goal, when you are stuck and don’t know how to move ahead. Have fun! 
@LucF 
 NOTES  
While the engine’s code can supply multiple consecutive entries of longs or shorts in order to scale positions (pyramid), all exits currently assume the execution bot will exit the totality of the position. No partial exits are currently possible with the Engine. 
Because the Engine is literally crippled by the limitations on the number of plots a script can output on TV; it can only show a fraction of all the information it calculates in the Data Window. You will find in the Plot Module vast amounts of commented out lines that you can activate if you also disable an equivalent number of other plots. This may be useful to explore certain characteristics of your system in more detail. 
When backtesting using the TV backtesting feature, you will need to provide the strategy parameters you wish to use through either Settings/Properties or by changing the default values in the code’s header. These values are defined in variables and used not only in the strategy() statement, but also as defaults in the Engine’s relevant Inputs. 
If you want to test using pyramiding, then both the strategy’s Setting/Properties and the Engine’s Settings/Inputs need to allow pyramiding. 
If you find any bugs in the Engine, please let us know. 
 THANKS  
To @glaz for allowing the use of his unpublished MA Squize in the filters. 
To @everget for his Chandelier stop code, which is also used as a filter in the Engine. 
To @RicardoSantos for his pseudo-random generator, and because it’s from him that I first read in the Pine chat about the idea of using an external indicator as input into another. In the PineCoders group, @theheirophant then mentioned the idea of using it as a buy/sell signal and @simpelyfe showed a piece of code implementing the idea. That’s the tortuous story behind the use of the external indicator in the Engine. 
To @admin for the Volatility stop’s original code and for the donchian function lifted from Ichimoku . 
To @BobHoward21 for the v3 version of Volatility Stop . 
To @scarf and @midtownsk8rguy for the color tuning. 
To many other scripters who provided encouragement and suggestions for improvement during the long process of writing and testing this piece of code. 
To J. Welles Wilder Jr. for ATR, used extensively throughout the Engine. 
To TradingView for graciously making an account available to PineCoders. 
And finally, to all fellow PineCoders for the constant intellectual stimulation; it is a privilege to share ideas with you all. The Engine is for all TradingView PineCoders, of course—but especially for you. 
 Look first. Then leap.  
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.
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.















