Machine Learning Adaptive SuperTrend [AlgoAlpha]📈🤖 Machine Learning Adaptive SuperTrend - Take Your Trading to the Next Level! 🚀✨
Introducing the Machine Learning Adaptive SuperTrend , an advanced trading indicator designed to adapt to market volatility dynamically using machine learning techniques. This indicator employs k-means clustering to categorize market volatility into high, medium, and low levels, enhancing the traditional SuperTrend strategy. Perfect for traders who want an edge in identifying trend shifts and market conditions.
What is K-Means Clustering and How It Works
K-means clustering is a machine learning algorithm that partitions data into distinct groups based on similarity. In this indicator, the algorithm analyzes ATR (Average True Range) values to classify volatility into three clusters: high, medium, and low. The algorithm iterates to optimize the centroids of these clusters, ensuring accurate volatility classification.
Key Features
🎨 Customizable Appearance: Adjust colors for bullish and bearish trends.
🔧 Flexible Settings: Configure ATR length, SuperTrend factor, and initial volatility guesses.
📊 Volatility Classification: Uses k-means clustering to adapt to market conditions.
📈 Dynamic SuperTrend Calculation: Applies the classified volatility level to the SuperTrend calculation.
🔔 Alerts: Set alerts for trend shifts and volatility changes.
📋 Data Table Display: View cluster details and current volatility on the chart.
Quick Guide to Using the Machine Learning Adaptive SuperTrend Indicator
🛠 Add the Indicator: Add the indicator to favorites by pressing the star icon. Customize settings like ATR length, SuperTrend factor, and volatility percentiles to fit your trading style.
📊 Market Analysis: Observe the color changes and SuperTrend line for trend reversals. Use the data table to monitor volatility clusters.
🔔 Alerts: Enable notifications for trend shifts and volatility changes to seize trading opportunities without constant chart monitoring.
How It Works
The indicator begins by calculating the ATR values over a specified training period to assess market volatility. Initial guesses for high, medium, and low volatility percentiles are inputted. The k-means clustering algorithm then iterates to classify the ATR values into three clusters. This classification helps in determining the appropriate volatility level to apply to the SuperTrend calculation. As the market evolves, the indicator dynamically adjusts, providing real-time trend and volatility insights. The indicator also incorporates a data table displaying cluster centroids, sizes, and the current volatility level, aiding traders in making informed decisions.
Add the Machine Learning Adaptive SuperTrend to your TradingView charts today and experience a smarter way to trade! 🌟📊
Volatilityindicator
[Pandora] Vast Volatility Treasure TroveINTRODUCTION:
Volatility enthusiasts, prepare for VICTORY on this day of July 4th, 2024! This is my "Vast Volatility Treasure Trove," intended mostly for educational purposes, yet these functions will also exhibit versatility when combined with other algorithms to garner statistical excellence. Once again, I am now ripping the lid off of Pandora's box... of volatility. Inside this script is a 'vast' collection of volatility estimators, reflecting the indicators name. Whether you are a seasoned trader destined to navigate financial strife or an eagerly curious learner, this script offers a comprehensive toolkit for a broad spectrum of volatility analysis. Enjoy your journey through the realm of market volatility with this code!
WHAT IS MARKET VOLATILITY?:
Market volatility refers to various fluctuations in the value of a financial market or asset over a period of time, often characterized by occasional rapid and significant deviations in price. During periods of greater market volatility, evolving conditions of prices can move rapidly in either direction, creating uncertainty for investors with results of sharp declines as well as rapid gains. However, market volatility is a typical aspect expected in financial markets that can also present opportunities for informed decision-making and potential benefits from the price flux.
SCRIPT INTENTION:
Volatility is assuredly omnipresent, waxing and waning in magnitude, and some readers have every intention of studying and/or measuring it. This script serves as an all-in-one armada of volatility estimators for TradingView members. I set out to provide a diverse set of tools to analyze and interpret market volatility, offering volatile insights, and aid with the development of robust trading indicators and strategies.
In today's fast-paced financial markets, understanding and quantifying volatility is informative for both seasoned traders and novice investors. This script is designed to empower users by equipping them with a comprehensive suite of volatility estimators. Each function within this script has been meticulously crafted to address various aspects of volatility, from traditional methods like Garman-Klass and Parkinson to more advanced techniques like Yang-Zhang and my custom experimental algorithms.
Ultimately, this script is more than just a collection of functions. It is a gateway to a deeper understanding of market volatility and a valuable resource for anyone committed to mastering the complexities of financial markets.
SCRIPT CONTENTS:
This script includes a variety of functions designed to measure and analyze market volatility. Where applicable, an input checkbox option provides an unbiased/biased estimate. Below is a brief description of each function in the original order they appear as code upon first publish:
Parkinson Volatility - Estimates volatility emphasizing the high and low range movements.
Alternate Parkinson Volatility - Simpler version of the original Parkinson Volatility that I realized.
Garman-Klass Volatility - Estimates volatility based on high, low, open, and close prices using a formula that adjusts for biases in price dynamics.
Rogers-Satchell-Yoon Volatility #1 - Estimates volatility based on logarithmic differences between high, low, open, and close values.
Rogers-Satchell-Yoon Volatility #2 - Similar estimate to Rogers-Satchell with the same result via an alternate formulation of volatility.
Yang-Zhang Volatility - An advanced volatility estimate combining both strengths of the Garman-Klass and Rogers-Satchell estimators, with weights determined by an alpha parameter.
Yang-Zhang (Modified) Volatility - My experimental modification slightly different from the Yang-Zhang formula with improved computational efficiency.
Selectable Volatility - Basic customizable volatility calculation based on the logarithmic difference between selected numerator and denominator prices (e.g., open, high, low, close).
Close-to-Close Volatility - Estimates volatility using the logarithmic difference between consecutive closing prices. Specifically applicable to data sources without open, high, and low prices.
Open-to-Close Volatility - (Overnight Volatility): Estimates volatility based on the logarithmic difference between the opening price and the last closing price emphasizing overnight gaps.
Hilo Volatility - Estimates volatility using a method similar to Parkinson's method, which considers the logarithm of the high and low prices.
Vantage Volatility - My experimental custom 'vantage' method to estimate volatility similar to Yang-Zhang, which incorporates various factors (Alpha, Beta, Gamma) to generate a weighted logarithmic calculation. This may be a volatility advantage or disadvantage, hence it's name.
Schwert Volatility - Estimates volatility based on arithmetic returns.
Historical Volatility - Estimates volatility considering logarithmic returns.
Annualized Historical Volatility - Estimates annualized volatility using logarithmic returns, adjusted for the number of trading days in a year.
If I omitted any other known varieties, detailed requests for future consideration can be made below for their inclusion into this script within future versions...
BONUS ALGORITHMS:
This script also includes several experimental and bonus functions that push the boundaries of volatility analysis as I understand it. These functions are designed to provide additional insights and also are my ideal notions for traders looking to explore other methods of volatility measurement.
VOLATILITY APPLICATIONS:
Volatility estimators serve a common role across various facets of trading and financial analysis, offering insights into market behavior. These tools are already in instrumental with enhancing risk management practices by providing a deeper understanding of market dynamics and the inherent uncertainty in asset prices. With volatility estimators, traders can effectively quantifying market risk and adjust their strategies accordingly, optimizing portfolio performance and mitigating potential losses. Additionally, volatility estimations may serve as indication for detecting overbought or oversold market conditions, offering probabilistic insights that could inform strategic decisions at turning points. This script
distinctly offers a variety of volatility estimators to navigate intricate financial terrains with informed judgment to address challenges of strategic planning.
CODE REUSE:
You don't have to ask for my permission to use/reuse these functions in your published scripts, simply because I have better things to do than answer requests for the reuse of these functions.
Notice: Unfortunately, I will not provide any integration support into member's projects at all. I have my own projects that require way too much of my day already.
Realized volatility differentialAbout
This is a simple indicator that takes into account two types of realized volatility: Close-Close and High-Low (the latter is more useful for intraday trading).
The output of the indicator is two values / plots:
an average of High-Low volatility minus Close-Close volatility (10day period is used as a default)
the current value of the indicator
When the current value is:
lower / below the average, then it means that High-Low volatility should increase.
higher / above then obviously the opposite is true.
How to use it
It might be used as a timing tool for mean reversion strategies = when your primary strategy says a market is in mean reversion mode, you could use it as a signal for opening a position.
For example: let's say a security is in uptrend and approaching an important level (important to you).
If the current value is:
above the average, a short position can be opened, as High-Low volatility should decrease;
below the average, a trend should continue.
Intended securities
Futures contracts
Squeeze Momentum DeluxeThe Squeeze Momentum Deluxe is a comprehensive trading toolkit built with features of momentum, volatility, and price action. This script offers a suite for both mean reversion and trend-following analysis. Developed based on the original TTM Squeeze implementation by @LazyBear, this indicator introduces several innovative components to enhance your trading insights.
🔲 Components and Features
Momentum Oscillator - as rooted in the TTM Squeeze, quantifies the relationship between price and its extremes over a defined period. By normalizing the calculation, the values become comparable throughout time and across securities, allowing for a nuanced assessment of Bullish and Bearish momentum. Furthermore, by presenting it as a ribbon with a signal line we gain additional information about the direction of price swings.
Squeeze Bars - The original squeeze concept is based on the relationship between the Bollinger Bands and Keltner Channel , once the BB resides inside the KC a squeeze occurs. By understanding their fundamentals a new form of calculation can be inferred.
method bb(float src, simple int len, simple float mult) => method kc(float src, simple int len, simple float mult) =>
float basis = ta.sma (src, len) float basis = ta.sma (src, len)
float dev = ta.stdev(src, len) float rng = ta.atr ( len)
float upper = basis + dev * mult float upper = basis + rng * mult
float lower = basis - dev * mult float lower = basis - rng * mult
Both BB and KC are constructed upon a moving average with the addition of Standard Deviation and Average True Range respectively. Therefore, the calculation can be transformed to when the Stdev is lower than the ATR a squeeze occurs.
method sqz(float src, simple int len) =>
float dev = ta.stdev(src, len)
float atr = ta.atr ( len)
dev < atr ? true : false
This indicator uses three different thresholds for the ATR to gain three levels of price "Squeeze" for further analysis.
Directional Flux- This component measures the overall direction of price volatility, offering insights into trend sentiment. Presented as waves in the background, it includes an OverFlux feature to signal extreme market bias in a particular direction which can signal either exhaustion or vital continuation. Additionally, the user can choose if to base the calculation on Heikin-Ashi Candles to bias the tool toward trend assessment.
Confluence Gauges - Placed at the top and bottom of the indicator, these gauges measure confluence in the relationship between the Momentum Oscillator and Directional Flux. They provide traders with an easily interpretable visual aid for detecting market sentiment. Reversal doritos displayed alongside them contribute to mean reversion analysis.
Divergences (Real-Time) - Equipped with a custom algorithm, the indicator detects real-time divergences between price and the oscillator. This dynamic feature enhances your ability to spot potential trend reversals as they occur.
🔲 Settings
Directional Flux Length - Adjusts the period of which the background volatility waves operate on.
Trend Bias - Bases the calculation of the Flux to HA candles to bias its behavior toward the trend of price action.
Squeeze Momentum Length - Calibrates the length of the main oscillator ribbon as well as the period for the squeeze algorithm.
Signal - Controls the width of the ribbon. Lower values result in faster responsiveness at the cost of premature positives.
Divergence Sensitivity - Adjusts a threshold to limit the amount of divergences detected based on strength. Higher values result in less detections, stronger structure.
🔲 Alerts
Sell Signal
Buy Signal
Bullish Momentum
Bearish Momentum
Bullish Flux
Bearish Flux
Bullish Swing
Bearish Swing
Strong Bull Gauge
Strong Bear Gauge
Weak Bull Gauge
Weak Bear Gauge
High Squeeze
Normal Squeeze
Low Squeeze
Bullish Divergence
Bearish Divergence
As well as the option to trigger 'any alert' call.
The Squeeze Momentum Deluxe is a comprehensive tool that goes beyond traditional momentum indicators, offering a rich set of features to elevate your trading strategy. I recommend using toolkit alongside other indicators to have a wide variety of confluence to therefore gain higher probabilistic and better informed decisions.
Bandwidth Volatility - Silverman Rule of thumb EstimatorOverview
This indicator calculates volatility using the Rule of Thumb bandwidth estimator and incorporating the standard deviations of returns to get historical volatility. There are two options: one for the original rule of thumb bandwidth estimator, and another for the modified rule of thumb estimator. This indicator comes with the bandwidth , which is shown with the color gradient columns, which are colored by a percentile of the bandwidth, and the moving average of the bandwidth, which is the dark shaded area.
The rule of thumb bandwidth estimator is a simple and quick method for estimating the bandwidth parameter in kernel density estimation (KSE) or kernel regression. It provides a rough approximation of the bandwidth without requiring extensive computation resources or fine-tuning. One common rule of thumb estimator is Silverman rule, which is given by
h = 1.06*σ*n^(-1/5)
where
h is the bandwidth
σ is the standard deviation of the data
n is the number of data points
This rule of thumb is based on assuming a Gaussian kernel and aims to strike a balance between over-smoothing and under-smoothing the data. It is simple to implement and usually provides reasonable bandwidth estimates for a wide range of datasets. However , it is important to note that this rule of thumb may not always have optimal results, especially for non-Gaussian or multimodal distributions. In such cases, a modified bandwidth selection, such as cross-validation or even applying a log transformation (if the data is right-skewed), may be preferable.
How it works:
This indicator computes the bandwidth volatility using returns, which are used in the standard deviation calculation. It then estimates the bandwidth based on either the Silverman rule of thumb or a modified version considering the interquartile range. The percentile ranks of the bandwidth estimate are then used to visualize the volatility levels, identify high and low volatility periods, and show them with colors.
Modified Rule of thumb Bandwidth:
The modified rule of thumb bandwidth formula combines elements of standard deviations and interquartile ranges, scaled by a multiplier of 0.9 and inversely with a number of periods. This modification aims to provide a more robust and adaptable bandwidth estimation method, particularly suitable for financial time series data with potentially skewed or heavy-tailed data.
Formula for Modified Rule of Thumb Bandwidth:
h = 0.9 * min(σ, (IQR/1.34))*n^(-1/5)
This modification introduces the use of the IQR divided by 1.34 as an alternative to the standard deviation. It aims to improve the estimation, mainly when the underlying distribution deviates from a perfect Gaussian distribution.
Analysis
Rule of thumb Bandwidth: Provides a broader perspective on volatility trends, smoothing out short-term fluctuations and focusing more on the overall shape of the density function.
Historical Volatility: Offers a more granular view of volatility, capturing day-to-day or intra-period fluctuations in asset prices and returns.
Modelling Requirements
Rule of thumb Bandwidth: Provides a broader perspective on volatility trends, smoothing out short-term fluctuations and focusing more on the overall shape of the density function.
Historical Volatility: Offers a more granular view of volatility, capturing day-to-day or intra-period fluctuations in asset prices and returns.
Pros of Bandwidth as a volatility measure
Robust to Data Distribution: Bandwidth volatility, especially when estimated using robust methods like Silverman's rule of thumb or its modifications, can be less sensitive to outliers and non-normal distributions compared to some other measures of volatility
Flexibility: It can be applied to a wide range of data types and can adapt to different underlying data distributions, making it versatile for various analytical tasks.
How can traders use this indicator?
In finance, volatility is thought to be a mean-reverting process. So when volatility is at an extreme low, it is expected that a volatility expansion happens, which comes with bigger movements in price, and when volatility is at an extreme high, it is expected for volatility to eventually decrease, leading to smaller price moves, and many traders view this as an area to take profit in.
In the context of this indicator, low volatility is thought of as having the green color, which indicates a low percentile value, and also being below the moving average. High volatility is thought of as having the yellow color and possibly being above the moving average, showing that you can eventually expect volatility to decrease.
Bandwidth Bands - Silverman's rule of thumbWhat are Bandwidth Bands?
This indicator uses Silverman Rule of Thumb Bandwidth to estimate the width of bands around the rolling moving average which takes in the log transformation of price to remove most of price skewness for the rest of the volatility calculations and then a exp() function is performed to convert it back to a right skewed distribution. These bandwidths bands could offer insights into price volatility and trading extremes.
Silverman rule of thumb bandwidth:
The Silverman Rule of Thumb Bandwidth is a heuristic method used to estimate the optimal bandwidth for kernel density estimation, a statistical technique for estimating the probability density function of a random variable. In the context of financial analysis, such as in this indicator, it helps determine the width of bands around a moving average, providing insights into the level of volatility in the market. This method is particularly useful because it offers a quick and straightforward way to estimate bandwidth without requiring extensive computational resources or complex mathematical calculation
The bandwidth estimator automatically adjust to the characteristics of the data, providing a flexible and dynamic measure of dispersion that can capture variations in volatility over time. Standard deviations alone may not be as adaptive to changes in data distributions. The Bandwidth considers the overall shape and structure of the data distribution rather than just focusing on the spread of data points.
Settings
Source
Sample length
1-4 SD options to disable or enable each band
GARCH Volatility Estimation - The Quant ScienceThe GARCH (Generalized Autoregressive Conditional Heteroskedasticity) model is a statistical model used to forecast the volatility of a financial asset. This model takes into account the fluctuations in volatility over time, recognizing that volatility can vary in a heteroskedastic (i.e., non-constant variance) manner and can be influenced by past events.
The general formula of the GARCH model is:
σ²(t) = ω + α * ε²(t-1) + β * σ²(t-1)
where:
σ²(t) is the conditional variance at time t (i.e., squared volatility)
ω is the constant term (intercept) representing the baseline level of volatility
α is the coefficient representing the impact of the squared lagged error term on the conditional variance
ε²(t-1) is the squared lagged error term at the previous time period
β is the coefficient representing the impact of the lagged conditional variance on the current conditional variance
In the context of financial forecasting, the GARCH model is used to estimate the future volatility of the asset.
HOW TO USE
This quantitative indicator is capable of estimating the probable future movements of volatility. When the GARCH increases in value, it means that the volatility of the asset will likely increase as well, and vice versa. The indicator displays the relationship of the GARCH (bright red) with the trend of historical volatility (dark red).
USER INTERFACE
Alpha: select the starting value of Alpha (default value is 0.10).
Beta: select the starting value of Beta (default value is 0.80).
Lenght: select the period for calculating values within the model such as EMA (Exponential Moving Average) and Historical Volatility (default set to 20).
Forecasting: select the forecasting period, the number of bars you want to visualize data ahead (default set to 30).
Design: customize the indicator with your preferred color and choose from different types of charts, managing the design settings.
Squeeze & Release [AlgoAlpha]Introduction:
💡The Squeeze & Release by AlgoAlpha is an innovative tool designed to capture price volatility dynamics using a combination of EMA-based calculations and ATR principles. This script aims to provide traders with clear visual cues to spot potential market squeezes and release scenarios. Hence it is important to note that this indicator shows information on volatility, not direction.
Core Logic and Components:
🔶EMA Calculations: The script utilizes the Exponential Moving Average (EMA) in multiple ways to smooth out the data and provide indicator direction. There are specific lengths for the EMAs that users can modify as per their preference.
🔶ATR Dynamics: Average True Range (ATR) is a core component of the script. The differential between the smoothed ATR and its EMA is used to plot the main line. This differential, when represented as a percentage of the high-low range, provides insights into volatility.
🔶Squeeze and Release Detection: The script identifies and highlights squeeze and release scenarios based on the crossover and cross-under events between our main line and its smoothed version. Squeezes are potential setups where the market may be consolidating, and releases indicate a potential breakout or breakdown.
🔶Hyper Squeeze Detection: A unique feature that detects instances when the main line is rising consistently over a user-defined period. Hyper squeeze marks areas of extremely low volatility.
Visual Components:
The main line (ATR-based) changes color depending on its position relative to its EMA.
A middle line plotted at zero level which provides a quick visual cue about the main line's position. If the main line is above the zero level, it indicates that the price is squeezing on a longer time horizon, even if the indicator indicates a shorter-term release.
"𝓢" and "𝓡" characters are plotted to represent 'Squeeze' and 'Release' scenarios respectively.
Standard Deviation Bands are plotted to help users gauge the extremity and significance of the signal from the indicator, if the indicator is closer to either the upper or lower deviation bands, this means that statistically, the current value is considered to be more extreme and as it is further away from the mean where the indicator is oscillating at for the majority of the time. Thus indicating that the price has experienced an unusual amount or squeeze or release depending on the value of the indicator.
Usage Guidelines:
☝️Traders can use the script to:
Identify potential consolidation (squeeze) zones.
Gauge potential breakout or breakdown scenarios (release).
Fine-tune their entries and exits based on volatility.
Adjust the various lengths provided in the input for better customization based on individual trading styles and the asset being traded.
SuperTrend ToolkitThe SuperTrend Toolkit (Super Kit) introduces a versatile approach to trend analysis by extending the application of the SuperTrend indicator to a wide array of @TradingView's built-in or Community Scripts . This tool facilitates the integration of the SuperTrend algorithm with various indicators, including oscillators, moving averages, overlays, and channels.
Methodology:
The SuperTrend, at its core, calculates a trend-following indicator based on the Average-True-Range (ATR) and price action. It creates dynamic support and resistance levels, adjusting to changing market conditions, and aiding in trend identification.
pine_st(simple float factor = 3., simple int length = 10) =>
float atr = ta.atr(length)
float up = hl2 + factor * atr
up := up < nz(up ) or close > nz(up ) ? up : nz(up )
float lo = hl2 - factor * atr
lo := lo > nz(lo ) or close < nz(lo ) ? lo : nz(lo )
int dir = na
float st = na
if na(atr )
dir := 1
else if st == nz(up )
dir := close > up ? -1 : 1
else
dir := close < lo ? 1 : -1
st := dir == -1 ? lo : up
@TradingView's native SuperTrend lacks the flexibility to incorporate different price sources into its calculation.
Community scripts, addressed the limitation by implementing the option to input different price sources, for example, one of the most popular publications, @KivancOzbilgic's SuperTrend script.
In May 2023, @TradingView introduced an update allowing the passing of another indicator's plot as a source value via the input.source() function. However, the built-in ta.atr function still relied on the chart's price data, limiting the formerly mentioned scripts to the chart's price data alone.
Unique Approach -
This script addresses the aforementioned limitations by processing the data differently.
Firstly we create a User-Defined-Type (UDT) replicating a bar's open, high, low, close (OHLC) values.
type bar
float o = open
float h = high
float l = low
float c = close
We then use this type to store the external input data.
src = input.source(close, "External Source")
bar b = bar.new(
nz(src ) , open 𝘷𝘢𝘭𝘶𝘦
math.max(nz(src ), src), high 𝘷𝘢𝘭𝘶𝘦
math.min(nz(src ), src), low 𝘷𝘢𝘭𝘶𝘦
src ) close 𝘷𝘢𝘭𝘶𝘦
Finally, we pass the data into our custom built SuperTrend with ATR functions to derive the external source's version of the SuperTrend indicator.
supertrend st = b.st(mlt, len)
- Setup Guide -
Utility and Use Cases:
Universal Compatibility - Apply SuperTrend to any built-in indicator or script, expanding its use beyond traditional price data.
- A simple example on one of my own public scripts -
Trend Analysis - Gain additional trend insights into otherwise mainly mean reverting or volume indicators.
- Alerts Setup Guide -
The Super Kit empowers traders and analysts with a tool that adapts the robust SuperTrend algorithm to a myriad of indicators, allowing comprehensive trend analysis and strategy development.
Williams Vix Fix [CC]The Vix Fix indicator was created by Larry Williams and is one of my giant backlog of unpublished scripts which I'm going to start publishing more of. This indicator is a great synthetic version of the classic Volatility Index and can be useful in combination with other indicators to determine when to enter or exit a trade due to the current volatility. The indicator creates this synthetic version of the Volatility Index by a fairly simple formula that subtracts the current low from the highest close over the last 22 days and then divides that result by the same highest close and multiplies by 100 to turn it into a percentage. The 22-day length is used by default since there is a max of 22 trading days in a month but this formula works well for any other timeframe. By itself, this indicator doesn't generate buy or sell signals but generally speaking, you will want to enter or exit a trade when the Vix fix indicator amount spikes and you get an entry or exit signal from another indicator of your choice. Keep in mind that the colors I'm using for this indicator are only a general idea of when volatility is high enough to enter or exit a trade so green colors mean higher volatility and red colors mean low volatility. This is one of the few indicators I have written that don't recommend to buy or sell when the colors change.
This was a custom request from one of my followers so please let me know if you guys have any other script requests you want to see!
Standardized SuperTrend Oscillator
The Standardized SuperTrend Oscillator (SSO) is a versatile tool that transforms the SuperTrend indicator into an oscillator, offering both trend-following and mean reversion capabilities. It provides deeper insights into trends by standardizing the SuperTrend with respect to its upper and lower bounds, allowing traders to identify potential reversals and contrarian signals.
Methodology:
Lets begin with describing the SuperTrend indicator, which is the fundamental tool this script is based on.
SuperTrend:
The SuperTrend is calculated based on the average true range (ATR) and multiplier. It identifies the trend direction by placing a line above or below the price. In an uptrend, the line is below the price; in a downtrend, it's above the price.
pine_st(float src = hl2, float factor = 3., simple int len = 10) =>
float atr = ta.atr(len)
float up = src + factor * atr
up := up < nz(up ) or close > nz(up ) ? up : nz(up )
float lo = src - factor * atr
lo := lo > nz(lo ) or close < nz(lo ) ? lo : nz(lo )
int dir = na
float st = na
if na(atr )
dir := 1
else if st == nz(up )
dir := close > up ? -1 : 1
else
dir := close < lo ? 1 : -1
st := dir == -1 ? lo : up
SSO Oscillator:
The SSO is derived from the SuperTrend and the source price. It calculates the standardized difference between the SuperTrend and the source price. The standardization is achieved by dividing this difference by the distance between the upper and lower bounds of the SuperTrend.
float sso = (src - st) / (up - lo)
Components and Features:
SuperTrend of Oscillator - An additional SuperTrend based on the direction and volatility of the oscillator, behaving as the SuperTrend OF the SuperTrend. This provides further trend analysis of the underlying broad trend regime.
Reversion Tracer - The RSI of the direction of the original SuperTrend, providing a dynamic threshold for premium and discount price areas.
float rvt = ta.rsi(dir, len)
Heikin Ashi Transform - An option to apply the Heikin Ashi transform to the source price of the oscillator, providing a smoother visual representation of trends.
Display Modes - Choose between Line mode for a standard oscillator view or Candle mode, displaying the oscillator as Heikin Ashi candles for more in-depth trend analysis.
Contrarian and Reversion Signals:
Contrarian Signals - Based on the SuperTrend of the oscillator, these signals can act as potential buy or sell indications, highlighting potential trend exhaustion or premature reversals.
Reversion Signals - Generated when the oscillator crosses above or below the Reversion Tracer, signaling potential mean reversion opportunities or trend breakouts.
Utility and Use Cases:
Trend Analysis - Utilize the SSO as a trend-following tool with the added benefits of the oscillator's SuperTrend and Heikin Ashi transform.
Valuation Analysis - Leverage the oscillator's reversion signals for identifying potential mean reversion opportunities in the market.
The Standardized SuperTrend Oscillator enhances the capabilities of the SuperTrend indicator, offering a balanced approach to both trend-following and mean reversion strategies. Its customizable options and contrarian signals make it a valuable instrument for traders seeking comprehensive trend analysis and potential reversal signals.
Volume-Price DiffScript is designed to analize volatility in real-time.
Once added to chart, script starting to collect 2 things:
Ticks count (tc)
Price changing ticks count (pctc)
The pctc/tc ratio may be interpret as a volatility measure.
Label above real-time bar shows:
Ticks count
Price changing ticks count
Ratio between (2) and (1) in percents
Using this indicator trader may detect volatility spikes.
More the "Diff" - less the volatility and vice versa.
Intraday Volatility Bands [Honestcowboy]The Intraday Volatility Bands aims to provide a better alternative to ATR in the calculation of targets or reversal points.
How are they different from ATR based bands?
While ATR and other measures of volatility base their calculations on the previous bars on the chart (for example bars 1954 to 1968). The volatility used in these bands measure expected volatility during that time of the day.
Why would you take this approach?
Markets behave different during certain times of the day, also called sessions.
Here are a couple examples.
Asian Session (generally low volatility)
London Session (bigger volatility starts)
New York Session (overlap of New York with London creates huge volatility)
Generally when using bands or channel type indicators intraday they do not account for the upcoming sessions. On London open price will quickly spike through a bollinger band and it will take some time for the bands to adjust to new volatility.
This script will show expected volatility targets at the start of each new bar and will not adjust during the bar. It already knows what price is expected to do at this time of day.
Script also plots arrows when price breaches either the top or bottom of the bands. You can also set alerts for when this occurs. These are non repainting as the script knows the level at start of the bar and does not change.
🔷 CALCULATION
Think of this script like an ATR but instead it uses past days data instead of previous bars data. Charts below should visualise this more clearly:
The scripts measure of volatility is based on a simple high-low.
The script also counts the number of bars that exist in a day on your current timeframe chart. After knowing that number it creates the matrix used in it's calculations and data storage.
See how it works perfectly on a lower timeframe chart below:
Getting this right was the hardest part, check the coding if you are interested in this type of stuff. I commented every step in the coding process.
🔷 SETTINGS
Every setting of the script has a tooltip but I provided a breakdown here:
Some more examples of different charts:
TrendCylinder (Expo)█ Overview
The TrendCylinder is a dynamic trading indicator designed to capture trends and volatility in an asset's price. It provides a visualization of the current trend direction and upper and lower bands that adapt to volatility changes. By using this indicator, traders can identify potential breakouts or support and resistance levels. While also gauging the volatility to generate trading ranges. The indicator is a comprehensive tool for traders navigating various market conditions by providing a sophisticated blend of trend-following and volatility-based metrics.
█ How It Works
Trend Line: The trend line is constructed using the closing prices with the influence of volatility metrics. The trend line reacts to sudden price changes based on the trend factor and step settings.
Upper & Lower Bands: These bands are not static; they are dynamically adjusted with the calculated standard deviation and Average True Range (ATR) metrics to offer a more flexible, real-world representation of potential price movements, offering an idea of the market's likely trading range.
█ How to Use
Identifying Trends
The trend line can be used to identify the current market trend. If the price is above the trend line, it indicates a bullish trend. Conversely, if the price is below the trend line, it indicates a bearish trend.
Dynamic Support and Resistance
The upper and lower bands (including the trend line) dynamically change with market volatility, acting as moving targets of support and resistance. This helps set up stop-loss or take-profit levels with a higher degree of accuracy.
Breakout vs. Reversion Strategies
Price movements beyond the bands could signify strong trends, making it ideal for breakout strategies.
Fakeouts
If the price touches one of the bands and reverses direction, it could be a fakeout. Traders may choose to trade against the breakout in such scenarios.
█ Settings
Volatility Period: Defines the look-back period for calculating volatility. Higher values adapt the bands more slowly, whereas lower values adapt them more quickly.
Trend Factor: Adjusts the sensitivity of the trend line. Higher values produce a smoother line, while lower values make it more reactive to price changes.
Trend Step: Controls the pace at which the trend line adjusts to sudden price movements. Higher values lead to a slower adjustment and a smoother line, while lower values result in quicker adjustments.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
VWMA/SMA Delta Volatility (Statistical Anomaly Detector)The "VWMA/SMA Delta Volatility (Statistical Anomaly Detector)" indicator is a tool designed to detect and visualize volatility in a financial market's price data. The indicator calculates the difference (delta) between two moving averages (VWMA/SMA) and uses statistical analysis to identify anomalies or extreme price movements. Here's a breakdown of its components:
Hypothesis:
The hypothesis behind this indicator is that extreme price movements or anomalies in the market can be detected by analyzing the difference between two moving averages and comparing it to a statistically derived normal distribution. When the MA delta (the difference between two MAs: VWMA/SMA) exceeds a certain threshold based on standard deviation and the Z-score coefficient, it may indicate increased market volatility or potential trading opportunities.
Calculation of MA Delta:
The indicator calculates the MA delta by subtracting a simple moving average (SMA) from a volume-weighted moving average (VWMA) of a selected price source. This calculation represents the difference in the market's short-term and long-term trends.
Statistical Analysis:
To detect anomalies, the indicator performs statistical analysis on the MA delta. It calculates a moving average (MA) of the MA delta and its standard deviation over a specified sample size. This MA acts as a baseline, and the standard deviation is used to measure how much the MA delta deviates from the mean.
Delta Normalization:
The MA delta, lower filter, and upper filter are normalized using a function that scales them to a specific range, typically from -100 to 100. Normalization helps in comparing these values on a consistent scale and enhances their visual representation.
Visual Representation:
The indicator visualizes the results through histograms and channels:
The histogram bars represent the normalized MA delta. Red bars indicate negative and below-lower-filter values, green bars indicate positive and above-upper-filter values, and silver bars indicate values within the normal range.
It also displays a Z-score channel, which represents the upper and lower filters after normalization. This channel helps traders identify price levels that are statistically significant and potentially indicative of market volatility.
In summary, the "MA Delta Volatility (Statistical Anomaly Detector)" indicator aims to help traders identify abnormal price movements in the market by analyzing the difference between two moving averages and applying statistical measures. It can be a valuable tool for traders looking to spot potential opportunities during periods of increased volatility or to identify potential market anomalies.
Grid by Volatility (Expo)█ Overview
The Grid by Volatility is designed to provide a dynamic grid overlay on your price chart. This grid is calculated based on the volatility and adjusts in real-time as market conditions change. The indicator uses Standard Deviation to determine volatility and is useful for traders looking to understand price volatility patterns, determine potential support and resistance levels, or validate other trading signals.
█ How It Works
The indicator initiates its computations by assessing the market volatility through an established statistical model: the Standard Deviation. Following the volatility determination, the algorithm calculates a central equilibrium line—commonly referred to as the "mid-line"—on the chart to serve as a baseline for additional computations. Subsequently, upper and lower grid lines are algorithmically generated and plotted equidistantly from the central mid-line, with the distance being dictated by the previously calculated volatility metrics.
█ How to Use
Trend Analysis: The grid can be used to analyze the underlying trend of the asset. For example, if the price is above the Average Line and moves toward the Upper Range, it indicates a strong bullish trend.
Support and Resistance: The grid lines can act as dynamic support and resistance levels. Price tends to bounce off these levels or breakthrough, providing potential trade opportunities.
Volatility Gauge: The distance between the grid lines serves as a measure of market volatility. Wider lines indicate higher volatility, while narrower lines suggest low volatility.
█ Settings
Volatility Length: Number of bars to calculate the Standard Deviation (Default: 200)
Squeeze Adjustment: Multiplier for the Standard Deviation (Default: 6)
Grid Confirmation Length: Number of bars to calculate the weighted moving average for smoothing the grid lines (Default: 2)
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Intraday Volatility BarsThis script produce a volatility histrogram by bar with the current volatility overlayed.
The histogram shows cumulative average volatility over n days.
And the dots are todays cumulative volatility.
In other words, it calculates the True Range of each bar and adds it to todays value.
This script is build for intraday timeframes between one and 1440 minutes only.
I use this to show me when volatility is above/below/equal to the average volatility.
When the dots are above the histogram then it is a more volatile day, and vice versa.
Recognizing a more volatile day as early as possible can be an advantage for daytrader.
Days that start with higher volatility seems to continue to increase relative to the past few days. Or when midday volatility rises it seems to continue as well.
Happy Trading!
Bollinger Band Percentile SuiteThe Bollinger Band Percentile Suite (𝐵𝐵𝒫𝒸𝓉 𝒮𝓊𝒾𝓉𝑒) is a comprehensive and customizable toolkit built upon the foundation of the %B indicator. The methodology behind this toolkit remains consistent with the original %B indicator, while introducing a host of powerful features to enhance its functionality and adaptability.
Key Features and Customization:
The 𝐵𝐵𝒫𝒸𝓉 offers a wide array of customizable options to suit your trading preferences and strategies. It includes a variety of 14 moving average types that can be chosen as the basis for the Bollinger Band calculation. Additionally, traders have the flexibility to set their upper and lower boundaries for mean reversion detection, allowing for analysis tailored to the user's preference.
Deviation Calculation:
The toolkit provides an option to choose between standard and weighted deviation calculation methods. This added customization ensures that the indicator's behavior aligns with your unique trading style and preferences.
Signals and Reversals:
The 𝐵𝐵𝒫𝒸𝓉 excels in identifying potential overbought and oversold market conditions. It highlights these levels on the chart and marks potential reversal signals with small circles positioned either at the top or bottom of the indicator pane, providing traders with actionable insights.
Trend and Color Coding:
Incorporating a color-coded approach, the BBpct Suite enhances your understanding of market dynamics. It offers bar coloring options based on trend, allowing traders to identify bullish or bearish market conditions as the percentile goes above or below the midline.
Extremities and Reversions:
Recognizing extreme market conditions is crucial for traders. The 𝐵𝐵𝒫𝒸𝓉 includes color-coded indicators for extremities, indicating when the percentile ventures above or below the predefined thresholds. Moreover, it promptly identifies reversions by marking the moment the percentile crosses under the upper threshold (overbought) or over the lower threshold (oversold).
The Bollinger Band Percentile Suite equips traders with a versatile toolkit to gain valuable insights into market overbought and oversold conditions, and potential reversal signals. Its extensive customization options and array of features empower traders to make well-informed decisions based on their unique trading strategies and risk tolerance.
Please note that while the BBpct Suite provides robust analysis, it is advisable to combine its insights with other technical indicators and tools for a comprehensive trading approach.
Example Chart:
ATR DeltaThe ATR Delta indicator is based on the concept of Average True Range (ATR), which reflects the average price range over a specified period. By calculating the difference between current and previous ATR values, the ATR Delta provides valuable insights into volatility shifts in the market. This information can help traders identify periods of heightened or diminished price movement, enabling them to adjust their strategies accordingly.
The ATR Delta indicator consists of two main calculations:
-- ATR Calculation : The Average True Range (ATR) is calculated using the specified length parameter. It measures the average price range (including gaps) during that period. A larger ATR value indicates higher volatility, while a smaller value indicates lower volatility.
-- ATR Delta Calculation : The ATR Delta is calculated by subtracting the ATR value of the previous bar from the current ATR value. This calculation captures the change in volatility between the two periods, providing a measure of how volatility has evolved.
Positive ATR Delta values indicate an increase in volatility compared to the previous period. It suggests that price movements have expanded, potentially indicating a more active market. On the other hand, negative ATR Delta values indicate a decrease in volatility compared to the previous period. It suggests that price movements have contracted, potentially signaling a calmer or range-bound market.
The ATR Delta indicator uses coloration to visually represent the relationship between the ATR Delta, zero, and a signal line:
-- Green color is assigned when the ATR Delta is positive, above the signal line, and increasing. This coloration suggests a scenario of higher volatility, as the market is experiencing upward momentum in price swings.
-- Red color is assigned when the ATR Delta is negative, below the signal line, and decreasing. This coloration suggests a scenario of lower volatility, as the market is experiencing downward momentum in price swings.
-- Gray color is assigned for other cases when the ATR Delta and signal line relationship does not meet the above conditions.
These colors are reflected in the columns of the ATR Delta as well as the bar coloration.
The ATR Delta indicator includes a signal line, which acts as a reference for interpreting the ATR Delta values. The signal line is calculated as a moving average (EMA) of the ATR Delta over a specified length. It helps smooth out the ATR Delta fluctuations, providing a clearer indication of the underlying trend in volatility changes. When the ATR Delta crosses above the signal line, it may suggest a potential increase in volatility, indicating a market that is becoming more active. Conversely, when the ATR Delta crosses below the signal line, it may suggest a potential decrease in volatility, indicating a market that is becoming less active.
The coloration of the signal line in the ATR Delta indicator helps to differentiate between positive and negative values and provides further insight into market sentiment. When the signal line is positive, indicating increasing volatility, it is colored lime. This color choice reinforces the bullish sentiment and signifies potential opportunities for trend continuation or breakouts. On the other hand, when the signal line is negative, indicating decreasing volatility, it is colored fuchsia. This color choice highlights the bearish sentiment and suggests potential range-bound or consolidation periods. These colors are reflected in the background of the indicator.
The ATR Delta indicator offers several potential applications for traders:
-- Volatility Analysis : The ATR Delta is invaluable for understanding and analyzing volatility dynamics in the market. Traders can observe the changes in ATR Delta values and use them to assess the current level of price movement. This information can help determine the appropriate strategies and risk management approaches.
-- Breakout Strategies : Traders often use the ATR Delta to identify periods of increased volatility, which frequently accompany breakouts. By monitoring the ATR Delta, traders can anticipate potential price breakouts and adjust their entry and exit levels accordingly.
-- Trend Confirmation : Combining the ATR Delta with trend-following indicators allows traders to validate the strength of a trend. Higher ATR Delta values during an uptrend may indicate stronger momentum and a higher likelihood of continuation. Conversely, lower ATR Delta values during a downtrend may suggest a potential consolidation phase or trend reversal.
Limitations :
-- Lagging Indicator : The ATR Delta indicator is based on historical data and calculates the difference between current and previous ATR values. As a result, it may lag behind real-time market conditions. Traders should be aware of this delay and consider it when making trading decisions. It is advisable to combine the ATR Delta with other indicators or price action analysis for a more comprehensive assessment of market conditions.
-- Parameter Sensitivity : The ATR Delta indicator's effectiveness can be influenced by the selection of its parameters, such as the length of the ATR and signal line. Different market conditions may require adjustments to these parameters to better capture volatility changes. Traders should carefully test and optimize the indicator's parameters to align with the characteristics of the specific market or asset they are trading.
-- Market Regime Changes : The ATR Delta indicator assumes that volatility changes occur gradually. However, in rapidly changing market regimes or during news events, volatility can spike or drop abruptly, potentially rendering the indicator less effective. Traders should exercise caution and consider using additional tools or techniques to identify and adapt to such market conditions.
The ATR Delta indicator is a valuable tool for traders seeking to analyze and monitor volatility dynamics in the market. By calculating the difference between current and previous ATR values, it provides insights into changes in price movement and helps identify periods of increased or decreased volatility. Traders can leverage the ATR Delta to fine-tune their strategies, validate trend strength, and identify potential breakout opportunities. However, it is essential to recognize the limitations of the indicator, including its lagging nature and sensitivity to parameter selection. By combining the ATR Delta with other technical analysis tools and applying sound risk management practices, traders can enhance their decision-making process and potentially improve their trading outcomes.
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:
VolatilityThis script shows three different calculations for volatility.
All three can be used as Stop-Loss...
- Absolute Price Changes
- Maximum Price Fluctuation
- and every one should know Average True Range
The script has a dark and light theme.
And the colors can be changed and each can be deactivated.
On top of that I stumbled over the fact that when MPF crosses over APC
this could result in a significant change in price and could also be used as an entry or exit.
This is also highlighted by default. You can change its background color and you can deactivate it too.
ACP measures volatility over most recent close prices.
This is excellent for comparing volatility.
It includes both frequency and magnitude.
In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
MPF measures volatility over most recent candles, which could be used as an estimate of risk.
It may also be effective as the basis for a stop-loss or take-profit,
like the ATR but it ignores the frequency of directional changes within the time interval.
In other words: The difference between the highest high and lowest low over 'n' bars.
When you don't know what the ATR is then you can look at this link .
Volatility-Based Mean Reversion BandsThe Volatility-Based Mean Reversion Bands indicator is a powerful tool designed to identify potential mean reversion trading opportunities based on market volatility. The indicator consists of three lines: the mean line, upper band, and lower band. These bands dynamically adjust based on the average true range (ATR) and act as reference levels for identifying overbought and oversold conditions.
The calculation of the indicator involves several steps. The average true range (ATR) is calculated using a specified lookback period. The ATR measures the market's volatility by considering the range between high and low prices over a given period. The mean line is calculated as a simple moving average (SMA) of the closing prices over the same lookback period. The upper band is derived by adding the product of the ATR and a multiplier to the mean line, while the lower band is derived by subtracting the product of the ATR and the same multiplier from the mean line.
Interpreting the indicator is relatively straightforward. When the price approaches or exceeds the upper band, it suggests that the market is overbought and may be due for a potential reversal to the downside. On the other hand, when the price approaches or falls below the lower band, it indicates that the market is oversold and may be poised for a potential reversal to the upside. Traders can look for opportunities to enter short positions near the upper band and long positions near the lower band, anticipating the price to revert back towards the mean line.
The bar color and background color play a crucial role in visualizing the indicator's signals and market conditions. Lime-colored bars are used when the price is above the upper band, indicating a potential bearish mean reversion signal. Conversely, fuchsia-colored bars are employed when the price is below the lower band, suggesting a potential bullish mean reversion signal. This color scheme helps traders quickly identify the prevailing market condition and potential reversal zones. The background color complements the bar color by providing further context. Lime-colored background indicates a potential bearish condition, while fuchsia-colored background suggests a potential bullish condition. The transparency level of the background color is set to 80% to avoid obscuring the price chart while still providing a visual reference.
To provide additional confirmation for mean reversion setups, the indicator incorporates the option to use the Relative Strength Index (RSI) as a confluence factor. The RSI is a popular momentum oscillator that measures the speed and change of price movements. When enabled, the indicator checks if the RSI is in overbought territory (above 70) or oversold territory (below 30), providing additional confirmation for potential mean reversion setups.
In addition to visual signals, the indicator includes entry arrows above or below the bars to highlight the occurrence of short or long entries. When the price is above the upper band and the confluence condition is met, a fuchsia-colored triangle-up arrow is displayed above the bar, indicating a potential short entry signal. Similarly, when the price is below the lower band and the confluence condition is met, a lime-colored triangle-down arrow is displayed below the bar, indicating a potential long entry signal.
Traders can customize the indicator's parameters according to their trading preferences. The "Lookback Period" determines the number of periods used in calculating the mean line and the average true range (ATR). Adjusting this parameter can affect the sensitivity and responsiveness of the indicator. Smaller values make the indicator more reactive to short-term price movements, while larger values smooth out the indicator and make it less responsive to short-term fluctuations. The "Multiplier" parameter determines the distance between the mean line and the upper/lower bands. Increasing the multiplier widens the bands, indicating a broader range for potential mean reversion opportunities, while decreasing the multiplier narrows the bands, indicating a tighter range for potential mean reversion opportunities.
It's important to note that the Volatility-Based Mean Reversion Bands indicator is not a standalone trading strategy but rather a tool to assist traders in identifying potential mean reversion setups. Traders should consider using additional analysis techniques and risk management strategies to make informed trading decisions. Additionally, the indicator's performance may vary across different market conditions and instruments, so it's advisable to conduct thorough testing and analysis before integrating it into a trading strategy.
Daily Factor Indicator [CC]The Daily Factor Indicator was created by Andrea Unger (Stocks and Commodities Jun 2023 pgs 26-31), and this is a new volatility indicator that compares the body, which is the absolute difference between the previous open and previous close, and the range which is the difference between the previous high and previous low. The indicator is calculated by dividing the body and range to determine the volatility for the previous bar. This indicator will range between 0 and 1. Values closer to 1 mean very high volatility, and values closer to 0 mean very low volatility. I have introduced a simple moving average strategy to decide buy or sell signals and colors. Darker colors mean the indicator is above the threshold level, and lighter colors mean the indicator is below the threshold level. Colors are shades of green when the price is above the moving average and shades of red when the price is below the moving average. Feel free to try out your own threshold level and general buy and sell signals.
Let me know if there are any other indicators you would like me to publish!